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 |
---|---|---|---|---|---|---|---|---|
797 |
hey guys welcome back to another video and today we're going to be solving the lead code question all paths from source to target so before i get started with the question uh if there's any lead code question you want me to solve specifically just let me know down in the comments and i'll try to get it solved for you all right anyway so in this question we're given a directed acyclic graph of n nodes we need to find all the possible paths from node 0 to node n minus 1 and return them in any order so the graph is as follows so okay anyways so we're given this as an input and i know this looks kind of confusing so let's just break it down and let's first understand what does the input actually mean and what do we need to really output in this question all right so this is the input that we're given and let's try to understand what this actually means so to do that what we need to do is let's uh first write down where the index each element is at so one comma two is at the index zero three is at the index one this is at the index two and this is at the index three so each of these indices represents the node so at index zero so zero that is connected to node one and two so 0 connects to 1 and 2. similarly node 1 over here because this is the index 1 connects to number 3. so we're going to connect that two three similarly the second node is also connected to three and the third node has nothing it's an empty list so that means that it's not connecting to anything so this is the graph that we're gonna have so this is what the input actually means now let's try to understand what does the question want from us so what the question is asking is we need to find all possible ways to get from zero to the last node so the last node is nothing else but n minus one so in this case that's going to be three so we need to get from zero to 3. and what does n minus 1 mean it's just the length of our input minus 1. so our input has a length of 4 so 4 minus 1. that's it all right so we need to find all the ways that we can get from zero all the way to three so let's look at the first way all right so now we're going to start at zero and we can either go to two or we can go to one so let's just go to two in the beginning so now we went to two and from 2 to get to 3 there's only one way 2 to 3. so what did we do we started off at 0 we went to 2 and from 2 we went to 3. so this is going to be one of our answers now let's look at our second answer so instead of going to two we can go to one from zero we can go to one and from one we can go to three so that's our second solution so we have zero comma one comma 3 and these are going to be our two solutions and this is what we're going to output so now how can we actually solve this so to solve this we can take two approaches we can take a depth-first approaches we can take a depth-first approaches we can take a depth-first approach or a breadth-first approach or a breadth-first approach or a breadth-first approach so in order to solve this question we're going to be taking a breadth first search approach so let's see how we can do that so over here i'm going to have our results right and we're also going to implement a q in order to solve this all right so now that we have this we're first gonna add our q is gonna start off with having a zero and each for each time we're gonna pop out that element and before we pop it out we're gonna check if the last element is equal to our target so what is our target is the length of our input minus one so four minus one which equals to three so you see if the last element of whatever we pop out is equal to zero so we're going to pop this out and is 0 equal to 3 obviously not so now what we're going to do since it's not equal to 3 we're not going to do anything to results but we're going to look for zeros neighbors so first let's look at its first neighbor it one of its neighbors is one zero to one right so we're going to add that to our q zero comma one so does it have any other neighbors it does it has 0 and 2. so 0 is connected to 2. so we're going to add that to our q as well 0 comma 2. now again now we're going to go back to our queue and we're going to check if the last element is equal to 3 and over here 1 is not equal to 3. so we're going to pop this out and now we're going to look for its name we're going to look for the last elements neighbors so we're looking for one's neighbors so in this case 1 is pointing to 3. so we're going to add that to our queue so we're going to add 0 comma 1 comma 3. all right so we got this added similarly we're going to go to 0 comma 2 again 2 is not equal to 3 so we're going to look for two's neighbors which is 3 and then we're going to add that to our q again so 0 comma 2 comma 3. now when we go when we pop this element out what happens is the last element is equal to 3 so that means that we've reached from this beginning to our target so we're going to add this to our results so to our results we're going to add 0 comma 1 comma 3. similarly we're going to pop this element out as well and then the last element is also 3. so we're going to add that again so 0 comma 2 comma 3. so and now there's nothing else inside of our q and we're done with the question and this is the answer that we have so now let's implement this in python and let's see how that looks like so we're going to start off with initializing our queue so our queue is going to have a list it's going to be a list and the first element is going to be a list with the value of zero so that's how our queue is gonna start off and we're gonna also initialize a result which is gonna be an empty list and we're gonna have our target which is nothing else but the length of the graph minus one okay so now we're gonna put it inside of a while loop which is gonna keep going until uh we have a value in our q so while q is not equal to none we're gonna go inside of our while loop over here we're gonna set a temporary variable so this is gonna just be whatever we pop out so q dot pop and then we're gonna pop out the zeroth element you could also implement a dq from collections but i'm just going to do this for now all right so now we're going to check if the last element of that temporary variable or whatever we popped out is equal to our target so if temp now the last element is at the index of negative one is equal to target then in that case we're going to add that to our results target okay so now result dot append and then we're gonna add that temporary variable all right else so if that is not the case what we need to do is we need to look for its neighbors and how can we do that so let me just write it down and then i'll explain it so for neighbor in graph so we're going to our graph over here and we're going to look at the whatever is at the last index so temp negative one so this is what was pop was the last element of what we popped out and we want to look for those for its neighbors and the best way to do that is we go to that index in the graph so that's how we get all of its neighbors so now we have all of its neighbors and we're going to add that to our queue so q dot append we're going to add the temporary variable plus the neighbor inside of a list okay so now that we have that we're going to go we're going to keep going inside of our while loop until we have nothing left inside our queue and once we exit that we're going to return our result all right so let's submit this and see what happens right and as you can see our submission did get accepted and finally again if there is any question you want me to solve specifically just let me know in the comments and i'll try to solve it and thanks a lot for watching and do let me know what you thought about the video thank you
|
All Paths From Source to Target
|
rabbits-in-forest
|
Given a directed acyclic graph (**DAG**) of `n` nodes labeled from `0` to `n - 1`, find all possible paths from node `0` to node `n - 1` and return them in **any order**.
The graph is given as follows: `graph[i]` is a list of all nodes you can visit from node `i` (i.e., there is a directed edge from node `i` to node `graph[i][j]`).
**Example 1:**
**Input:** graph = \[\[1,2\],\[3\],\[3\],\[\]\]
**Output:** \[\[0,1,3\],\[0,2,3\]\]
**Explanation:** There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
**Example 2:**
**Input:** graph = \[\[4,3,1\],\[3,2,4\],\[3\],\[4\],\[\]\]
**Output:** \[\[0,4\],\[0,3,4\],\[0,1,3,4\],\[0,1,2,3,4\],\[0,1,4\]\]
**Constraints:**
* `n == graph.length`
* `2 <= n <= 15`
* `0 <= graph[i][j] < n`
* `graph[i][j] != i` (i.e., there will be no self-loops).
* All the elements of `graph[i]` are **unique**.
* The input graph is **guaranteed** to be a **DAG**.
| null |
Array,Hash Table,Math,Greedy
|
Medium
| null |
1,059 |
hello friends now list of the Oh party from source to destination let's see a statement given the ages of a directed graph and the two North's source and the destination of this graph determining whether or not a party starting from souls eventually end at destination there is at least one person exists from the source node to the destination node if a purse exists from the source know that you are noted with no outgoing ages then the node is eager to destination the number of possible purses from source to destination is a return true if and only if oil rose from sauce leader to destination let's see these examples the first example is that we have three nodes ages is 0 to 1 0 to 2 the source node is 0 destination node is 2 we return false because there is a purse indeed in one na it is starts from 0 and there let's see example 2 we start from sauce 0 but there is an infinite loop that did not enter in node 3 so we return false in this example all the parts from 0 will enter in the know the destination so return qu and for this example oh the pair start from the source node will get into the infinite loop of this one so we will not end at this destination node so return false and for this example even all the nose will like getting to the infinite self loop in a destination node now they will enter here so we return false so that problem becomes u first we will check whether there is a circle if there is circle we will return false if the parts start from the sauce Noda does not have a circle we will check that the enter node if it had equal to the destination node if there is some path that a doesn't enter in the destination know that we return false otherwise we return true so let's see how to detect a circle interactive graph we will use this classic algorithms from the COAS which is the introduction to algorithms we'll first to mark all the notes to the white color that is we use 0 to represent that then when we try to process know that William mark it as gray color we will use one and for all the color in the caustic we mark it as the gray color and we check is an order to its neighbor node once we find its never know de also you go to the gray color that means we have find a circle what does that mean you see this example we started from one and a week keep a dude f4 search then we go to two then we go to three they will go to four but when we at four we find that is - it when we at four we find that is - it when we at four we find that is - it already colored as gray so that is a back edge that means kinetic vertex u 2 extender V in a depth first tree so we just find a circle will return false if nothing wrong happens we will mark the color and black that means we have finished process that node so for this specific question we were first built graft we change the ages to agency agent Alisa then we will do the depth-first search from the source node depth-first search from the source node depth-first search from the source node if the current node has no neighbor knows that means it is a ending node if the current node II got your destination node return true if it is not this case will return false how about a recursion case we'll first mark the current node as gray color then we check all its neighbor nodes if the color of the neighbor knows equal to one which means it'll already in there kostik we return false that means circle fund if the never know D is white and we find a fourth case because we will keep it to the Deaf for search we return false even a zero happens we mark a current node to the black color and we return true so let's now write a code which will first to educate check if ages talents equal to zero we return true because if we have no ages that means that there is only one node so other parts from the source real leads to the destination node we return true otherwise we'll get our we will use agency Lisa to represent this graph usually we will use I will use a hash map but there will be much slower so in this case I will use at least two array list her red so what does is me that means every node as a index in the array and for every index that lists her means its neighbor notes so new list the size should be we also need our colors the cell also peon we are first a beaut graph we pass this tree and ages so let's first employments is a Beautif this Lister integer all right gee and the ages and ages so for every age in the ages this is afrin ode front of the ego tutor easy row and there - no of the ego tutor easy row and there - no of the ego tutor easy row and there - no there will be e1 if G if Rho is known we will first a new G from where new linked list then G fro will add the two to its list okay so we have finished this part then we were just a return dirt therefore such so we will pass this graph under the source code all souls source node and the destination node and also the Carles boolean the FS this integer graph that will be Seoul's destination and the colors so the base case is if is a and the node which means G as ego to know or GS the size equal to 0 this is the anti node which is a written as equal to D if the current know that if you go to a destination node return true otherwise return false if not the best case we color that note u 1 and therefore every next note is neighbor node G as if Derrick Allah he got you one we already made that we return false if Carla's next equal to 0 we have the process it and we find a fourth case they'll be next at the colors we return force otherwise we call out a current to know the chooser black and we return shoe okay I have typo just a typo okay thank you for watching see you next time
|
All Paths from Source Lead to Destination
|
missing-element-in-sorted-array
|
Given the `edges` of a directed graph where `edges[i] = [ai, bi]` indicates there is an edge between nodes `ai` and `bi`, and two nodes `source` and `destination` of this graph, determine whether or not all paths starting from `source` eventually, end at `destination`, that is:
* At least one path exists from the `source` node to the `destination` node
* If a path exists from the `source` node to a node with no outgoing edges, then that node is equal to `destination`.
* The number of possible paths from `source` to `destination` is a finite number.
Return `true` if and only if all roads from `source` lead to `destination`.
**Example 1:**
**Input:** n = 3, edges = \[\[0,1\],\[0,2\]\], source = 0, destination = 2
**Output:** false
**Explanation:** It is possible to reach and get stuck on both node 1 and node 2.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1\],\[0,3\],\[1,2\],\[2,1\]\], source = 0, destination = 3
**Output:** false
**Explanation:** We have two possibilities: to end at node 3, or to loop over node 1 and node 2 indefinitely.
**Example 3:**
**Input:** n = 4, edges = \[\[0,1\],\[0,2\],\[1,3\],\[2,3\]\], source = 0, destination = 3
**Output:** true
**Constraints:**
* `1 <= n <= 104`
* `0 <= edges.length <= 104`
* `edges.length == 2`
* `0 <= ai, bi <= n - 1`
* `0 <= source <= n - 1`
* `0 <= destination <= n - 1`
* The given graph may have self-loops and parallel edges.
|
First define a function f(x) that counts the number of missing elements until x. Then use binary search with the given function f(x) to find the kth missing element.
|
Array,Binary Search
|
Medium
| null |
1,877 |
Hello everyone welcome to my channel Quote Surrey with Mike So today you are going to do video number five of the playlist of Two Pointer Technique, okay and it is a very simple question but it is a very good question and is also famous, this is also a similar question to it. Now I will tell you that it is marked medium, not at all medium, it is actually a very easy question. Actually, this and its similar question are also marked medium but that too is quite easy. Lead code is 18777. The name of the question with intuition is Minimize Maximum. Pair even is fine. Maximum pair is even in. Hey someone asked this question. The similar problem is lead code 881 boards to save people. Okay, I think there will be a video on that too, you can search it either in my get hub repo. Look at the question, it is very simple, just the way of explaining, a little difficulty has been deliberately made in the question so that you find it tough. It tells very simply that pair sum is A B E A P B. It is known that the maximum pair sum is the largest. Pair sum in the list of pairs for example, if we assume that you have all these pairs, find the sum of all, 1 P 5 2 P 3 4 P 4, the maximum of all will be yes, okay, now it says that one number has been given to you whose The length is even, okay, pair the elements into n pairs, okay, let's say you have 1 5 2 3, it will always be of even length, so it says pair up, let's say you have paired one and two and 5 and 3 have been paired, you can pair them in any way, it is okay, each element of numbers is exactly one pair, meaning it will always be like this, 15 is 2 3, it can never happen that one is five, neither is there five in the other pair. Come, this one will not be like this. Every number will be in a unique pair. Okay, this is this. This makes sense. Let's look at this. The maximum pair sum is minimized. I think many people have disliked this question because of this line. It is a bit confusing but actually this line is an important part of this question, you will also understand that it is not very tough, it will become clear in some time, return the minimized maximum pair, see what you have to extract, the maximum pair which is minimized immediately after optimal pairing off. The elements try to understand what is being said. Pay attention to this question. Pay attention to this example. Look here, how could you have done the pairing. One way of pairing was that you would pair 35. Let's do this and pair 23. Okay, find out the maximum from these. 3 5, what will happen? 8 2 3 5. Maximum has come. Look, this time your maximum has come to T. Okay, now what is another way of pairing? You have done pairing. Did not do it with two, you have done it this time, the pairing and the pairing is done by two, so see what comes Answer 3 P3 6 5 Pu So Sen is Sas and what is the maximum from Sen? So see this time my maximum has come less. This time look at the maximum in the first one. Eight had come. Look at the maximum in the second one. If seven has come then your maximum is whatever you are extracting. No, it should be minimized, so see, your answer is that is why seven is here, not even a small maximum can be brought, no, see, I have taken out the maximum, the pair is even, look at the butt of even pairs, earlier I had got eight, now I have got seven. You have to do optimal pairing, right? It is written here that optimally, you have to pair it so that the maximum sum of your pair gets minimized. Okay, this thing is clear, this was the most important part. Now see how simple its interface is, that too. Let me show you and intu and b means the good thing is that the problem with bots is not lead code 81 is very similar, it is almost the same problem, okay intu let me show you, intu is very simple, think about it yourself. As we go by the values, take this example, 3523 is 3 5 2 3, okay, then you think for yourself that you should do pairing with whom, like let's say, look at the biggest number, then who is the biggest number, if the number is five, then I am tensed. That brother, if I pair this five with some other bigger number then I will get an even bigger number. Okay, and I will get a bigger number because already five is the largest element. And take a bigger number here too. If we take this then we will get an even bigger number, okay then what will I do, here I will not take three because look, if I pair five and zero, then the sum of both will come to eight and let's hold the smallest element, if we hold two then see seven will come, okay It is clear till now that means we will pair the largest with the smallest. Okay, so we will pair five and two. Okay, this is the reason. I am telling you again why because the largest number is very dangerous. And if you add from a larger number, you will get a bigger number, so let's do one thing, let's add it from the smallest number, okay, the story of these two is over, after that there is only three, one element left, three, pair these two. Will do 3 Answer came six Which is the maximum among the two That is seven This was your answer Okay let's take one more example Let's understand with exactly the same logic Let's try to develop the same into That 3 is 5 is 1 is 2 It is 6. Okay, so you think for yourself, according to intuition, what I said is that the biggest number is the most dangerous for me because it will make my sum very big. Okay, so what would you like that six is the biggest number. If you pair it with the smallest number, is the biggest number. If you pair it with the smallest number, is the biggest number. If you pair it with the smallest number, see that it will be paired with two because its sum will be eight. If you pair it with any other number other than two, then see that the bigger number will come. If you pair six with three, then you will get nine. If you pair it with five, then 11 will be four. If you do it with 10 then you will get 10 with the smallest one, look at it, so I have paired six with two, okay after that let's go with six, the tension is over, which is the biggest number after six The big number is looking like five. To me, this is also a big number, so we will pair it with the smallest number, two, so it has already been used. After that, which is the smallest number, it is looking like three, I am fine, so five will be paired with three. If you pair it, you will get eight. If you pair five with four, you will get nine, which is a bigger number. We want the smallest number. Okay, so five is paired with three, after that four and four are left, so pair them. Let's do 4, the answer is eight, okay, then look, our maximum is eight and its answer is also eight, okay, if we assume that you would have paired 6 4, then 5 4 and 3 2, let's assume we pair it like this. If you had given then see its value is even, its value is nine, its value is five, see what is the maximum value, then it is 10, then the answer would have been 10, which is not the optimal answer. You have to find the minimum answer of the maximum, so my answer is eight, okay here. Then you think to yourself, do you remember I told you that this is the largest number, then this is the second largest number, this is the third largest number and this is the smallest number, this is the second smallest number, this is the third largest number, then this is your How can we get it optimally? Brother, sort it or just do simple sorting. Okay, let's see. Let's accept this. If we sort it, what will happen. What was the smallest number? What was after that 3 4 5 6? So look at the largest number. Where will you find the large number? It is on the right most because it is sorted in ascending order and S is the smallest number. Here, 6 and 2 are paired. When the work of these two is finished, this was I pointer, this was J pointer. Brought J here and I. Bring here, okay, this second number, this second Smollett number, pair these two, 35, after that I will come here J will come here, pair these two, tell me how simple it was and exactly the same question is Bots to Save People Lead Code 881 Okay, so that was all, the story ended in the question. The most important thing was to understand why we did the sorting. The most important thing was Y is sorting and why did we do the sorting. I have explained to you here that the largest number is sorted into the smallest. Add from the number itself so that a small number comes out. Okay, so you have understood the reason, the code is very simple. Look, we are using two pointer, I and J. That is why, I have included it in the playlist of two point technique. So look at aa, I started from zero, first of all we will sort it, see what is there in step one, step two, aa is starting from 0 and h is from n-1, if h is from n-1 then how long will it and h is from n-1, if h is from n-1 then how long will it and h is from n-1, if h is from n-1 then how long will it last? Look at this, we should keep going till the A lane is there. Okay, A lesson will happen, only then I will be able to get a pair. Look, A will come here, then J will come here, as if both will cross each other, then only. Then if you will not be able to get the pair then A lesson should continue till J. After this there is nothing, just find the sum of both, Nums of I plus Nums of J and that is my result, it is 0 Result equal to maximum, keeping track of the value that is coming. Is the result comma even? Then what to do in the last one is to return the result. Size is fine. But why do we need to sort first? You have already come to know. Beginning of names and end of names is fine and one. Take variable int result equal to 0 while i lesson j find sum of both pointers names of i plus numbers of j let's update the result maximum of result comma sum and return result in s submit it and see hope fully we should Be able to pass all the cases and java code you will get it in my get hub any doubt raise in the comment section here we yes raise i pointer and j pointer no raise i pointer and j minus okay any doubt Raise in the comment section I will try to help you out see you guys in next video thank you
|
Minimize Maximum Pair Sum in Array
|
find-followers-count
|
The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs.
* For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`.
Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that:
* Each element of `nums` is in **exactly one** pair, and
* The **maximum pair sum** is **minimized**.
Return _the minimized **maximum pair sum** after optimally pairing up the elements_.
**Example 1:**
**Input:** nums = \[3,5,2,3\]
**Output:** 7
**Explanation:** The elements can be paired up into pairs (3,3) and (5,2).
The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.
**Example 2:**
**Input:** nums = \[3,5,4,2,4,6\]
**Output:** 8
**Explanation:** The elements can be paired up into pairs (3,5), (4,4), and (6,2).
The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.
**Constraints:**
* `n == nums.length`
* `2 <= n <= 105`
* `n` is **even**.
* `1 <= nums[i] <= 105`
| null |
Database
|
Easy
| null |
1,486 |
hey everybody there's a slurry you're watching me solve this problem live during a contest I'm gonna stop the explanation and then it's going to go into some code review some times and then just me working on a prom let me know what you think about this format hit like button to subscribe one join me on a discord link below and I will start now okay XO operation in a way give me an integer N and an interest thought defining away nums where num sub i's is you go to start plus two times i so in that so yeah so this one you just the hard part is just converting the numbers from an index I do I put Y into this form that they tell you in an X so everything together that's pretty much it for this one it's then your time I don't even know why recommend I mean this is a for loop I don't know if I recommend it for an interview but you know you should be able to get this pretty quickly hopefully yeah - 1 x oi pretty quickly hopefully yeah - 1 x oi pretty quickly hopefully yeah - 1 x oi operations in a no way so for this problem it was pretty much implement what they tell you to do which is for each index you map it to this other in formula and then you XOR each number that's pretty straightforward and if it sounds straight for is because that's pretty much all I had to do yeah and watch me do this I suppose
|
XOR Operation in an Array
|
find-the-distance-value-between-two-arrays
|
You are given an integer `n` and an integer `start`.
Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`.
Return _the bitwise XOR of all elements of_ `nums`.
**Example 1:**
**Input:** n = 5, start = 0
**Output:** 8
**Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^ " corresponds to bitwise XOR operator.
**Example 2:**
**Input:** n = 4, start = 3
**Output:** 8
**Explanation:** Array nums is equal to \[3, 5, 7, 9\] where (3 ^ 5 ^ 7 ^ 9) = 8.
**Constraints:**
* `1 <= n <= 1000`
* `0 <= start <= 1000`
* `n == nums.length`
|
Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn).
|
Array,Two Pointers,Binary Search,Sorting
|
Easy
| null |
25 |
so let's continue with our playlist before that hey welcome back to the channel I hope you guys are doing extremely well so the problem that we will be solving today is reversing nodes in k group so what is the problem exactly stating it is stating that you will be given the head of the link list and you'll also be given a value K now your task is to reverse the nodes in K Group what does it mean let's take this example where you given the head and you given the value K as three and your task is to figure out all the groups of size three and you have to reverse them individually and you'll have to reverse them individually if I ask you which one is the first group of size three you'll be like this one is the first group of size three so what you will do is you'll end up reversing all the nodes in it so three will be at first after that two after that one because you have reversed it so let's do the reversal you'll have three then two and then one perfect once this is done which one is the next group of size three can I say that this one is the next group of size three I can so you again have to reverse it so if I reverse it I'll have six then five and then four and one will be connecting to six after that which one is the next group of size three this one so again I have to reverse it so nine will be at first then eight and then seven so is there any other group of size three no there is only a single element now this is not of size three so if there is no other group of size three it can be of size one it can be of size two doesn't matter it has to be exactly of size three then only I'll reverse them otherwise I'll just attach it as it is and this will be my updated head and this is what I will return as an answer so before I move on to the solution there is one video that you should definitely watch that is reversing the link list in case you haven't seen it go back and watch it and then you can restart this particular video so how do I approach this particular problem it is asking me to reverse the notes in key group so this is the first group that I'll have to reverse this is the second group that I'll have to reverse this is the third group that I'll have to reverse and for the last one I don't have to so if I carefully observe if I try to reverse the first group three will be here and that will be my updated head so for the first group I'll have to think about the updated head because the head will change correct and then it will be following to two and then to one so if I reverse this you'll have six you will have five then you'll have four but you have to remember that this one will be pointing to six so these are the things that I have to take care okay so what I will initially do is I'll take the first group and I'll just do the reversal on it and then I'll think for the later half how can I do that obviously have to do a traversal because without traversal I cannot do anything on the link list I'll take a temporary I'll place it at the head I'll not alter the head I'll take a temporary and I'll place it at the head now I know one thing that this is my first key group but I'm writing the code how will I know it I know temporary is standing at the first Elm I need the last element of this group correct so if I say this is the first element this is the second element this is the third element or rather this is the kth element so I can simply write a iterative function which can find me the K node we can easily write it I not get into implementation details get the K node so this will be my K node remember this will be my K node now I can definitely say that I have the first K Group where I have the first element and the last element I do have it now what is my next task the next task is to reverse this particular first G group right how can I do it I don't know how to reverse a link list but it is a link list I cannot reverse any particular part of the link list I cannot say reverse this much in a link list I cannot see it but what if I send this as an individual link list I can what if I say hey let's break this link or rather let's break this link and have it point to null can I say this I can and if I do this what will happen is this one will be an individual link list this entire thing will be an individual link list where temporary is the head and kth node is the last node so now if I call the reverse function I'll get the reverse link list I will so just call it and get the reverse link list so you'll call the reverse function which will reverse the link list and the will be pointing to n so if you remember whenever you call the reverse function it returns you the head of the updated link list head of the reverse link list so this will this is what you will get in return this is what you'll get in return so what you'll get is a new head correct remember the initial head is here so the initial head is still here at one the initial temp is still here remember this and K node is still here why because even after reversal K node will still be three temporary and head will still be one so I've just written it the only thing that the reverse function will do is it will reverse it and I definitely know that the K node will always be my new head perfect I've done it now can I say one thing if temporary is equivalent to head this is my first group hence the head will always be updated the initial head will always be updated so let's update it so what you'll do is you'll update the initial head to K node you'll update the initial head to the K done super simple so what I've done is I'll repeat first I have placed temporary at head then I figured out the K node so I know this is my first group and I need to reverse it so I broke down the link and pointed it to null so that it's an individual link list I just reversed it so I've got the Reversed link list now once I've got the Reversed link list the initial head was at one I know the initial head will get updated to three so I'll just do it done now this is my temporary this is where my temporary stands but I need to go to the next group I need to go to the next Group which one is the next group this one is my next group correct how can I go to four I cannot goow I cannot go because I broken down the link so remember before breaking down the link there was a link right before breaking down this link preserve the next one so you can easily preserve the next node and once it is reversed what you can do is you can take temporary to the next node so this is what you'll do you'll take temporary to the next node perfect so I've done I've taken temporary to the next row I can again repeat the task what was the task now I know I have to figure out the next key group this is the next key group again figure out the K node so this will be my K node why again run the counter this will be one this will be two this will be three which is the K node so I'll again figure out the K node once you figured out the K node what is your next job remember this is like this next Lo now can go off and this will be temporary what is your next job is to make sure this particular key group is an individual link list otherwise the reverse function will not happen right will not form the reverse so what you will do is you'll break it down but before breaking down please preserve the next node so please preserve the next note and you can easily do it by saying kth node of next is my next node done once done this please break down this load and point it to null so once you've done it can I again pass this temporary as the head to this reverse function and it will reverse it so once it is reversed you'll get something like six 5 four six will be pointing to five will be pointing to four and four will be pointing to null remember over here temporary is at four and the K node is at 6 the K node is still at six done what is the next thing that you have to do just think the next thing that you have to do is to make sure this one should be pointing to six the one should be pointing to six you'll have to remember which one is your last node which one was your last node in the previous group you'll have to remember that as well so just use one more variable to remember which one is the previous note so you'll have the previous note stored so just make it point so make the previous note point to this done now what is the next job before going to the next Group which is this one please make sure you remember the previous node which is this one because you need to make the connection correct what's the next take the temporary to the next you can easily do it because you preserved the next node done and dusted what's the next job again this is my next key group so I'll do the job for it so let's do it so this is my next key group where temporary is standing at 7 again find the kth node so this will be my kth node perfect once youve got the kth node what is the next job get the next node so this will be my next node perfect after this is your key group correct you'll have to reverse it but you cannot have it you cannot reverse an individual section of the link list you can reverse the entire link list so what you will do is you will break this link and he'll make it point to null once it is done can I ask the reverse function to reverse it where temporary is my head I can so this will be reversed so what will Happ happen is you will get seven sorry 9 following 8 following seven and this is pointing to null so do you remember you preserved the previous node now since you preserved the previous node what will happen is this will go off and this four will be pointing to nine done where will your temporary be your temporary will be here your K node will be here quite simple what is the next job is to make sure you again preserve the previous node because you'll have to form the connection after that you take the temporary over here and this is done now let's go to the so let's go and find the next K Group the next job is to reverse this particular k group but do we have K elements we don't have K elements so if you do not have K elements I repeat if you do not have K elements you don't reverse so what is the next connection you just attach this one to this the remaining elements so can I say the previous node will be attached to the temporary or to the next node doesn't matter and once this is done your head is updated so you're done and dusted quite simple you'll just have to reuse the reverse function that is what you have to do so I'll be adding down the pseudo code now this won't be any language specific code in case you want the C++ Java python or JavaScript want the C++ Java python or JavaScript want the C++ Java python or JavaScript codes the link will be in the description how do I start off I started off by placing the temporary at head so I'll do the same over here I'll place the temporary at head and then we did a traversal to find out all the K groups let's do a traversal for that I have to run a while loop for sure so temporary is not equal to null for sure what was the next thing I know that this will be my first k group so I figured out temporary and I figured out the K node if you remember so let's find out the K node so I'll say hey function I'll write a function find KDE or get KDE this is your head and it'll have to give me the KR it will give me the KR which will technically be this one right what if it doesn't have a k node what if the link list was only this much only with two elements will it have a group of size three it won't right so you have to keep that in mind what if you have a link list which is small so you don't have to reverse anything over here so please make sure you check if there is no K node imagine if there is no K node you get a null the function returns you null in that case you'll have to do something and then break we'll talk about that something afterwards but as of now you stop so you break you no more Travis perfect what is the next thing that you will do the next thing that I will do is if this is not happening like if there is a group then you'll get the K what is the next thing that you'll do you'll have to separate the SK group from that entire link because you cannot reverse a section of the link list this will be pointing to this you'll have to separate it you'll have to separate cre it but do you remember you need to store this otherwise you cannot Trav further so please make sure you take a next node and store the next one so maybe you can take something as next node and you can store it next node will be K node next so what I've done is I've remembered the next one perfect what is my next job will be okay I've remembered the next not I have to make sure this is separated and pointing to null because I need to separate this particular link list I'll do that for you so I'll say hey K node your next is pointing to null so what has happened is this particular link list has been separated now you can reverse it how can you reverse it's very simple call the reverse function which is the head is temporary and ask them to reverse it so what will happen is you will get this reversed link list now what is the next job you'll have to identify is it your first group or is it your later groups how do you identify that it is your first group how do you identify if temporary is equivalent to head then only it's your first group first key group rather so be like hey if temporary is equal to head remember the reverse will return you the head of the updated head of the Reversed link list but you already know which one will be the head will be the K note you already know it right so can I say after reversal the new head or rather the updated head will be the K note I can so for the first time I can say that the head maybe I can use the white one so that you can remember the head will be the K Thro only if this is the first instance like first key group otherwise what do you update the head you don't update the head but you need to make sure that you do something else and what is that something I'll come to it afterwards so what I've done is I made sure this is updated what is my next job the next job is to take temporary from here and place it here correct so I'll do that I'll write the else so I'll take temporary and place it at next node I'll take temporary and place it at next so what I can say is hey my job is done hey my job to reverse this portion is done but do you need to remember this you need to remember the previous LOE why because when you reverse this next K the previous has to point so please make sure before moving the temporary here you remember this so maybe I'll take another previous node and I said before moving temporary please remember the previous node done and dusted what will happen on the next stage let's Analyze This Is Where the wild Loop will end and let's analyze what happens at the next step The Next Step temporary goes here again finds the K node which is this so this is done this never executes perfect next note is K node next so the next node is stored perfect G node next is null k no next is n so it points to n nice reverse so the reversal happens is temporary head no so comes to else what will you do one else if you're not updating head please make sure you connect the previous notes next to this one please make sure you do this so what you do is on else you'll say previous node your next should be pointing to the current G node perfect so this is done so I can say this is done what after this you have to remember the previous node so you remembered it here one after this you have to take the temporary you'll have to take the temporary from here and place it here so this will be done by this n and nust it but what happens during this scenario what happens when temporary is standing here let's go there what happens when your temporary is here you go and find the K node and what you get is null so you break out but you'll have to do one step which is the previous node has to point to this so please make sure you point previous nodes next to null sorry not null to Temporary before breaking out please make sure the previous thoughts next is pointing to Temporary got it but can you straight away do this you cannot why because when he started off there was no previous s and he started off there was no previous not what if you had a link list which was something like this one pointing to two pointing to null and this is your head for the first time temporary was here and a k node your K node will be null you don't need to do anything because this doesn't have a k node since it is the first one you will never have the previous node you'll never have the previous Noe so if there is no previous Noe you don't do it so you'll say hey if there is a previous node then only do it if there is a previous note then only do it remember one thing this will be executed only if it's a lengthier link list for smaller link list this will turn out to be false you can take smaller examples do a dry run on the code and you'll understand it in a much better way so let's quickly get back into the code editor and understand the code so what I've done is initially I've written the get K Throne it's very simple standing somewhere you have a k you do minus till you reach the K node super simple have a simple traversal by K minus and you return temporary in case there is no K node it will be returning null have to write the function K reverse so initially temporary will be head previous last the previous one will be null and you keep traving till it is null get the K node by calling the function if it is null just make sure you point it the previous pointing should be done and then you can break out because there will be no further K groups after that you get the next not just preserve it make sure you separate out the link list reverse it if it is head uh if it is the first K Group update the head if it is not make sure you point the previous K Group to the new ones just store the previous and after that move to the next once this is done update like return the updated head so I'll go ahead and submit this so if I ask you what is the time complexity what will be the time complexity you're seeing a simple traversy right am I doing something else I'm also doing a get G so if you carefully observe if I go back to the iPad so what I'm doing is I'm standing temporary like I'm making temporary stand here and I'm reversing this entire thing which is basically taking linear time then I'm reversing this entire thing So eventually I'm reversing section by linear time so that's definitely a big of n while reversing each and everything correct at the same time I'm trying to find the K node as well like when I'm standing at temporary I'm finding the Kate node and I'm standing at temporary I'm finding the K nde that's another this much which is again B go off n so can I see the overall time complexity is B go off to N I can and the space complexity is beo of one because I don't think I'm using any external space because I'm just changing the links and my work is done so I hope youve understood everything and in case you still have doubts what I'll recommend you to do is just write down multiple examples do dry ones because that is how I did it initially it was tough for me as well but I did a dryon on a lot of examples and now it's in my head so please do it and if you're still watching please do consider giving us a like and if you're new to our Channel what are you waiting for hit that subscribe button and with this I'll be wrapping up this video Let's readence our other video till then byebye D when your heart is broken don't ever forget your golden I will find the light
|
Reverse Nodes in k-Group
|
reverse-nodes-in-k-group
|
Given the `head` of a linked list, reverse the nodes of the list `k` at a time, and return _the modified list_.
`k` is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of `k` then left-out nodes, in the end, should remain as it is.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[2,1,4,3,5\]
**Example 2:**
**Input:** head = \[1,2,3,4,5\], k = 3
**Output:** \[3,2,1,4,5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= k <= n <= 5000`
* `0 <= Node.val <= 1000`
**Follow-up:** Can you solve the problem in `O(1)` extra memory space?
| null |
Linked List,Recursion
|
Hard
|
24,528,2196
|
845 |
hey guys welcome back to another video and today we're going to be solving the lee code question longest mountain in area all right so in this question let's call any contiguous sub array b of a mountain if it has the following properties so the sub area b must have a length which is greater than or equal to three and this over here is the second condition so i think this over here is a little bit confusing so instead let's just let me just kind of uh draw it out or illustrate it okay so uh all it is uh like the questions name of we need to have a mountain and what a mountain means is that uh it just looks like this right a mountain and over here we're going to have the highest number and every number leading up to that is going to be greater than the before number so for example we might have a number one then we might have two then we might have five again uh they do not have to uh increment they do not have to be incrementing by the same uh value right so uh this increments by one this increments by three but as long as the previous number is smaller than the current number and then we could have seven and then after seven let's say we have the number 10. now 10 over here would be considered our p and the reason for that is because let's say the number which comes after 10 is the number nine right so now since 10 is kind of like our peak everything after 10 must be less than 10. so for example we might have nine then we might have eight we might have seven and then we might have one right so all these numbers over here are less than the previous number and more importantly everything up to 10 is in ascending order and everything after 10 is in descending order so this over here is kind of the it's basically the condition that they were talking about and this is one of the conditions that we need to satisfy okay so note that b could be any sub area of a uh that includes the entire uh area of a itself okay and given an area a of integers return the length of the longest mountain possible okay so we want to find out what the longest mountain is and if there is no mountain we return zero so for example over here we have two and in this case everything is equal to the same thing right so we can actually have a mountain all right so we have that and let's just look at this example over here two one four seven three two five let's just look at it quickly and then we'll go through it step by step all right so real quickly um in this case let's find one of the mountains okay so one mountain could possibly be one uh four seven and then three two right so that's a pretty big mountain right so seven would kind of be considered our peak so we had one then we have four since four is greater than one and seven is greater than four then after seven everything goes in descending order right so that's kind of the downfall of it so seven then we have three and then we have two so what exactly is the length of this so the length of this is one two three four five so that over there is going to be the largest mountain we have so we're going to end up outputting the number five all right so hopefully you understand how the question works and now let's see how we can actually solve this and let's look at the same example actually okay so this over here is the area that they were that was given to us in the first example and let's just see how we can solve this so uh the first time i saw this question i kind of came up with two different ways to solve this so the first way is what i would do is i would have some sort of pointer so let's say the first pointer starts off at two and then what i would do is i would check if the next value is greater than whatever the pointer value is so in this case is one greater than two it's not so in that case we know that we don't have a mounted so we're going to keep doing that until we find the starting of a mountain and it's going to go up to a certain point and once it reaches that point what's going to happen is that we're going to check for how much for all the values that are below the peak okay so that's one way to do it but a better or kind of an easier way to do it would be to find out what the peak exactly is so what do i mean by the p so by the peak i mean the top most point over here so how exactly can we find a peak so doing that is going to be pretty simple and all we need to do is the peak uh whatever value is to the left of the peak is going to be less than it okay so everything to the left of the peak is less than it and everything to the right of the peak is also going to be less than that right so uh this over here is going to be kind of our center point so now that we found a peak all we need to do is we kind of want to see how long our mountain is going to be so let's just see how we can do this so first we're going to go to 2 but over here you want to notice that at 2 you won't have anything to the left of 2 right so in that case we can kind of deduce that whatever is at the zeroth index and the last index are never going to be a peak and the reason for that is really simple is because uh at two you won't have anything to the left of it and at five you won't have anything to the right of it okay since this is not a cycle okay so two and five are never going to be answered so we're just gonna kind of ignore them so we're gonna start off at the number one so we're gonna check is one a peak so to do that we're gonna do go to two and four so one is supposed to be greater than two and greater than four but in this case one is not greater than two it's not greater than four so one is not a valid peak okay so now let's uh try four okay so is four a valid peak well uh four is greater than one but it is less than seven so it is not a valid peak but now once we get to seven does look like a promising peak right because uh seven is greater than four and is greater than three so this over here is a possibility so now we found a possibility which is the number seven okay so the first point is finding the peak now all we need to do is we want to find out all the elements to the left of it and all the elements to the right of it and how exactly can we do that so to do that we're going to be using a two-pointer method two-pointer method two-pointer method we're going to have a pointer called left and we're also going to have a pointer called right so let's just look at them one by one okay so the left pointer over here and it's going to be moving to the left so how do we know when it's going to be moving to the left so one quick thing that we can see is over here we have the number four and we have the number seven so technically the previous number must be smaller than whatever number we are currently on and the reason for that is because it is an ascending order so the number before the number of current number we're on has to be smaller right so in this case four or whatever this number is has to be less than seven and it is so in that case we're going to move our pointer to the left by one all right now we're going to check it again so now we're going to check if one is less than four and it is one is less than four so we're going to move it to the left by one again okay so now we're going to check is uh 1 less than 2 1 is not less than 2. so in this case we're going to stop and our pointer is now going to stay at this value okay so this is basically telling us that this over here is going to be the start of our mountain all right perfect okay so we have this and now what we need to do is we want to take care for the right value over here right and for the right value we're going to do a similar thing which is basically whatever the right value is it has to be less than whatever the current value is and the reason for that is because we're going in descending order so the first number uh has to be greater than the second number right so yeah pretty simple so in this case 3 is less than seven so we move to the right so now right is going to be over here uh two is less than three so we're also going to move to the right so now we move that to the right and now it's gonna be over here and then we have the number five but five over here is actually not less than two so in that case we know that we need to stop over here since five is not less than two so yeah so this over here is going to represent the ending right so this is going to be the end point of our mountain so now that we have the end point and the start point we can kind of figure out what the length of our mountain is and to do that we'll be using the indices of this so this is at index one and the ending over here is at zero one two three four five so this is at index five so to find out the length of the mountain we would do five minus one plus one okay so if you just did five minus one you would get one two three and four right but oh they are we want to include the left and the right values itself so we're going to do plus one so it's inclusive so in this case this is nothing else but the value of five and now this is going to be our answer and if you look back that is exactly that the answer that we got right so hopefully you understand how this works it's not too hard and now let's see how it looks like in code okay so over here we're going to start off by initializing our result okay so our result over here is going to start off with a value of 0. so now we're going to actually go through each of our indices inside of the area a okay and we're gonna be going through the index because uh it's easier to find the length that way all right so to do that we're gonna do for index and what exactly are we going to is going to be the range so we're going to start off at the first index and the reason we're starting off at the first index is because we know for a fact that whatever is in the zeroth index and the last index is not going to have a value and since we know the last index is cannot can also not be a peak what we're gonna do is we're gonna only going to go up to the length of a minus one so we're gonna ignore the last value since it cannot be the peak and we're also ignoring the zerox value okay so now that we have this we want to check if whatever we're currently on is a valid peak or not and to do that the current value we're on is going to be a index so a index over here has to be greater than a index plus one okay so a index has to be greater than a index plus one and a index over here also has to be greater than the previous value so that's going to be a index minus one okay so if it's uh supports this condition we know that we have a possible or valid peak and in this case um again we're not going to be checking if the length of our thing is three because if this is true as it is we already have a length of three all right so now what we're going to do is we're going to initialize our pointers so over here we're going to have a left pointer and we're also going to have a right pointer and they're both going to start off at the same place which is going to be the index okay so they both start off at the same place so in the very beginning let's first kind of find out what the left value is going to be so for the left value what we're going to do is uh we're going to check so we're going to go to the index l and in order to move our left pointer by one to the left we're gonna check if a l is greater than a l minus one so this is the same thing like i said earlier and if this is true then in that case what we're gonna do is we're do we're gonna decrease our left value by one so l minus equals one but over here the problem is what if we keep going to the left so we have to have some sort of store a stopping point because we cannot have a lower bound value less than whatever is at the zeroth index so to kind of just uh make sure of that we're going to add a condition so while l is greater than zero and this so in this case uh we don't end up with an index error okay so now we're going to do the same with our right so for the right we what we're going to do is we're going to go to a r and a r has to be greater than a r plus 1 since it is in descending order and if that is true then in that case we're going to increase the right pointer by 1. all right so over here we want to check the same thing we don't want our right pointer crossing the fifth value right so that is also going to give us an index error so to just make sure of that we're going to check if r plus 1 is less than the length of a okay so yeah um and we're gonna put n okay so this uh ensures that we don't go past the last index value all right so that should be it so at the very ending we want to find out what our current uh length is of the mountain so to find out what the current length is going to be r since r is going to be bigger than l so r minus l and then plus one but we want to compare this with whatever the previous or existing result is so to do that what we're going to do is we're going to make result equal to the maximum between the previous result whatever the previous result is and whatever the current uh mountain value length we found just right now and we're going to choose the maximum between them okay so that should be it and at the very ending we're going to go outside of our for loop and we're going to end up returning our and one more thing i do want to add is the time complexity of this is going to be big o of n and the space complex uh complexity is going to be constant space right so big o of one and as you can see our submission was accepted so finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thank you
|
Longest Mountain in Array
|
longest-mountain-in-array
|
You may recall that an array `arr` is a **mountain array** if and only if:
* `arr.length >= 3`
* There exists some index `i` (**0-indexed**) with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
* `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`
Given an integer array `arr`, return _the length of the longest subarray, which is a mountain_. Return `0` if there is no mountain subarray.
**Example 1:**
**Input:** arr = \[2,1,4,7,3,2,5\]
**Output:** 5
**Explanation:** The largest mountain is \[1,4,7,3,2\] which has length 5.
**Example 2:**
**Input:** arr = \[2,2,2\]
**Output:** 0
**Explanation:** There is no mountain.
**Constraints:**
* `1 <= arr.length <= 104`
* `0 <= arr[i] <= 104`
**Follow up:**
* Can you solve it using only one pass?
* Can you solve it in `O(1)` space?
| null | null |
Medium
| null |
111 |
all right so this leaker question is called minimum depth of binary tree it says given a binary tree find its minimum depth the minimum depth is the number of nodes along the shortest paths from the root node down to the nearest leaf node note a leaf is a node with no children all right so given this binary tree if we go down the right side the depth is 3 but if we go down the left side the depth is 2 so the minimum depth of this is 2 all right so the key to solving this problem is to use breadth-first search problem is to use breadth-first search problem is to use breadth-first search if you don't know what I mean there are a couple ways you can traverse a tree one way is to use depth first so what that means is you start at the top and you go as deep as possible but somewhere like there and then here and there and check the other side going as steep as possible or we can use breadth-first search which or we can use breadth-first search which or we can use breadth-first search which is what i'm gonna do in the solution with breadth-first search it starts at with breadth-first search it starts at with breadth-first search it starts at the top and then checks each child in this direction instead alright so how do we actually do breadth-first search we actually do breadth-first search we actually do breadth-first search we'll do it using a queue and if you don't know what a queue is just a data structure in which the first element added will be the first one removed so let's say we added these in this order one came first then two and three and then four which one is going to be the first one removed one which one's the next one to next three and then four I also have a video explaining more in detail what a queue is and how to implement it and I'll link that down below alright so we're going to need to keep track of a couple things one being the current depth of course since that's what we're trying to figure out and I'll explain nodes in a bit alright so I'll go over quickly exactly what we're gonna do and then I'll slow it down a little bit in the second render so what you do is you add the first node to the queue and you check to see if it has any children remember what we're looking for is a leaf node and a leaf node is a node that has no children once we find a leaf node we can stop and just return the depth all right so again we check to see if it has children it does so we need to add the children to the queue 15 and 20 all right so now that we're done with that node we need to get rid of it and we need to add one to our depth because what we're saying is that our tree has at least a depth of one next you move to the children so the number 15 you do the same thing does 15 have children yes it does so you add them so the number 2 was added because it's its only child and since we're done with that we get rid of it and move on to the next child was the number 20 again we check to see if it's a leaf node it's not so we added stroll and now that we're done with it we take it out of the queue all right so now that we're done another level of the queue we need to add another one to the depth now let's repeat look at the first thing that's in the queue is it a leaf node in this case it is so what we're gonna do is we're gonna add one more to the depth and return that so what we're saying is that this tree has a minimum depth of three all right so what's this mysterious nodes variable I mentioned down here all it is a mechanism we're going to use to keep track of how many of the nodes in a level we've already taken account of what I mean is this after we added 17 we say okay well this level only has one node once we've removed one node we know that we can add one to our depth because we're done with that level for instance let's say we do 17 is it a leaf node no so we add its children we remove it add one to the depth so at this point we'd have a depth of one and now that we've done that one loop we know that our nodes remaining zero move to the next level how many nodes do we have now in the queue we have two so now we know we have to do that logic for two nodes so now when we get to the number 15 we say is it a leaf node no so we remove it and add its children so that's just the node 2 and at this point we've only done one node in this level so we'll just decrease nodes by one meaning we know we only have to do one more node before we get to the next level all right so now we're on the number 20 is it a leaf node no we add its children 19 to 24 we can remove it and now that we've removed it we know there are zero nodes left on this level so we can get rid of this and once we know they're no more nodes left on that level we can add one to the depth let's just finish that off now we're on this level how many nodes are in the queue there are three so now we know we need to do that logic possibly three times unless we find a leaf node first so we start at the number two is this a leaf node yes so now we add one to our depth and we're done we don't actually have to do anything to the nodes variable this time because we found our answer all right so let's get to the code I've shortened the example a little bit on the left in order to save time all right so what lead code has given us is a function called min depth which accepts the root and the root is just the root of the binary tree all right so the first thing we have to do is we have to check whether that root is null because if nothing was given to us then it has no depth so the depth would be zero all right so the next thing we have to do is we have to create the queue we talked about we can just do this with an array so we'll say let Q equal an array that'll look like this okay now we have to push the root into our Q so Q don't push route next we have to instantiate our depth variable and we'll instantiate it at zero because we haven't done anything yet all right now we need an outer while loop this outer while loop helps us traverse down the tree then we need an inner while loop the inner while loop helps us to go across a level of a tree from left to right but in order for us to keep track of how many nodes there are we need to have our number of nodes variable we'll make that equal to the number of nodes in our queue now we can make our while loop that says wild number of nodes is greater than zero misspelled nodes all right so now we need to grab the node or nodes that are in our queue so we'll say let current node equal Q dot shift in JavaScript shift just returns and gains access to the first item in an array which is how we're emulating a queue because remember in a queue the first item that was added is the first one removed all right so now that we have access to that we can show that like this it's going to be out here but now we're gonna check if that item which is the node 17 has any children if it has no children we've gotten to a leaf node in which case we can just return the depth at that point so we'll say if current node dot left equals null remember the current node right now is the node 17 and current node right equals null so here we're checking if it has no children then we could just increment the depth and return that number but that's not the case in our example right now the note 17 has two children so we need to add those children so we'll say if her note left doesn't equal null meaning it has a left child what do we need to do we'll add that child to the queue that would look like this it's left child is 15 so we're adding that to the queue we also have to check if it has the right child and if it does add that to the queue so if current node dot right doesn't equal null then we'll add it's right child and that would look like this if the right child is 26 so that's in the queue I forgot to add our number of nodes so right now our number of nodes in that first level is 1 it was just the node 17 so now that we've checked the children of the node 17 we can just decrement our number of nodes all right so our number of nodes in that level is now 0 so now that our number of nodes is 0 it means we can start our outer while loop over again and it also means we can add 1 to the depth because we've successfully gone through all of the nodes in this row all right so depth plus at this point this is the finalized version of the code so if you want to run it now it should work but let me just walk you through the rest of this example so we're on the outer while loop line 21 line 22 it says let number of nodes I've missed the s let number of nodes equal the length of the queue right now is 2 so now we enter the inner while loop we're gonna access the first node all right so we're on line 27 it asks if the node 15 has any children no it doesn't so now what we could do if you look at line it's 28 and 29 is we add one to the depth just right here and now we'll just return that immediately and that maps to our example our minimum depth is 2 all right let's run the code see how we did looks good let's submit all right so our solution was faster than about 81 percent of other JavaScript submissions as usual decode and written explanation are linked down below if you liked the video give it a like and subscribe to the channel it helps out a lot see you next time
|
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
|
83 |
everyone today we are looking at lead code number 83 remove duplicates from a sorted list okay so this question here is asking if we have a list of one two we want to remove any duplicates we want to remove this 1 here and return 1 2. here we have 1 2 3. we want to go ahead and remove this one over here and either one of these threes so we return 1 2 3. okay so how do we go about doing this let's jump over here in the conceptual here we have duplicates we have a list of one and two and we want to return a list of 1 and 2. okay so one way to think about this is we could create a helper function that just says remove node we can find out what nodes are duplicates so we could create an array or we create a hash table and we can have a key for each one of the numbers and the frequency that key is in the list so one is appearing twice two is appearing once okay and now we know that if any of the values here are more than one then we go ahead and remove those keys okay so that's one way we could approach this the only issue with doing it that way is that it is a bit complicated and also what about time and space complexity well we're going to have to traverse through this list numerous times it'll still be linear time but we're going to have to go through that list many times more than once because we're gonna have to go through it once to create the hash and they're gonna have to go through it again to go ahead and remove the duplicates the so first we're gonna have to find the duplicates and then we'll have to go over it again to remove the duplicates the second issue is space we're going to have to create linear space because we're going to have to create a hash data structure and essentially keep a frequency of all the values and how many times they're appearing now something important to remember is that this list that they're giving us is sorted okay it's a sorted list so even in that we can assume that the numbers we don't have to go and find the duplicates in the whole list we have to traverse the whole list we can see that whatever is going to be next whatever value is if it's the next value and it's the same as the previous then we can you know we can assume that it's a duplicate the only issue with that is let's say we have a list where we have 1 and two well we can say that this next value is the same so we remove that then we're back here and we can say this next value is the same we remove that and then we can uh get to the next value so that's another way we could do this is let's say we have one two we can just go here and this is our previous and this is our current and we can just say we just keep on incrementing this current until they have different values until this previous has a different value than current and then we just go ahead and set the previous dot next to that new current okay so that's another way we could do this now if we did it that way what would be our space complexity where space complexity would be constant because we don't have to create any new data structure and we only have to traverse through the list once okay and so that's actually how we want to approach this so let's say let's go and take that second example which i believe was one two three okay so here we have a list one two three okay and let's say we created a previous node and we just set it to some value we'll just say minus infinity and we'll say this is previous and this is a node we're going to create and we're going to set it to be before the head so that node that dummy node.next is going to be the that dummy node.next is going to be the that dummy node.next is going to be the head of our input list okay our current node will be the head of the list so we'll start there and we're going to traverse through this whole list but what we want to check is if the previous value the node at previous.val previous.val previous.val is equal to the current dot val what do we want to move this current all the way out until they don't equal so let's say we get to this next one here okay and the previous vowel which is one is equaling the current val well then we want to just go ahead and create a while loop and increment that current until it is not equaling the previous vowel and then what do we want to do so let's go ahead and write that statement here we could say while our current that we do have a current node and current.val and current.val and current.val is equal to previous dot val what do we want to do we just want to increment current we equal current.next current we equal current.next current we equal current.next okay now once current is outside of the range once current is here we'll break out of this while loop and we just want to set our previous dot next to current okay else what do we want to increment previous and current so let's say we get here now to our next iteration and previous and current does not equal each other then we just want to go ahead and increment this okay we'll increment this here and then we will go ahead and remove out that current okay so we can just say p dot next or p equals p dot next p equals c and c equals c dot next okay and if we do it this way then what is our time and space complexity well our time how many times are we traversing this list relative to the size of the input just once so our time complexity here will be o of n and then our space complexity well what um what data are we creating relative to the size of the input well we have our previous pointer we have our current pointer okay and no matter how big the input size is it's a constant amount of space that we're creating relative to the input size so our space complexity here will be constant okay which is pretty good okay so let's go ahead and jump into this code here so first we want to go ahead and create that dummy node and we'll set this to minus infinity set it to minus 1 but we might have minus 1 in the list and that might cause a bug so we'll just set it to minus infinity and then we want to go ahead and make sure the dummy is connected to our input so we can say dummy.next so we can say dummy.next so we can say dummy.next and i believe uh yeah we can just go ahead and set this here as a second in the second parameter right over here okay okay and so now what do we want to create our current node set it to head we want to create our previous and set it to dummy okay and now we want to say while current is true if current.val equals previous dot val if current.val equals previous dot val if current.val equals previous dot val what do we want to do i'm going to say while current and current dot val and the reason we want to do current and current.val is that if current is null current.val is that if current is null current.val is that if current is null if we do reach a point where current is null and we try to call dot val on it will throw an error so that's why we want to say if then we want to make sure there is something in current and current dot val equals prev.val equals prev.val equals prev.val okay what do we want to increment current now once we're out of that what do we want to update our previous dot next so previous dot next is going to equal current okay so now because what we're doing here is that once we get out of this we want to make sure that once our current is here it's out of the same as previous stop val we want to break this here and you want to set this over here okay and else what do we just want to increment current and previous so we can say previous dot next is going to equal current and current is going to equal current.next okay and then we do have a reference to that dummy node so we just want to return dummy.next dummy.next dummy.next okay let's see what happened here previous.next equals current.next to next equals current and previous equals current not previous.next previous.next previous.next and there we go okay so that is lead code number 83 remove duplicates from a sorted list i think the important pattern to remember here is using this dummy node it's a anytime you're dealing with addition or removal of nodes from a list from a linked list you always want to set up a dummy node before the head and it just makes deleting adding nodes much easier because you really um stamp out a lot of edge cases what if you know what if all the nodes that you have to remove is from the beginning uh it's hard to keep track of those pointers but using this dummy node strategy really makes that much easier and then uh the other thing is just making sure that there's small bugs like this where you want to make sure the current does have uh that there is a node there because if not when you try to call dot val on it will throw an error and then anytime with linked lists you just want to make sure you really map out where exactly the pointers are changing and it will just make life a lot easier okay so that's leap code number 83 remove duplicates from a sorted list hope you enjoyed it and i will see you on the next one
|
Remove Duplicates from Sorted List
|
remove-duplicates-from-sorted-list
|
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_.
**Example 1:**
**Input:** head = \[1,1,2\]
**Output:** \[1,2\]
**Example 2:**
**Input:** head = \[1,1,2,3,3\]
**Output:** \[1,2,3\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 300]`.
* `-100 <= Node.val <= 100`
* The list is guaranteed to be **sorted** in ascending order.
| null |
Linked List
|
Easy
|
82,1982
|
402 |
Hello guys welcome back to tech division in this video also directly remove's digit problem wish to meet code 9th me challenge so let's not look at the problem statement the problems the giver unwanted birth represented as a string remove's deposits from the number is the Smallest Possible Number 9 Notes The Length of the Sentence So and Will Always Be Grade Two K Indiscriminately Examples in Order to Give It Is the Way You Want to Remove from This Number 90 Number Will Be Converted into the Earliest Possible Number 132nd Urs Shravan Number Will Be 129 Vikas Will Be Removed From This Point 307 OK Software Decided To Remove In Order To Convert Giver Number To The Smallest Possible Number Solving Subscribe This Is The Giver To Find The Number Of Units Between Four Digit Numbers Can be done only in a moving from left to right the best all the best android least to the Sydney with love you are hidden that in two and numbers like two three four 5 Sentences with a small s possible number which you can form by Giving Combination OK Software Can Be Possible Numbers Have Shown A Good Sign For Changing Possible Numbers Ranges In Ascending Order With Minimum Digit On Left Side You Will Get Meaning Of Possible To Maintaining Its An Order From Middle East Possible Number One Tuition For Solving Problems According To The Question Veer is not its position Who can only move to remove the number in ascending order to be able to convert subscribe to the Page if you liked The Video then subscribe to Underwear Give in number and also from 282 letters they can remove only one Digit honge soaye just rot na customer subscribe this Video Most Obscene 1212 Subscribe And Is Hair Removing This Is The Meaning Of Possible Number Where Is Equal To Remove The Previously Seevy Channel Subscribe Number 90 Number One Will Be Seen Question In Order To Solve This Problem So Latest Se And Number K 137 So End And Key Value Request To That I Switch To Remove Vastu Defects And They Want To Remove The Number 200 Grams Representing Different If You Want To Remove Latest Busy Schedule This Is The Meaning Of This Is The Number 21 After removing it is the smallest possible number one does not know this is not be possible to remove this you will get the smallest possible number 2 this is the number with unnecessary 181 sources this is happening because dista is having more weightage in this app You can see the subscribe to acid from where does not care what is the height of the obscene 120 to subscribe already subscribe digit number which of this is it is this after removing any digit number which is the best app so I want to decrement this value For this leftmost digit is much possible so let's move will have to process elements moving from left to right and see when you find most difficult you will have to remove the previous PK element in order to fight and this graph which is already explained. Election Video then subscribe to the Page if you liked The Number 21 Nov Quid Price And You Know When You Want To The Second You Can Describe School Me Entry Form 2018 200 Already Told You Will Have To Remove The First Pick Places Where They Will Remove Second and they will get the result number S2 110 will be the answer for class 9 4 9 0 in special case 120 from this 20 subscribe The Channel element wheeler to wheeler which you can only move to 9 0 7 subscribe beautiful left side of The second example you can directly show the values the first directly show the values the first directly show the values the first DP by going in from 3202 you will remove this first pick's individual decrement saver mode settings pair decrement nine ten one is pet so you will have to remote's LED 120 no limits of nine you Can See The Number 107 But They Have To Leave Subscribe Now To The Number 989 Solved Example In Order To Get Better Understanding Digit Number And Were Given Away To Remove From This Is This Value So Much As Possible To Be Possible After The Data Structures Can We use in order to remove the previous pics 24 Want to keep track of this pic dried The previously selected picture will have to basically take the ascending order History and Storage Ever Swift Want to keep track of this type of history The Best Director's Best 108 will also be used To Latest Extract Notifications Pack Abs For The Post Element Will Always Love Later This Is Not Difficult Subscribe It 90 subscribe The Video then subscribe to the world will be lit Decisions Gas The Top Of The State Is Better Than This Current Elementary Live In This Case Also Remove this point Naveen compare with top special value 1510 will also push very love you want to be next element and will also decrement its value to three love this is 10 top 10 history for this is to maximum so this is pe elements of obscurism will just Removed due to which will help you and the will take you to 9 we want to remove will rule 10 20 number building and they are currently 0 users click this vikram leading cirrhosis vishal removed all the ladies gents 1430 half to the number 90 singh one- Way Traffic Jam Sunnah * Compare singh one- Way Traffic Jam Sunnah * Compare singh one- Way Traffic Jam Sunnah * Compare One Will Be Pushed Singh Shyam Singh To Know The Six Dravya Maximum Officer Singh Maximum Subscription Will Just Removed And Avoid 2009 Se Subscribe 120 Avoid Every Element And Industry Will All Elements Which Gives You Table Number Is 120 Know What Is The Time Complexity The Solution Between Is Just Once Were Processing Disinterest Win Only Once And Space Complexities Also And Sons Were Using Stack So Let's Not Look At The Code Shown In This Code Were Value K Vitamin E Didn't Want To Remove No I Will find what is the number of units which will take you will not the previous maximum element subscribe our processing industry and subscribe elements of elements first free hand pure ki value he absolutely sweet se to denge is dahez pe element yonder left side of any Digit So Nothing Will Be Removed But After Processing The Kids In Every Thing Will Be Pushed Into The Doctor Away Now You Can See Your Values Through And Subscribe The Elements From The Will Only Be Elements In Increasing Its Rule Over Subscribe And Subscribe To The Channel School From this thank you have element to the first maximum subscribe quilling tank level after bj phone this is a special case this pure key value still left and youth where is not entirely different that when the day this is that gives equal to a dream defect Let This Audit Be Removed And You Will See The Returns 09 Samudra Ke Self Mein Arise Latest You Number One 020 Cases Have Enough But You Will Simply Remove This 21000 Subscribe Digit Number And This Type Of A Take Care Of Yourself Thank You Will Have To Elements from Sydney with Love Story subscribe and phone number 100MB basically storing the number from the right hand side ok and after scoring number to table point the number will simply tag 10 substring starting from the opposition to the Video then subscribe to the solution in different Languages and Placid Like Share and Languages and Placid Like Share and Languages and Placid Like Share and Subscribe
|
Remove K Digits
|
remove-k-digits
|
Given string num representing a non-negative integer `num`, and an integer `k`, return _the smallest possible integer after removing_ `k` _digits from_ `num`.
**Example 1:**
**Input:** num = "1432219 ", k = 3
**Output:** "1219 "
**Explanation:** Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
**Example 2:**
**Input:** num = "10200 ", k = 1
**Output:** "200 "
**Explanation:** Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
**Example 3:**
**Input:** num = "10 ", k = 2
**Output:** "0 "
**Explanation:** Remove all the digits from the number and it is left with nothing which is 0.
**Constraints:**
* `1 <= k <= num.length <= 105`
* `num` consists of only digits.
* `num` does not have any leading zeros except for the zero itself.
| null |
String,Stack,Greedy,Monotonic Stack
|
Medium
|
321,738,1792,2305
|
426 |
hey everybody this is Larry this is me trying to do an extra bonus premium Farm oh yeah I hit 1900 so maybe that's to celebrate uh let's do it let's do one they haven't done before hopefully how do I do this yeah uh medium let's just say and maybe we'll get an SQL question because I feel like that happens a lot okay not this time though outside friends my watch is telling me that I should sleep soon well let's finish this one quickly then shall we um hit the like button hit the Subscribe button join me on Discord hope y'all are just having a great uh beginning of the weekend and all this good stuff and April Fools and all this stuff don't get fooled by things on the internet hopefully uh I mean you know but still have fun I guess so I'm gonna drink a little bit sip of water today's form is 426 convert binary search three and two uh sort of doubly linked list that sounds like a mess actually uploaded linked list not just well I still ahead oh is that the head just to like say what well okay so the tricky part is that we have to do it in place but oh that's why I didn't read even the second line but I was just very I just read the title uh okay so basically you want to use uh let's left is to go to previous and right as you go to next okay and then okay let me think about this um that's actually maybe an interesting problem I mean it definitely is a problem that you don't really see in competitive programming um so Mega live sometimes I struggle on those just because it's uh it's almost like a different set of tools you know um I mean it may not be hard but it is new and different to me because in competitive uh way or very rarely you're going to see problems like this just because how they're gonna check it right and of course even here they can't really check it per se um what they you know I mean but at the end of the day you're only cheating yourself right so that's you know you're supposed to uh do the enforcement yourself okay so the only two thousand notes hmm I thought maybe there's a linear thing but now I'm thinking maybe there's a quadratic type thing and whether that um that would be interesting the In-Place part is a little bit scary the In-Place part is a little bit scary the In-Place part is a little bit scary because it means that you know um it's a little bit tricky right um and there are a couple of constraints that I want to um enforce a little bit on myself at least initially if I can't get it then I'm you know maybe be a little bit uh looser under the constraints um is that because we have to we want to do a transformation in place I'm going to try at least initially like I said to use only all of I want to say all of one extra space other than maybe stack um but we'll see how that goes uh because you know like the core stack maybe that's gonna be linear anyway so maybe that's an awkward thing to say um but then the other thing is that given that n is equal to 2000 meaning that you if you can do quadratic then do you still need extra space right like sometimes the trade-off is going to be sometimes the trade-off is going to be sometimes the trade-off is going to be linear time linear space and or n Square time or one space right and then it's like well which one do I really want or n log I don't know something like this right so we'll play around with a couple of those ideas and then really think about it I think these forms to me um I don't always do them in the sense I don't always do this rather um in the sense that uh you know I have I've had enough practice to kind of wish have uh visualization in my head but what I was gonna say is that I do uh recommend having uh actually like real pencil but I what I was gonna say is I do recommend having notepad and just draw things out um and that would help him get a pencil real quick um I kind of destroyed out um I kind of see you know um explore the properties of these things right and I think one of the one thing that I would also add and I kind of mentioned this a couple of days ago during one of those other prompts um is that uh you know in some problems you see me do this where I'm way slow I mean you know so if you're here to kind of just get an answer explain that um you know well this is probably not that but I would also say that this is how you get better right um when you see me like in the future prom hopefully anyway and you see me doing it you know the first time I do it maybe it'll take 10 minutes and I see a similar problem that's different but I could use the idea and then do it in five minutes instead right that's what practice is right it's about you know uh well one thing at the way at least is that it means that you don't have to reproof things that you proved in the past and you see like properties that are you know either true or false and like oh no I knew I know this to be true because I proved it last time right so stuff like that is how you kind of get better as well um uh especially on the hot really hard problems it's about like combining like three or four of these observations together or maybe five or whatever and if you spend your time proving each individual thing then it's gonna uh just eat up your time right uh so yeah anyway all right let's see I'm drawing the first example right now and then kind of just playing around with um with uh yeah and I know that maybe I could draw on screen instead um but I think the way I think I'm still like old school I'm old I started out so you know uh well I didn't start it off but I started a long time ago is what I mean so I'm trying to think about you know what's the proper way to do this right um I think intuitively the way that I would consider doing it initially is going to be um with a stack right what would the stack or uh like a recursive stack what would that look like um you know uh if we want to do it in order then we probably would do want it to uh what is this head oh do we just return head okay uh and that's just the first element so we could probably I mean that part is probably easy but um because you just take the leftmost element right but basically we only do like uh in order to restore is what I was going to say to do the recursor uh recursion and then okay so then now just looking at this particular example it's going to uh so now we had one we're gonna pass in the parent so that now uh one will point at two with the right because that's the next and then left we leave it whatever for now uh and then we go back to two is pointing to one to the left which is actually good but we what we want is return the node that is the smallest on the left when we return because right now one is a leaf that's why I'm able to kind of just be a little bit sloppy a little bit lazy uh about it but you'll say we have a 1.5 what does that you'll say we have a 1.5 what does that you'll say we have a 1.5 what does that look like well then the next note is going to work and then we passed so we pass the parent um so the thing the tricky part about this is that when we do it in place no okay I think I'm making a little bit more complicated than it needs to be because I'm trying to be a little bit careful to be honest um I think one thing that I was very um I think that one thing that I'm very worried about is that if I change some like you can only do this recursion once because uh like this traversal once because once you change the links you may lose the original lengths right but now that I think about it if you keep track of the first node you can if and if you because I think one thing that I think I'm made a little bit complicated is that I was trying to do both at the same time in that like both the forward links and the backlinks right but if we are able to just kind of do a sorting if you will um then you can just Traverse it a second time and it just like put everything backwards right so I think this is actually pretty straightforward I think I definitely um I'm trying to be careful but I well I would say it's straightforward but I think I have to algorithm in my head so it's like a classic uh mathematician joke right like everything you don't know is impossibly hard and everything you do know is Trivial no matter you know there's no you know nothing in between right so before I uh prove to myself it's why I'm like oh this is ridiculous and now I'm like oh yeah straightforward of course you know uh okay so yeah 10 minutes in though so definitely taking my time on here but uh but yeah let's do it um so the I say head is you go to uh node of negative one or whatever and then now we the smallest element on the tree is going to be left most node right so um current is equal to root while current dot uh left is not none current is you go to current dot left and then yeah and then uh head dot next uh it's very awkward there is no next better okay fine Dot left is you go to current right okay so then now this is the smallest node right okay and then now we just do a um in order to reversal right of a no and this is I'm gonna do it like uh almost like a crappy Morris traversal for a thing but not really um I'm just gonna take care of the extra space so then we just do um yeah so left is you're going to note that left right is going to know that right I'm using I'm um having these references now I mean I don't know that this is necessary but the reason why I have it um as these references is because if I make um make changes this will still be kept on the color stack which will make this a little very linear time thing or sorry linear space thing obviously it's gonna be linear time at least and we'll see how this goes um yeah and then you basically process left in order uh note that left in order to know that right and then do something of the current node right what we want is that you know let's say we have a previous node dot right as you go to the current node right and that's pretty much uh the idea so previous as you go to none um yeah non-local please if priv is not yeah non-local please if priv is not yeah non-local please if priv is not none then we do this and then after that previously go to node so then yeah this is kind of a very cheesy way of doing it to be frank but oh I did lie though because this should use left and this should use right I think we don't manipulate the left so we actually probably okay here but for code symmetry reasons you know it's a little bit easier to kind of figure out where you went wrong in case when things go well um and this is not sufficient but when we turn head down left and then see what it complaints it gives us um okay yeah no attribute is a good way but yeah but now left will have the node um so current is going to hit that left and then you basically do something like um while Kern that left or to current dot right is not none uh then current is going to turn down right basically now you have a linked list and then you just have to kind of go back right so current dot right that left is equal to current and that's pretty much it probably and I'm probably wrong hmm oh something is none where is it going 80s no 86s oh that's awkward I mean that's an awkward error as well uh okay I mean we still want to debug it obviously because we want to submit the problem I don't know why I say it like this but uh but yeah um we can just add some print statement and maybe that'll be okay for now uh it doesn't even want to put none type there's no attribute right but do I return none um it's way awkward I don't know what dish I mean this is just a very crap you ever message really or like it gives me no way to kind of um do anything about it right so I guess we can just return uh root Maybe does that give me anything no okay they give me some stuff yeah okay I mean that's fine um but why is headcart left not right is this going to yeah so couldn't that left should not be let's see now we got this print stuff um okay that's not very useful but still nice okay hmm so what is wrong here is that still true here am I confused but also it means that hmm we're confused but I just never execute this should at least be uncut it let's play around then I mean I don't know am I doing we could oh I am dumb I get it uh it turns out in code uh a very fundamental thing you want to do is uh just that's not true uh a very fundamental thing you want to do is call the functions that you write so that you can kind of see stuff I mean now there are other issues but that's fine right I forgot usually pretty good about this but I forgot to write the base case for this one um okay all right it's still an issue uh oh I didn't make it circular that's why um okay uh so then now we have basically a link a doubly linked list but I didn't make it circular oh and also I didn't return the correct one anyway so this is gonna be the same ever probably because we still didn't make it circular Larry so um Okay so head.life so this that left is Okay so head.life so this that left is Okay so head.life so this that left is equal to the last one which is maybe current is yeah because that should be the last one and then current that right as you go to head that left maybe something like that yeah okay I can't believe uh just a lot of silliness happy April fools I mean uh it looks okay right so let's give it some um before I do that I want to test a zero case uh real quick actually they don't always have problems of zero case but you know okay good Gucci uh it's way awkward though hmm whatever fine yeah oops the wood is none we turn none and whatever right save me a wrong answer hopefully I saved me another one okay good uh yeah pretty straightforward really but I um yeah I don't know I just kind of got confused I think uh oh I'm not gonna lie I mean this is this type of problem is something that like I said in the beginning uh I just don't have that much practice on um so you know I'm trying to give it a healthy amount of respect and that um I don't know that makes silly mistakes right so yeah um I think that's all I have for this one so let me know what you think I hope y'all have a great weekend I'll see y'all soon uh stay good stay healthy to good mental health goodbye and take care bye-bye
|
Convert Binary Search Tree to Sorted Doubly Linked List
|
convert-binary-search-tree-to-sorted-doubly-linked-list
|
Convert a **Binary Search Tree** to a sorted **Circular Doubly-Linked List** in place.
You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.
We want to do the transformation **in place**. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.
**Example 1:**
**Input:** root = \[4,2,5,1,3\]
**Output:** \[1,2,3,4,5\]
**Explanation:** The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship.
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[1,2,3\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-1000 <= Node.val <= 1000`
* All the values of the tree are **unique**.
| null | null |
Medium
| null |
1,802 |
welcome to Pomodoro Joe for Saturday June 10th 2023 today we're doing leaked code problem 1802 maximum value at a given index in a bounded array this is a medium problem you're given three positive integers n index and Max sum you want to construct an array nums which is zero indexed that satisfies the following conditions the length of nums is equal to n all right so we have exactly n elements nums at index I is a positive integer where 0 is less than or equal to I Which is less than n okay so for every element in our array we have to have a positive integer so it has to be at least one all right the absolute value of nums index I minus nums at index I plus one is less than or equal to one where zero is less than I Which is less than n minus one so this is just saying that every element can only be at most one away from the previous element so it can be the same or it can be one plus one or minus one but it can't be anything greater than that all right the sum of all the elements of nums does not exceed Max sum all right so the sum of our entire array can't exceed Max the sum and nums at index maximized okay so we have a peak where we maximize our value at nums index return the nums index of the constructed array note that absolute value is equal to blah okay so wow this is a tricky one to understand but here are the basics number one we have to construct an array but we don't actually have to construct the array we just have to conceptually construct the array but we're tasked with creating an array of exactly n elements in length we want to maximize our value at the index but in order to do so we have certain constraints every element in the index has to be a positive integer so it has to be at least one every element in our array has to be equal value or 1 plus or minus the previous element but it can't be anything greater than that you can't have a Delta greater than one all right so this is a tricky problem we'll put 25 minutes on the power door timer and we will get started okay so for this one I think I'm going to do an exhaustive search or a bounded search they're called a bounded array so I'll call it a bounded search now a bounded search is basically we can find a lower bound and an upper Bound for our value-add index then we can just for our value-add index then we can just for our value-add index then we can just search every value in between finding the maximum one that satisfies the conditions that lay that are laid out right here so let's see what pieces will we need well we'll need some Min value to start with I'll just set it to none at the beginning and we'll need a max value to start with so we'll go between the Min and the max value let's see we'll need some result at the end we'll return our result let's see this has to be at least one so we have a Min value and a max value let's see we'll also create some function checking whether or not our value is valid we'll just call it as valid take some value X and for now we'll just pass and then we just have to go for every element so we can just say for I in range from the Min value to the max value plus one because we want it to be included we'll just call let's see if is value is not value is valid it's valid and we'll pass in this I then we'll just continue it's only when we're not valued then okay if it's not valid then we can return I minus 1. how about that but then we let's see we could go from the max value to the Min value with a step of negative one and as soon as we find one that doesn't work no as soon as we find one that does work there we go so we'll go from the max value to the Min value minus one as a step of negative one and if we find a valid answer we can just return that answer otherwise if we get to the end we can return our Min value here hopefully this will have actually returned in here but just in case all right now I have to create this is valid okay how do we figure out if this value is valid all right well let's take a look at our array here we know it has to have at least ones so I have a bunch of ones let's just choose five to start with here let's say we're allowed to have our we're looking for a maximum value at index two so that's 0 1 2. so we can make this two and that'll fall off to one and one but if we make this 3 then this Delta is too great so we have to make these two and then one and so on and so forth and then this if we made this four this could be three but then this would have to be a two so it kind of depends on our Max sum here so we could have some value we don't necessarily have to go down to one it really depends on our Max sum so what is our Min value well let's see our Min value would be if we just divided our Max sum up among every single one of our elements it's actually that should be pretty easy so that's Max sum that's I'll do an integer divide by the number of elements we have and that's our Min value now what's our maximum value let's see if we have our Min value so that's just leveling off this playing field right so let's say these are all fives one two three four five so that's leveling off our playing field now if we pop this one up to six this one can be five and this one could be four so then we could pop this one up to seven and this could be six and this could be five so it looks like it depends on how far away we can get from our index so the minimum value would have to be the one or sorry the maximum value will have to be the minimum value way out here at the Edge Plus n divided by 2. well it's not necessarily divided by two it's divided by two in this case because we happen to be in the center but if we were way at one Edge we could have basically a slope down by n elements so most we could have Max sum or sorry our max value would be our Min value plus n I think Okay so our Min value could actually be smaller though that's interesting there's probably a better max value here I bet we could find a better max value but I think this is our maximum value so we'll start with this all right back to is valid okay so in our array here we kind of have five zones so we have our index in the center or index on one well I'll call it the center it doesn't have to be the center of the array but it's the center of our zones so we have the index then in order to maximize our index we need to minimize all of the other values because we have to stay within this maximum so in order to maximize our index we make it the max we minimize the other values which means starting from the max at our index we will slope down at a rate of one per element so this is like our slope we'll be decreasing our values on either side of our Peak here so Zone one is our index it's the peak then we have zones two which are sloping down on either side to the left and to the right because we're trying to minimize those values then we have our final area where Let's see we might reach the end of our array so we stop or we end or we flatten out because this could end up hitting zero and if we hit zero we can't really have zero values for our elements we have to go to ones so we'll go flatten out and that will go to the end and we'll have that on both sides so this will either be the end or flat so these are like our five zones the Peak at our index we slope down on either side and then we either hit the end of our array or we hit a flat where we basically just have ones until the end of the array that's a lot to keep track of all right so let's just do this okay so we need to figure out if all of these values summed up is less than our maximum or less than or equal to our maximum so we'll have some value here and it will start as X because we have at least X at our Peak here then we need to add to that a certain amount on either side our slope here oh boy so what do we add to this well we need to essentially create some we need to know how many elements we can go to the left and to the right so how many elements are in this slope and then how many elements are in the flat if we have a flat okay so I'll have this like slope left slope right and flat left and flat right all right let's do that so let's figure out how many elements are in our slopes slope left actually we should start with flat left well oh this is going to change depending on our input so the slope left and the flat left will change depending on our Peak if we have a high peak then we might not have any flat if we have a low Peak we might have a long flat there's a little bit of slope so it can't really have a slope left but I could have the number of elements to the left and to the right there we go so we'll have left elements our element count we'll call it left count so this is how many elements are to the left of our index so that means this is just index all right and then our right count how many elements are to the right of our index well that should be our total n minus one because we're taking away our index itself and then minus the left count that makes it easy sorry for Min value or max value or left count and our right count cool now we have to fill and we still have to figure out our left slope and our right slope now these are going to vary depending on this value X all right how do we figure those out let's start with our left slope we'll just do the left slope count I believe that's going to be our the count that we can have here so we can have x minus 1 in our slope and that should be the same for the right okay oh but that is going to be our index so this is going to be our index plus x minus 1. as long as it's less than n otherwise it'll be n ah this gets really tricky so we have to figure out whether or not we're going to hit our end and this is the same thing here we can have x minus 1 but it's going to be the index minus x minus 1. so I'm not making very clear with the semi so we're looking at our index how far to the left can we go with our slope so at our index we have value X at the index before our index so at index minus 1 we can have x minus 1 that's our value and we can have x minus two x minus 3 as we move back to the left we're decreasing our values at those elements so as we're moving to the left we can move at most X spaces or x minus 1 elements before we hit zero now at zero we can't actually have a zero element so we stop at x minus one so as soon as we reach x minus one all the elements before that will be value one so we look at our index we can go at most x minus one elements to our left before we flatten out so this is index minus x minus 1. so this will be the index at which we have to flatten out but our X could be let's say 10. let's let me choose some large value 10 but our index could be two well we're going to hit the beginning of our array before we ever flatten out so we actually have to do a minimum of this or zero and same thing with our right slope we have to do a maximum I know a minimum again a minimum because we could exceed the bounds we'll do index plus x minus one because we're going from the index to the end or n minus 1. whichever one is smaller okay so that's going to give us our left and our right and this shouldn't actually be count this should be index right so that's our left slope index and our right slope index and then our flat let's see left flat this will actually be a count that's going to be essentially just our left slope index so that's a lot so this is going to be essentially we'll have a bunch of ones one until we start sloping up two three four five so whatever this index is so this is zero one two three looks like it's going to be index plus one let's say our right flat okay out and this will actually be n minus one so we have to start at the very end and we'll subtract our right slope index I'm going to speed through a bunch of this right now this is just finding the boundaries of these different areas it's not super interesting you can check out my code in GitHub or you can jump to the end where I go through it a little bit better later on all right here back to the program so now we actually have to figure out how these help us in terms of calculating the value at these elements or the sum of the values of these elements so we'll have sum of elements and we'll need to start with some X we need to know the start value and we need to know how many there are so count okay so we start at X we have count number of elements and every time we go through we have to remove one from our X so our value will start as I guess zero okay go account and so let's see we will say vowel plus equals x minus r i so we'll take away one we'll start with taking away zero then we'll take away one then we'll take away two three four and that gives us our slope all right and we will cache this because I'm pretty sure we'll be doing the same values over and over again so we start our value at X then on the left and the right we'll actually go down to x minus one so let's see we'll actually have to calculate our value add our left slope so we'll add the sum elements all right so this will be x minus 1. and we'll have left slope count I'll have to create that and then the Val plus equals the sum elements starting at x minus 1 again and then be the right slope count and then we need to add our Flats basically so the left flat count could be zero okay this is also where we need to do some checking on our bounds because those might be zero and then the valve plus equals our left flat count again those are the number of elements but they'll all be equal to one so we'll be adding that as just straight up value here and then at the end we will return whether or not our value is less than or equal to our Max sum wow that is a lot of work and I still haven't done this left slope count yet alright so the left slope count well we've figured out the index I think that'll just be our index minus our left slope index double check this and this will be the right slope index minus our index hmm I have very low confidence in this only one minute left let's just see how this goes oh that does work okay we'll submit this and see how we do I'd be surprised if we pass but let's check it out we have a wrong answer so we'll use this test case let's see I was pretty sure at this point that I had something wrong with my boundaries calculations this for the slopes and the flats I think I was off by one somewhere so I actually had to revert to going to pencil and paper drawing out some diagrams unfortunately I don't really have software here to show that to you so I went offline I stopped the video did my diagrams came back and then I corrected the errors in my calculations and we'll jump back in here and we're back sorry I had to take a break and do a little bit of Investigation here so after some investigation turns out finding these indices can be really tricky so I'll show you what I ended up doing and I'm just going to fast forward through this to spare you some of the trial and error here so the first thing this was wrong I don't want the minimum of the index or zero because this can result in negative values I really want the maximum of this or zero the other thing that I had wrong here I'll just jump ahead so that's one thing I had wrong another thing down here this should be from n minus 1 because we want to go from the last index okay so this does seem to work at least for the test cases let's try this all right so that works for the test cases again finding this indices was kind of tricky so that's why I had this print here all right let's submit this I don't think this is going to run in the time that we need but it's worth a shot yep time limit exceeded we only get 127 out of that 370 test cases wow okay so we'll add this test case to our list here and we'll try it but we're going to have to do a couple different things for this one I mean really beating a third of the test cases oh that's interesting it shows us beating this test case now all right well first I'll get rid of this because we don't need this anymore next instead of going through every single value let's do a binary search and binary searches are fairly straightforward but let's just get rid of this so now we'll have a low and a high so the low index will start at zero and the high index actually it's not going to be an index is it's going to be the value that we're searching for so this will be the Min value and the high will be the max value now while our low value is less than our high value well then we'll find the mid value what's the midpoint well that will be the low Value Plus the Delta between the high value and the low value divided by two so this would be high minus low and we'll do an integer divide by two so this will basically find the midpoint between high and low by finding the difference between the two finding the middle point of that distance and then adding on the low so we get the base now that we've found our midpoint we check if it's valid so if is valid the midpoint this is a valid midpoint then we can raise our low to the mid plus one if it's not a valid midpoint then we need to lower our high down to the midpoint okay so that works so now we have our basic binary search searching between our low and our high which is our starting Min value and our starting max value let's just see if we can pass time limit exceeded but we do a little bit better 212 out of the 370 test cases so we'll add this test case to our list here all right now we need to get into some more mathematical things so at this point we have our binary search we're just checking values between the low and the high doing a binary search pattern now R is valid is slow we're basically doing a lot of calculations and this is valid this is where I had to actually look do a little bit of looking at because it's been a while since I've done this type of math but what you can use instead of doing this type of iterative approach to summing up all these values you can use a mathematical approach now this is an arithmetic sequence so there's something called an arithmetic sum and let's see if I had to look this up so I'll try to leave a link in the description let's see if I can remember how this goes in fact I am just going to copy and paste it all right so the arithmetic sequence formula goes like this the sum of the sequence will be the element at index one at the start of the sequence plus the element at the index at the end of the sequence and that whole thing will be multiplied by the length of the sequence divided by two and note that this is a floating Point divided by two so this will give us the sum so instead of having to do this sum we can actually do this sum which should be a lot faster now in this case we actually need the element values at index 1 and index n which is a little bit different than what we have where we have the end value and the count so some of this will be the same this n value would be the same but the start value might be a little bit different so we need to change some of this actually do we need to no we can actually calculate our start value from these two elements let's see if we can do this I'm not sure this is going to work but let's give it a shot let's see this will be our x minus our count or one whichever is bigger so either start at one or we start at x minus the count I think it might be x minus count plus one and the N value will be X and now we do our sum here so we'll return let's see this will be start value plus the end value times our count divided by 2. all right so that should give us this value nothing else needs to change in here let's see if this still works oh that works and we're passing this test case all right let's submit that see how we do and we pass I'm actually a little bit shocked by that all right and we do okay we beat 33 for runtime and 53 for memory not too bad not great clearly there's a lot of room for improvement here but there's still a lot this is pretty messy so you could probably go through and clean a bunch of this up unfortunately I am really low on time I'm probably not even going to have time to edit this and get it posted today so apologies if you're seeing this late but it's a tough problem this is actually a pretty tricky medium mostly because I didn't remember my arithmetic sequence formula so I did have to look that up all right so for this one we're using the exhaustive but bounded search pattern so we basically find our Min and Max values that we know we have to be somewhere in between then we'll do a binary search between those Min and Max values using in this case an arithmetic sum to try to figure out the sum of all the elements in our array so this one's super tricky for a medium problem not as tricky as new 21 game but still pretty tricky okay that is it for me hope you enjoyed this hope you had fun hope you learned something hope you can go out and write better code
|
Maximum Value at a Given Index in a Bounded Array
|
number-of-students-unable-to-eat-lunch
|
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions:
* `nums.length == n`
* `nums[i]` is a **positive** integer where `0 <= i < n`.
* `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`.
* The sum of all the elements of `nums` does not exceed `maxSum`.
* `nums[index]` is **maximized**.
Return `nums[index]` _of the constructed array_.
Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise.
**Example 1:**
**Input:** n = 4, index = 2, maxSum = 6
**Output:** 2
**Explanation:** nums = \[1,2,**2**,1\] is one array that satisfies all the conditions.
There are no arrays that satisfy all the conditions and have nums\[2\] == 3, so 2 is the maximum nums\[2\].
**Example 2:**
**Input:** n = 6, index = 1, maxSum = 10
**Output:** 3
**Constraints:**
* `1 <= n <= maxSum <= 109`
* `0 <= index < n`
|
Simulate the given in the statement Calculate those who will eat instead of those who will not.
|
Array,Stack,Queue,Simulation
|
Easy
|
2195
|
674 |
hey everyone welcome back and today we'll be doing another Elite code 674 longest continuous increasing subsequence this is an easy one given around saute sorted array of integers num return the length of the longest continuous increasing subsequence the subsequence must be strictly increasing so in this case we are going to return 3 because we have increasing subsequence 1 2 3 and 4 is just putting you can say n to our uh longest increasing subsequence and here we can have another C subsequence which of which length is 2 but now we have the greater one which is 3 will be returning the greater one so if the elements are same and not in increasing order then output is one because it should be a increasing order it should be in increasing order so we'll be making a result and an anchor variable which will be 0 and so for I in range of length of nums we will see like if I is greater than 0 and nums at I minus 1 what happened I minus 1 is greater than or equal to nums at I then we are going to just anchor put anchor to wherever our I is and in the next part we will just take the maximum so the maximum of result and I plus not I plus but I minus anchor because I is going to be our ending you can say ending point and anchor is going to be our starting point so I is always going to be greater than the anchor or equal to and now we can just add 1 because we are going to return it in the case where and not by indices just by lens we'll be returning uh adding one and we can just return the result and that's it so what we are doing here is we have three five four and seven so at first I will be 0 and anchor will be here like here anchor is here and I is also here and now we will keep increasing our eyes so the I is going to be increase and I will be here when at when we have you can say 3 in our result because anchor is basically 0 and I is at 2 and adding 1 2 I is because this is the second index 0 1 2 so that's why I is 2 and the result will be holding 3 at this point and whenever we have our next value uh a value at we are on is less than the value which was previous we are going to take our anchor to wherever our I is y is at this position and what this will do is just cancel out I and anchor will cancel out each other and this will start the repetition again and now I will be becoming 2 at this point anchor will be staying here anchor will not anchor is going only going to increase when there is a case like this the value we are on is less than the value which was previous so we are saying uh I is greater than 0 because we do not want to just uh go out of bounds like previously if you start from here then we are not going to have I minus 1 greater than the IDR on so at the end I is going to have 2 and the result is going to have 3 so this is just basically result is just greater and will be returning result at that case so that's it
|
Longest Continuous Increasing Subsequence
|
longest-continuous-increasing-subsequence
|
Given an unsorted array of integers `nums`, return _the length of the longest **continuous increasing subsequence** (i.e. subarray)_. The subsequence must be **strictly** increasing.
A **continuous increasing subsequence** is defined by two indices `l` and `r` (`l < r`) such that it is `[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]` and for each `l <= i < r`, `nums[i] < nums[i + 1]`.
**Example 1:**
**Input:** nums = \[1,3,5,4,7\]
**Output:** 3
**Explanation:** The longest continuous increasing subsequence is \[1,3,5\] with length 3.
Even though \[1,3,5,7\] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element
4.
**Example 2:**
**Input:** nums = \[2,2,2,2,2\]
**Output:** 1
**Explanation:** The longest continuous increasing subsequence is \[2\] with length 1. Note that it must be strictly
increasing.
**Constraints:**
* `1 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
| null |
Array
|
Easy
|
673,727
|
1,955 |
come on easy question okay hard question all right given an array numbers consisting of only zero one and twos return the number of different subsequents that are special in special means if it consists of positive number of zeros positive followed by a positive number of ones positive number of twos since then says larger return at modulo 10 to the power of nine plus seven subsequence of arrays of sequence that can be derived from the array by the links some are no elements without changing the order of the remaining elements two subsequences are different if the set of indices chosen are different so you have ten to the power five numbers okay that's quite a lot of numbers let me think it's definitely dp so dynamic programming what would the sub problem be well i guess the answer for a sub array but i can't do n squared sub arrays of the two maybe starting from the first and then continue when i add another number what i can do is add to the answer all that this extends fair enough i think i have a better idea how to solve this if i have a dp i1 number of subsequences ending with a 1. ending with zero limits of sequence is ending with a two so let's say for example we added two then i add to this dp position whatever this is which could be zero what if i see all zero if i see a zero then i just add one to this because i could be starting a new subsequence ending at zero or i double this as well because i'm adding this to all previous zeros so i get two times this plus one if i see a zero so if nums at i is equal to zero on dp i at 0 times equals to 2 and also dpi 0 plus if nums i is equal to 1 this will be equal to whether i add it to itself which would be times 2 or dp of i 1 plus equals to dp of i zero so that means i add it to a subsequence ending at zero if nums i is equal to two i could be adding it to itself or a subsequence ending at one and i don't need of n space i could just do this in constant space because i don't need to keep track of the previous dp values i also have to make sure i return that the answer modular this do i have to take the modulus as i go along maybe most likely let's give that a go so i have let's type def long as ll and then we can say ll zeros ones twos for int i is equal to zero less than numbers.size numbers.size numbers.size this was i if nums of i is equal to zero okay i actually haven't tested whether this works or not yet so let me see let's try an example zero one two when i see the zero this becomes a one these are zeros initially when i see the one i multiply this value by two which is zero plus number of zeros which is one for the two here when i see the two i multiply this zero by two which is just zero and then i add one to that so that's just one and then i see the two here i multiply um this value one by two so it's two plus um the values here which is one so that's going to be three you know what i could just copy and paste this one ones zeros twos ones and at the end return twos let's do the modulus thing so const static int mod is equal to one e nine plus seven zero is modulus equals two odd times model c equal to mod twos modulus equals to mod at seven um i don't know let's see nice not bad that's the first time i actually um hard question that's not actually that hard on the first code so kind of proud of that thanks for watching um like and subscribe keep using the code and i'll see you in the next video
|
Count Number of Special Subsequences
|
seat-reservation-manager
|
A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s.
* For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special.
* In contrast, `[2,1,0]`, `[1]`, and `[0,1,2,0]` are not special.
Given an array `nums` (consisting of **only** integers `0`, `1`, and `2`), return _the **number of different subsequences** that are special_. Since the answer may be very large, **return it modulo** `109 + 7`.
A **subsequence** of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are **different** if the **set of indices** chosen are different.
**Example 1:**
**Input:** nums = \[0,1,2,2\]
**Output:** 3
**Explanation:** The special subsequences are bolded \[**0**,**1**,**2**,2\], \[**0**,**1**,2,**2**\], and \[**0**,**1**,**2**,**2**\].
**Example 2:**
**Input:** nums = \[2,2,0,0\]
**Output:** 0
**Explanation:** There are no special subsequences in \[2,2,0,0\].
**Example 3:**
**Input:** nums = \[0,1,2,0,1,2\]
**Output:** 7
**Explanation:** The special subsequences are bolded:
- \[**0**,**1**,**2**,0,1,2\]
- \[**0**,**1**,2,0,1,**2**\]
- \[**0**,**1**,**2**,0,1,**2**\]
- \[**0**,**1**,2,0,**1**,**2**\]
- \[**0**,1,2,**0**,**1**,**2**\]
- \[**0**,1,2,0,**1**,**2**\]
- \[0,1,2,**0**,**1**,**2**\]
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 2`
|
You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an element, in a reasonable time. Ordered sets support these operations.
|
Design,Heap (Priority Queue)
|
Medium
|
379
|
958 |
hey what's up guys this is shown here and this time let's continue on this on our tree journey here so today we're gonna talk about this number 958 check completeness of a binary tree so for those who doesn't know what the complete binary tree is so complete a complete binary tree and then if it's not the last level all the nodes has to be filled and you're only allowed to have a missing node on the last level and but you're only allowed but on the left side those means the missing node on the level of the missing node I don't know that I'm you have to be filled ya have to be fused basically you need to have the last nodes I don't know the field as a left as possible yeah for example here you know there's a 7 here but you put a 7 here but you have a missing node here listen this is not allowed right you can only allow to have one missing down there on the right side and so how do we do it I mean they're like I think many ways of doing this problem so the first one is to you know you can keep counting the index of each node right so for example this one has index 1 right 1 2 3 4 5 6 yeah basically the same thing here and you just have a right here you have array to store all the indexes here all the index or index in this industry right and remember you have to press a price level search which is the other level other Traverse so you have one here to remember this is the index right 3 4 and the end to the six right and in the end you just check if the last index is equal to the length of this array right if the same then it's a complete binary tree if it's not for example this one went to three four three one two three four five and the last index in this array will be seven right will not be six then it's not and then it's after right and how can we track each of the two note the note index here so basically we start from root node one right start from the root node one and every time when we see a note here we just use the current index times two equals to the left sub the left node and then current index times two plus one to the right node right and then we skip traversing for the whole tree in the end which do this comparison yeah that's obviously our oh and compound time complexity and oh and space complexity right and that's one way the other ways is that we you know we can like most likely we're gonna we would be able to stop to traverse earlier right how right so if you watch closely you know every time you if we see a gap and there is like another node after this gap then we know this is a nuts like complete binary tree right because I'd like to remember we're doing this we're doing the other level Traverse so we do one two three no gap right four five gap six no gap see there's no gap until we traversed which reverse all that complete tree here for example this one 1 2 3 4 or 5 to the 6 here right ok we saw a gap and then we see another node then we know it's not a complete tree right another example will be like 1 2 3 let's see then 4 5 let's see there's a 6 here right and then we have some other nodes here I'd say there's like 8 right 9 and 10 right so in this case the last level it is fine because all the left side are filled but on the previous level there's a gap here right but remember we are doing this row level trigger I'm sorry that the lab or other papers here so we're doing 1 2 3 right 4 5 6 and then when we try to find the right subtree here it's nothing here there's nothing here then we already know we already saw a gap here and then once we reach this level ok we saw a gap then it's not a complete true complete binary tree right so the I think should be pretty clear what we need to do here right so first spiritual here to do the row level Traverse right and collection start EQ which pushed in roots to it right while queue right because here we are doing the level other favors but we don't care about what levels are we right now we just care about if we have seen the gap before so we don't need to create a level variable to keep track of the level right and we don't even need to that's that for - to traverse other out no down the same - to traverse other out no down the same - to traverse other out no down the same level here we don't care we just as long as we're following the same sequence it's fine basically the same sequence will be the note that would always pop from the left right top left and here and then we also kind of see gap right Foss so I'm gonna write this thing here if note right so remember this with a regular love all the traverse we already do a check here even though the data left is not emptied then we append to the key all right but keep in mind here we want this one to be we want this note to be added to the queue so that we traverse this level we can see there's a gap and then we can just keep doing right that's what we need to do here which too unlike we disap and without checking the existence of the note q dot append note left right and q down and no right we append the left first and then right so we can make sure and we are popping from the lab so we're making sure we always traverse from left to right since we're done we don't check that we don't attract yet the null here we have to check it here right so if okay if not right if not note right then we set a flag here we've seen gap right equals to true right house right else house we do this right let's see if it's not there won't be any left and right here but if there's not non first we see we said this gap here remember so and this time inside the if here if right the house means okay we see another note here but if we have seen the gap before all right if we have seen the gap before I never see another note what does it mean fast right fast then we'll just keep doing it in the end if everything works fine then we just return true yeah I think that's pretty much it is let's try to run it - perfect let's try to run it - perfect let's try to run it - perfect cool all right I think kind of pretty straightforward so we just keep pushing the left and the right note right regardless of its if it's in now or not because we do a check here if the if isn't now here we set the flag here and if there's a it's a no valid note and we have seen a gap before we know it's not a complete binary tree go guys okay I think that's it thank you so much for watching the video alright I'll see you guys later bye
|
Check Completeness of a Binary Tree
|
sort-array-by-parity-ii
|
Given the `root` of a binary tree, determine if it is a _complete binary tree_.
In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6\]
**Output:** true
**Explanation:** Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
**Example 2:**
**Input:** root = \[1,2,3,4,5,null,7\]
**Output:** false
**Explanation:** The node with value 7 isn't as far left as possible.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `1 <= Node.val <= 1000`
| null |
Array,Two Pointers,Sorting
|
Easy
|
2271,2283,2327
|
1,371 |
hello everyone so in this video let us talk about a medievable problem from lead code the problem name is find the longest substring containing vowels in even count let us talk about the problem statement first it states that you are given a string s you have to return the size of the longest substring containing each vowel and even number of times that is a e i o u all the ovals must appear in even number of times in the substring that you choose from this particular strength okay let's take some example to make it all more clear as you can see that in this particular string that you have you can take out a substring is just simply a continuous let's say characters you can extract out from this particular state so the complete string can also be taken as substring or some part of it so let's say if I take apart starting from this L all together from W or till this point this is a complete let's say a part of it which is a substring that if you take out this small string then that substring consists of all the vowels even number of times all the different vowels okay it should not be means that the vowels like frequency should also be same okay no they should be just even that is the whole problem statement submit for that as well you can see that if you take out l e c l e t c all of the vowels are appearing let's say even number times so e is appearing two times and all the others are not happening so it is 0 which is also considered as equal so now that's the problem statement now there might be multiple brute first way also but I think so the constraints are pretty large so the very gracious solution which I find out which is somewhat I also find out from the submissions also that you have to use bit Mass which is a very clever way to solve this prototype now how can we use bitmask to solve this problem not the very first constraint of this bitmask is that we only have five characters that we have to keep track of which are the vowels and thus you can make a bit mask for those vowels now how can you make a bit mask now there are multiple approaches to make a bit mask as well but what you can see is that if you take this you can assign every character to a particular bit in a particular number so a bit mask is actually just a simple number and so let's say if you have five characters you will make a bit mask of five bits so five bit numbers let's say 32. so from 0 to 32 which means that all the numbers from 0 to 32 are considered as bit mass for this particular number that I am going to describe now how we want to describe that let's say that I map that if I find it a I will change the very let's say first bit from the very right so this is let's say Mark to a this is e this is I this is O this is U you can mark it you can map it out using some map I will talk about that as well but what you can see that if I make this mapping and if I somewhat see that in the initial State like if I just take this as a string or let's say this if take this as a mask all the let's say all the frequencies of all the vowels are 0 which means that they all are even now if let's say e occurs one time I will flip this bit to 1. like this now this will become another new number which is totally fine with us but if I see e one more time it is flipped back to zero which eventually just means that it has gone to zero because all the zeros eventually just describe the number zero because if I have a number which has all the five bits equal to 0 which eventually just means that it is a zero number so what you can see is that I have a zero and if I added two e's it has again become zero which means that I have two E's which one which means that e is even number so I can just take this analogy to solve this particular problem out in which I will take this particular string that I have and I will make a bitmask code now how can I find out the longest sub thing for that there is a very similar problem to this which is finding out the longest sub array in the array such that the sum of all numbers inside that sub array is equivalent to zero I think so I have also made a video of that if I have not I will make a video of that as well but the problem statement you can search it online as well that you have to find out the longest sub array whose sum of all the elements is equal to zero okay this is a very similar problem to that in just a different representation so what we will be doing in that scenario is let's take a small example to understand that scenario and then we'll move on to the solution part because that is the oral idea that you have to need to solve this particular problem let's take an example that if I just remove this out let's say that initially we have this string okay all this now let's take this all string but let's take this as a string if we have this as a string now what you can see is that initially we don't have any characters so we have a 5 bit number okay and everything is even because I have not taken anything and it starts with 0 at this particular point which means that 0 means that what is the state what is the value of this bit number it is 0 because all the bits are zero okay initiate is zero if I add L to it let's say I start moving from left right over the string if I add L to it l is not of any type of vowel so I will just ignore it and this number will still not change it'll still zero if I add e now so e will be let's say this so it will be the bit of it will be changed it will become 1. now if again I see E I will make it to 0 again now what you'll observe from here is that or let's say if I take T also then again the number will become zero what you can see is that the number is zero at the very start and 0 at this particular t as well what it eventually means that the value if I take any characters in between they are nullifying it they are not contributing to anything because the number initially is also zero this is zero also so all the numbers or all the characters in between this particular string are not doing anything which is still not changing this number which means that they're nullifying it which means that they are contributing to zero and if they are contributing to zero which means that they are all even like the count should be all even because that is why they're not contributing to anything and thus if I see a number that is occurring again the same time if let's say I find it 0 and if let's say 0 occurs here as well and just give an example if zero again here as well which means that all the characters between this and this position are nullifying they are contributing to zero they have haven't added anything to this number which means that you can take this as a substring so you just have to find out the let's say any last occurrence of zero and the current occurrence of zero and all the characters in between can be considered as nullify and you can just add it I hope you understand that's our idea that you have to use that if I see the same number again or the same bit Mass again then all the characters between them are nullifying which means that they are contributing to 0 which means that 0 means that all the numbers between them all the characters between them are actually storing even number of vowels which you can take at a substring and you can just maximize it over all the possible substrings that you will find out okay that's the problem statement and that's a Perpetual solution that you have to use if you still want more context you can go check out that particular problem which I've told you okay let us now move down to the solution part for this particular problem how we will be doing is that we will have to make a map okay that this is the map that will store out where is the last I have seen this particular bit mask so which means that if I have seen 0 at the very starting so I have seen zero bit mask here and I have Co 0 bit mask here so I have to add those bit mask positions so I have added 0 as minus 1 which means that I have seen because this is the zeroth index this character is youth index so I have seen let's say the total value of the bit mask the value bit mask is 0 before taking the first character which is our index minus one it doesn't exist but I can make store it inside the map so at this index 0 I have like so I have seen a total value this is the value so I've seen the total value of the bit Mass the total bit mass is zero at the index minus one okay this is just a reference to find out the total number of characters industry now I will just do a for Loop over all the characters what I'll do is that if the ith character is let's say vowel so what I'll do is I have to now Mark in the bit mask so bit mask is let's say count I have made a variable count so I will just shift one to how much time I have that particular character so let's say either I can map or create one more mapping that a is mapped to this character e is map this character a i is coming to this character or you could have also created a 32 because I only have 26 characters so you could have also created a 32-bit so you could have also created a 32-bit so you could have also created a 32-bit number which is the just a standard bit and you can take out whatever is this bit position so let's say a is zeroth position so it will flip this viewer question number if e is fifth question so if just left the fifth position number depending upon what it is so you can just do a zor of the count number at that particular bit position it will be flipped okay so this is how you can flip a particular position now after flipping out what you will do you have a new number you have a new bit mask this is actually a bit path which is Count now if I had already seen this count before if I've already seen this com before I will find out so let's say I found a zero here and I have already seen 0 here and I have total got the bit mask of 0 at this point so this is the calculating of the bit mask at this particular point and if I've already seen the bit Mass I can check it inside the map because map is storing that key for this bit mask where it is found out if you have already found out I have to find out that I already founded it here and this is the bitmask I have so this is the characters between them what is the length between them that is the substring so I is the current position minus the last position I've seen that is this and I will get the substring length I will maximize it and if I'm seeing let's say I've got the total bitmask of lesser 12 and if I am seeing the 12 bitmaps for very first time then I will just update that particular bit mask and where I have seen this ith index that is how you will now that if I find 12 again which means that I have scene 12 at the very last Point whatever of time seen that whichever index I will now use this to find out the substring between that two occurrence of 12 as well okay that is how you can just find out the occurrences and whatever is the substring between them that is contributing nothing that is that all the substring all the characters between that particular let's say in that substring or eventually having vowels equal to zero and then you can maximize it over all the substrings and then just print the answer okay that is the particular overall problem statement now you can see that this is making a map which will be doing a particular operation o of log n this is the for Loop so for Loop and for everything let's say you will do some operations so o of n log n will be the overall diversity for this particular problem that's the complete logic and the good part for this particular problem if you still have any doubts requirements in the inbox of this particular video I will see you in an SMD coding and bye
|
Find the Longest Substring Containing Vowels in Even Counts
|
minimum-remove-to-make-valid-parentheses
|
Given the string `s`, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.
**Example 1:**
**Input:** s = "eleetminicoworoep "
**Output:** 13
**Explanation:** The longest substring is "leetminicowor " which contains two each of the vowels: **e**, **i** and **o** and zero of the vowels: **a** and **u**.
**Example 2:**
**Input:** s = "leetcodeisgreat "
**Output:** 5
**Explanation:** The longest substring is "leetc " which contains two e's.
**Example 3:**
**Input:** s = "bcbcbc "
**Output:** 6
**Explanation:** In this case, the given string "bcbcbc " is the longest because all vowels: **a**, **e**, **i**, **o** and **u** appear zero times.
**Constraints:**
* `1 <= s.length <= 5 x 10^5`
* `s` contains only lowercase English letters.
It is the empty string, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string.
|
Each prefix of a balanced parentheses has a number of open parentheses greater or equal than closed parentheses, similar idea with each suffix. Check the array from left to right, remove characters that do not meet the property mentioned above, same idea in backward way.
|
String,Stack
|
Medium
|
2095,2221
|
1,971 |
hey everybody this is Larry this is Minicon do an extra bonus question um this is a little bit later in the day so I'm going to restrict the difficulty to medium and easy or okay so you can really choose both and I it's a little bit later today so let's just do an easy one then and then pick a random one that isn't an SQL statement or maybe this is a and I probably know how to do it but I don't want to waste time on stream on video okay so let's look at this one 1971 fine if path existing graph and of course I just want to point out that now that uh I have premium it's giving me random ones that are not premium so I don't know OMG how does it work anyway there's a bi-directional graph of Android this is bi-directional graph of Android this is bi-directional graph of Android this is 0 to n minus one Edge is a UV okay uh okay so there's no multiple edges and no self edges write apart from source to destination um okay so this is pretty straightforward it's a little bit of an awkward easy to be honest in the sense that um to be fair especially at I don't know the time of inception of this Prime Inception it probably is a problem that you really expected to know but also one of those things that are very hard to learn if you haven't already done it um so like if you don't have graph I wouldn't say that you need graph background but if you haven't done graphs you're not going to get this one so yeah you'd have definitely have to study up but this is a connected components problem uh or you know there are a lot of way you would say about it but at the base it is a connected components form and the um probably a lot of ways to solve it but there are three main ways that you could start with one is deaf research that one's breakfast search and the other one is uh Union fine or DSU I'm not going to go over Audrey today how do I feel um I'm trying to find a Coin um okay heads I do PFS Tales I do uh DFS so let's see how it tails what did I say it was DFS okay let's do DFS so okay so let's do DFS and let's give it a spin um though I would also say that to be honest this is um when you're given an etched list like this it does make it easier to use Union fine to be honest uh where um yeah I mean that's pretty much it really that's the only point I wanted to make otherwise you know it is easier to do um in this case that first search from you know an adjacency list and so we'll build that list out so Jason C list is equal to uh collection is that the list and then for you we in uh edges that append you right so now we're just building a list of yeah edges uh Json C list right so then now um what do I say definite search so yeah let's put that first search um let's just say we have current node um actually we have a scene is a good set right so then now we go um how would I want to write it's fine either way right so um just do something like this right um and then if node is equal to destination we turn true L's scene dot add node um for V and adjacency list of the node if V is not in scene then we do a DFS on V right uh um well I would say and then we do deficit then we turn true otherwise we turn false right um basically there's a saying that we definitely search and we found the path then we returned true otherwise we return force and that should be okay unless I'm missing some like weird things in this way possible hopefully okay the other thing that sometimes happens is that because um I didn't look at the constraints but yeah because there are a lot of notes so that is one for the death research that I kind of consider but having taught up uh articulated which is that first search does create a lot of um you know core stack space and stuff like this so sometimes you may get into performance issues um so I was a little bit worried and it wasn't that fast to be honest um but still should be okay it's just that um yeah function calls are kind of expensive on Python and the code or well both but leak code kind of you know especially abuses it a little bit too much um this is going to be linear time linear space and yeah and in this case linear well linear is V plus e right so just to be clear hmm is this I guess input is only U but yeah in this case the linear time is going to be all of V plus e um every edges every Edge gets looked at least one both in the processing and in here and also each node get looked at almost one so yeah I mean of course in space you have the adjacency list here and then that first search will have that core stack space of uh of V so hence we have we all V plus G um cool that's all I have for this one let me know what you think um that's what I have so stay good stay healthy take good mental health I'll see y'all later and take care bye
|
Find if Path Exists in Graph
|
incremental-memory-leak
|
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself.
You want to determine if there is a **valid path** that exists from vertex `source` to vertex `destination`.
Given `edges` and the integers `n`, `source`, and `destination`, return `true` _if there is a **valid path** from_ `source` _to_ `destination`_, or_ `false` _otherwise__._
**Example 1:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[2,0\]\], source = 0, destination = 2
**Output:** true
**Explanation:** There are two paths from vertex 0 to vertex 2:
- 0 -> 1 -> 2
- 0 -> 2
**Example 2:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[3,5\],\[5,4\],\[4,3\]\], source = 0, destination = 5
**Output:** false
**Explanation:** There is no path from vertex 0 to vertex 5.
**Constraints:**
* `1 <= n <= 2 * 105`
* `0 <= edges.length <= 2 * 105`
* `edges[i].length == 2`
* `0 <= ui, vi <= n - 1`
* `ui != vi`
* `0 <= source, destination <= n - 1`
* There are no duplicate edges.
* There are no self edges.
|
What is the upper bound for the number of seconds? Simulate the process of allocating memory.
|
Simulation
|
Medium
| null |
215 |
so my folks today Les Deux little problem 2:15 the case largest element in problem 2:15 the case largest element in problem 2:15 the case largest element in the array so in this problem so we will use an algorithm called quick select it's very similar with quicksort except for quicksort is this time complexity is o n times morgan but here click select is normally o n so let's see how it works so you click select so we do partition first we put with your partition first use of partition function so the partition function ok for partition function that will do two things with you two things the first is to sort the array at the whole sort the array as a whole and the second is to return the piped position or private index so the array is a whole meaning on the left all numbers are less then the private value my own right is larger okay so this the partition function does two things so using the party function we can get the piper position and we can also sort the array based on a private value so there could be so if okay give the case value I mean we want to find the case largest then you know if K minus 1 is less than pi with less than a piper position standard position what that means then that means the technologist should oh it's not easy to understand but in produce motion maybe since we are looking for the case largest so maybe we should sort the array as a whole meaning on the left all the numbers are larger should be loaded that are larger then the private value so in that way we can solve this problem easier okay if K minus one now if K minus 1 is less than pi repetition then that the case largest should be on the left then we should search left where else then we search on the right so that's how it works I'll stand research on the right so let's try to find the time complexity of this algorithm so in this algorithm each comparison we need to do a partition function the partition function has a time complexity of olan and after comparison we search on the left which is different then we don't need to search on the right which is different from quicksort in quick sort of we need to search on the left and we need to search on the right nor thirst but sort on the left and sort on right so it you click select we saw it we only search on the left we totally ignored the right part so we saw on the next comparison we on the next comparison then we on the next comparison we do another partition function which operates at Oh an over two and then on the next one then we operate at an over four so the total time complexity is o n+ o n over 2 total time complexity is o n+ o n over 2 total time complexity is o n+ o n over 2 plus da plus o 2 plus a 1 so what's the time complexity of this it's really hard to into please look at it maybe we will gesso and squared or something like that but really it's not all in tempo log n but really it's not how to calculate it there's a good way to calculate like this so we say the overall time connect complexity come time clemency time complexity is o X so then what is a waxed so you want to find Oh X we use o x times or what a + or 1 Oh X we use o x times or what a + or 1 Oh X we use o x times or what a + or 1 then x + or 1 is really this + or 1 then x + or 1 is really this + or 1 then x + or 1 is really this + or 1 so it's really a 1 plus a 1 which is this 1 plus o 2 which is this 1 + + o so this 1 plus o 2 which is this 1 + + o so this 1 plus o 2 which is this 1 + + o so that so o 1 + or 1 equals o - and now that so o 1 + or 1 equals o - and now that so o 1 + or 1 equals o - and now the O 2 plus out 10 or 2 + or to give us the O 2 plus out 10 or 2 + or to give us the O 2 plus out 10 or 2 + or to give us oh four plus or four equals o 8 plus past avatars then you know the whole theme + together equals 1 can cross over that equals to all to n so that means Oh X really is Owen so it's little surprising that this algorithm gives us overall time complexity of Owen but it is indeed the case let's try to implement this algorithm so let's do the corner case first if we use quick slag function quick stack function should return this function okay similar with quick sort we need to run to the starting point and the end point fine click slack okay the end of the recursion is start larger equals to end - position equals the partition function - position equals the partition function - position equals the partition function maybe we should write the partition function first let's write the partition function first so the partition function should do two things by type value and high position Saudi Arabia private value so we need to define the private value we should note that we should sort the array in descending order instead of ascending order so all so meaning that on the left then answer our larger than private value so on the right the numbers should be smaller than 5 fle this is very similar ways quicksort algorithm that's we should note that this should be that's all you could put in the PI birthday now that array has been changed right I to private value then return I okay that's partition so find the pilot position using the partition function and then compare the type a position with K minus one last then type the position then we should search on the left return so click select return case our case now just adamant in array so return case our consignment in arrays we should return the left third position L if K minus one it's larger ten type of tradition okay - it's larger ten type of tradition okay - it's larger ten type of tradition okay - why is larger then piped position then we should search on the left all right not partition but click select okay else okay minus y equals to five a position that wishes return private position we're going to return the largest segment that is not the position so all right okay that should do it let's see quick select okay it's a typo here okay it looks good I'll put it's not okay so if start equals end wait a second something is wrong with the recursion if the star equals end then we should return the Ray start over again so that should do it okay good so as you can see the runtime is pretty long because the even though their time complexity is o an average is Oh an average by the universe case is really all N squared if we say you know you will select the pipe position it's like the private position Ray is always the smallest order largest number that will lead to the worst case so which gives you a time complexity of oh and squared so actually there are better ways to solve this problem or this kind of problem find a case largest element in an array we want to find a case largest element or you know or try to find K smallest element or my whatever a case something element you know we can always try to use a method or the in structure called hip in Python a hip is a minimum hip so it always store it use that fee and always store and store the element in order so that you can add an element into the hip and in the 10 the order in o log n time and also page Paige use this case use section so okay so for hip the add an element and maintain the same order or praising your o log n time also pop also operate in log n time also delete or injured delete say delete user his add also operate in log n time so if we have a heap then but you can keep track then we can keep track the largest number we always keep track the largest number and then we know the case large number by keeping the heap size to be K then let me think so if we keep all the keep every element in the you know in our hip so we keep every number in the hip every number in the from the numbers into the hip Tang in the hip you know the top one will always be the smallest one and this should be the largest one not just one okay so when we keep lumps into the hip we always want to keep the hip in the sides of K so we always pop in unless it's nicer than K we pop-pop the smallest one nicer than K we pop-pop the smallest one nicer than K we pop-pop the smallest one so in that way when the hip when we iterate all the numbers the final Kalin's hip will be will store or to learn all the large largest number so the smallest number then will be the case largest number then we just pop it out so let's try to implement and their algorithm by using the hip so when you firstly we need to import a hip keep queue for the hip queue then we create a hip iterate dance and put the numbers into him so it's hip Q dot hip push down into noms hip also come on keep the size of the heap we want to keep the size of the hip that's okay that's y equals 10 K so it's larger than k then we pop it out now we pop the smallest out so also we are going to use a method in heat Q dot pop hip Q top hip up interest hip up so then pop the smallest number in the num nums hip then up the iteration after iteration the K sighs he cute store all the K parties number so what we need to do is we just need to pop the smallest number which is pop that's it run wait a second oh we didn't return so this should be return just kick some it I mean student does not match any level okay so this is making son happy here that's good okay good so if we compare the runtime of using a hip queue with the selection sort algorithm a selection sort algorithm used one thousand one second and the hip who uses tens of milliseconds which is much faster this is because even though click select is supposed to have Oh n time complexity but in that but that's ideal case in many cases or in worst case is Oh N squared time complexity however in here Q Add and pop are operated in Owen operate operated in O log n time complexity so in this algorithm so each pop is own log and so we pop each Paco is all okay because the lands up because the length of the heap the last of here is K so he's pop is not well okay and during the iteration is during the iteration of is the time complexity is Owen so overall it's all n Times log K so it's oh-oh over all the time can have complexity is o n Times log okay this is very important okay so that's all the video for today thanks for watching if you like my video please upload it or subscribe my video channel I'm trying to update at least one very typical very important program I mean problem eco problem everyday so if you really want to like it you really want to you know support me please click subscribe or share my video with your friends thank you very much bye
|
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
|
322 |
hey guys it's all five one here and today we're going to be solving coin change in this problem we're given an array called coins and this represents coins of different denominations and that gives an integer amount that represent the total amount of money we want to get and in this problem they want us to return the fewest number of coins that you need to make up that amount so for example here we're given an amount of 11 and the coins we have to work with are one two and five and the solution would be to have two five coins and one coin and if the amount can be made up with any combination of coins then we just return negative one like we see here we have a coin of two and an amount of three and there's no way to get to that so we just returned negative one since this is a dynamic programming problem what you want to do is take our current problem and break it up into a subset of problems so for example to get the least amount of coins for the amount equal to 11 we need to know the minimum amount for the ones previous so for example let's say we do 11 minus 5. well now we need to know the minimum amount of coins we need to get to six and so we know that 5 and 1 give us that and now our new sub problem is going to be what's the minimum amount of coins we need to get to one well we know that's one but we can see here that we're trying to solve for 11 6 and 1. so how can we use this to develop our code so here I've redrawn the example from the problem and I've just made an array and the arrayed the 11th index is going to be 3 because that's a minimum amount of coins we need and for index six the minimum is 2 and for index one it's one because we can just make it from the one coin and also our base case is going to be zero because we don't need any coins to have a zero amount so before trying to solve this using some kind of complicated algorithm let's just do it by hand and see if we can notice any patterns so let's see what's the minimum amount of coins we need to get to well we know there's a coin for two so we can just write that down as one coin and for three well there's no three coin but we know from doing our math that two and one are going to make up three and that's the least amount of coins we need because if we do one and one then that would be too many coins that is supposed to be a two it's my bad and number four we know that two and two are the minimum amount of coins we need for that so I'm just going to write that down and then for five well there's a five coin so we can just put one um six is already solved and then for seven we know there's a five and a two coin so the minimum would be two for eight we have five two and one and that would be the minimum amount for eight and then for nine we could do five and then two coins so that would be five plus two which would be nine so that's three coins and then for ten we can use two fives so we only need two coins for 10. so what do we see here well here I'm just going to name the array to make the example easier to explain and also I want to address the fact that these indexes of the array are actually the amounts and so we're accessing index three for example we're looking for the minimum amount of coins that make up three so whenever you access results of three we know we're going to get the smallest amount of coins possible to make that index so now that we established that what else do we know well we know we want to check every single coin to see if it fits in the index but as you can see for one for example we don't need to check two or five so we want to iterate through every coin and for each coin we want to check if the current index let's just call it a minus our current coin value is greater than or equal to zero then we know that's a valid coin because for example let's say we are at index one so one minus one would give us zero but one minus two would give us a negative one and that wouldn't be a valid answer so what do we want to do if we do find a valid coin well we know if you find a valid coin we definitely want to update our index so we can do the results of a would be equal to the minimum amount of coins we need and let's say we're just doing it for the first index the way to represent that would be results of a minus coin plus one and the reason we do this is because result that a minus coin would be zero because one minus one would be zero and then we have this result here zero and then we want to add one because this represents the new coin we just iterated through right here so while this solution does work for one we want to generalize it a little because we're not guaranteed that this is sorted so for example let's say R1 was last well then our result at a would equal to result of a minus 1 plus 1 and that might not give us our min what we actually want is the Min between the result at a minus every coin so let's say our a is equal to 11. what we want is the Min between these next three values the result at 11 minus 1 results at 11 minus two and result at 11 minus five so how do we read this well let's see result at 11 minus 1 that would be ten and we can see that this is currently two so let me just write that down here and then for 11 minus 2 that would be nine and this gives us a value of three and then for 11 minus five we have 11 minus five that is six so our Min here would be two and then once we find our Min what we want to do is add one to that because this is what our newest coin is so for example here if we're doing 11 minus one we're looking at 10 and at this point we have a point of five and a coin of five making it up and we want to add 1 to consider our coin of one so now we can finish our pseudocode to start we want to iterate through every amount so for every amount you want to do this Loop and then we want to check every coin and then we want to find the Min to see what our result at a should be but this code won't work as we've seen here so we want to rewrite it like results at a is equal to the min between our current result because maybe we already found them in or results of a minus coin plus one the time complexity for this algorithm would be o of amount times coins the reason for that is because we have to iterate through every single amount and we also have to iterate through every coins every time we iterate through an amount and then for space we just have o of amount because we only need to store each amount in an array now that we're done with that let's get into the code to start we just want to initialize our amounts array and we want to initialize every value in the array to be positive Infinity the reason is because when we're going to compare our mins later on we want to have a really big number so that way it doesn't register the first iteration as the Min because otherwise it would be zero and we're going to do this for a length of amount plus one and from here we just want to set up our base case so amounts array at zero is going to be equal to zero because there are no points for that and now we just want to iterate through every amount so for current amount in range of one to ml plus one the reason we're doing them out plus one is because range is not inclusive we want to iterate through every coin so for coin and coins we want to check if the coin is valid and to do that we do current amount minus our current coin and we check if that's greater than or equal to zero if it is then that means the coin is valid and then from here we just want to set our min so amounts array at our current iteration which would be current amount is going to be equal to the Min between our current index or is going to be amount of rate at our current index minus coin plus one like we explained in the pseudo code and then from here that's pretty much the whole algorithm and we could just return amount array at amount but the problem with that is if we didn't find our actual amount then this would return an Infinity which is wrong so we only want to return this in the case that amounts array at amount is not equal to Infinity otherwise you want to return negative one and that should work and actually this is supposed to be in parentheses and now it should work so as you can see this code is pretty efficient and now we'll go through the code manually to start we're going to initialize our amounts array to be equal to Infinity at all spots with the size of a mouth plus one to include a space with zero after that we want to initialize our base case which is index 0 and we want to set it equal to zero and then now we want to loop from one all the way to amounts so to start our current amount is going to be equal to one and then now we want to iterate through each coin our coins are only one and three and we're going to start with one so amounts of Ray at one is going to be set to the Min between the current value and the current amount minus coin index which would be equal to zero after that we just want to add one to it so the Min between infinity and one would be one and then we can see that this three is not a valid coin because one minus three would be negative so we're not going to consider that one and now we go to the next iteration so current amount is equal to two and now we check is the current amount is less than a current coin which we're looking at one again so our current amount is two minus coin which is one that is greater than zero so now we want to set array at 2 equal to the Min between the current value and current amount minus coin index so current amount is two and the coin is one so we want to see the first index and then add one to that and the Min between infinity and 2 would be two and now we check if 3 is a valid coin well if you check current amount minus coin we see that 2 minus three is negative so we're not going to consider that either and now we go to our last iteration so current amount is now equal to three and then for each coin we're starting at one again then we want to check current amount minus coin so three minus one that is greater than zero and then now we want to set our array and our current amount 3 equal to the Min between the current value and current amount minus coin index Plus 1. and so we see that three minus 1 gives us the index two and if we add 1 to that we get three and the mean between infinity and three is going to be three and now we go to our last point value three and now we check current amount which is three minus coin which is three is equal to zero so that's a valid coin and now we set our array at the third of x equal to the mid between the current value and the index at 3 minus three which is zero plus one so our index at zero is zero and if we get one to that we get one the Min between three and one is one so we're going to set this to one and that's all the coins and the mouse we have to go through so now we check is amounts array at amount not equal to Infinity and we see that at 3 is equal to one so that's not true so we do return this which is amounts at amount which would be one and that's the right answer if this video helped in any way please leave a like And subscribe thanks for watching and I'll see you in the next video
|
Coin Change
|
coin-change
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.
You may assume that you have an infinite number of each kind of coin.
**Example 1:**
**Input:** coins = \[1,2,5\], amount = 11
**Output:** 3
**Explanation:** 11 = 5 + 5 + 1
**Example 2:**
**Input:** coins = \[2\], amount = 3
**Output:** -1
**Example 3:**
**Input:** coins = \[1\], amount = 0
**Output:** 0
**Constraints:**
* `1 <= coins.length <= 12`
* `1 <= coins[i] <= 231 - 1`
* `0 <= amount <= 104`
| null |
Array,Dynamic Programming,Breadth-First Search
|
Medium
|
1025,1393,2345
|
88 |
welcome to joey's tech friends in this video we are going to look into solving another interview question from lead code which is merge sorted array this is one of the most commonly asked questions that every fresher coder or experience coder must have in his or her pocket so without delaying any further let's look into its problem statement you are given two integer arrays in this question the two integer arrays are nums1 and nums2 and the elements in both the arrays are sorted in ascending order the condition of the question is that nums1 and nums2 should be merged into the array num1 only and the merged elements in the array nums1 should be in ascending order you are thus given two variables m and n the length of the array num2 is given by n and the length of the array nums1 is given as m plus n of which m represents the number of the elements of the array num1 and n represents the number of elements that need to be accommodated from nums to let's see the problem statement with the help of this example as you can see the array nums1 has these elements one two three and finally this array has three zeros of these the first three elements that means one two three belong to this array nums1 and the last three cells that contain zeroes are there to accommodate elements from this array nums two after merging the two arrays the array nums1 will become like this note that the integers are sorted in ascending order we have to solve this question without using any other array and the first approach that came to my mind was to simply fill the elements from nums to into these empty cells with zeros and then run the sort function which is going to do the job for us but we have to solve this problem in o and time so we need to follow some other approach let's discuss it then now this new approach that i thought of and you can think of that too so it's all about assigning three variables because we will have to do comparisons here okay that is for sure so i will be the variable that is going to iterate over nums 1 so let me put i over here and j will be the variable that is going to i trade over nums 2 so let me put j over here and with this i am going to put one more variable which is k that is going to track the cells of the array nums one in which will be putting in the array elements since these two arrays need to be merged into nums one only hence i am creating a separate variable which will be k so i and j are for comparison of the values in cells of nums 1 and nums 2 k is going to keep a track of the cells of the array num 1 in which the final sorted assignment of the element is taking place we are going to start from the left first to check if it works for us the variable i represents this cell and the variable j represents this cell let's do a comparison between the values of these two cells so 1 is less than 2 what is going to happen one is going to stay in this cell only what the algorithm is going to do the algorithm is going to assign the value represented by i to the cell represented by k hence the value is going to stay over here only after this comparison i is going to move one cell to the right and k is going to move one cell to the right as well now a comparison will again happen between the values of the cells are represented by i and j since they both are the same hence the algorithm is going to assign the value represented by i to the cell represented by k again so this 2 is going to stay over here only k will move to the right and i will move to the right as well now i represents this cell containing 3 and j represents this cell containing 2. let's do a comparison again between these two cells so 3 is greater than 2 so what the algorithm is going to do it's going to assign the value of the cell represented by j to the cell represented by k so 2 is going to replace 3 all right k will move one cell to the right this okay that means this cell of the num's 1 array needs to be populated now and j is also going to move one cell to the right while i is going to stay in the same position okay now the comparison is going to be made between the values of the cells represented by i and j so two will be compared against five but wait a minute this cell contained three you see three is gone the comparison won't happen with the right element now even if we store three in a temporary variable it will make the algorithm more complicated so why don't we try the same algorithm from the back of these two arrows then let's bring the variables to the back of the arrow now the variable j is going to start towards the left from the last cell of the array num2 and k will also start towards the left from the last cell of the array num1 however to do the right comparisons i will start from the last element of the array num1 and not from the back because the elements of the array nums1 are till here only since we are starting from the back of the array hence the bigger elements are going to be stored in the back and the smaller elements in the front because this array needs to be sorted in ascending order hence the comparison will be reversed this time so what's going to happen 3 will be compared against 6 because 3 is the value of the cell represented by i and 6 is the value of the cell represented by j between 3 and 6 which is greater 6 obviously so 6 will move to this cell represented by k okay and since 6 has been picked from nums 2 hence j is going to move one cell to the left now 3 will be compared against 5 since 5 is greater hence 5 will move to the second last cell which will be represented by k i am sorry i didn't shift it left it should have been shifted by me at the end of the first comparison since uh the element has been taken from nums 2 only so j will be shifted to the left and k will also be shifted to the left okay now this cell will be filled so 3 will be compared with 2 this time since 3 is greater than 2 hence the value of this cell represented by i will be populated in this cell represented by k and at the end of this comparison i will be shifted one cell to the left and k will also be shifted one cell to the left now two will be compared against two since they both are the same hence two will be picked from here from the first cell of the nums to array and will be populated in the cell represented by k so this 3 will be replaced by 2 all right j is going to move one cell to the left and i is going to stay here only now when the algorithm is going to see that j is representing an index which is less than 0 it's going to stop it's a signal that the merging of the two arrays has happened and the elements have been sorted in ascending order as well you can see over here the elements in the array nums1 are merged and have been sorted in ascending order only this is the algorithm so we nailed the whole problem with this approach now let's code this program in java now i have already created a class named merge sorted array in my project and i have already created a main function i highly recommend that you code this program along with me because that way you will be able to understand this program in a much better way the first step that we are going to take will be to declare the two integer arrays so it will be in square brackets we are going to call the first array is nums one only after the equals to sign we are going to write new int and within curly braces we are going to assign this array the elements that we have seen in the slides so it will be 1 comma 2 comma 3 comma 0 all right now let's declare the second array which will be nums 2. now this array will be initialized to the elements 2 5 6 okay now let's declare and initialize the variables m and n m is going to hold the length of the r in nums 1 and n is going to hold the length of the array nums2 so we are going to write int m equals to nums1 dot length and then in the next line we'll write in equals to nums2 dot length the next thing we'll do is to declare and initialize the variables i j and k so we are going to write int i now since i is going to start from the cell which is going to contain the last element of the array num s1 hence i is going to be equal to m minus 1. okay j on the other hand will start from the last cell of the r in nums 2. so j will be equal to n minus 1 and the variable k is going to start from the back of the array nums1 so it will be equal to m plus n minus 1 okay now we are going to start a while loop that is going to run till either j is greater than equal to 0 or i is greater than or equal to 0 the moment either i or j becomes less than zero the loop is going to stop in our example we saw j becoming less than zero so it will be while within brackets it will be i greater than equal to zero and operator j is greater than equal to zero within the body of the while loop the first condition that we are going to write will be if the value of the cell at index i in nums 1 is less than the value of the cell at index chain numbers 2. if it is then we assign to the cell of nums 1 represented by k the value of the cell at index j of the nums to array so it will be if within brackets nums1 i is less than nums to j i forgot to write one over here that's why it's getting right now it's okay and if this condition is satisfied then we are going to assign to the cell of nums 1 represented by k the value of the cell of the nums 2 array represented by j okay once we have done this we subtract k and j by 1 so that they move left okay and why don't we use a less than equals to operator over here so that when the values of these two cells are equal then the value is picked from the cell represented by j from the nums to i now in the else part it's going to be the other way round that means when the value of the cell of nums one array at index i is greater than the value of the cell at index j of the numbers to array then assigned to the cell of nums one at index k the value of the cell at i of the array nums1 of course we are going to reduce i and k again okay so it will be nums 1 represented by k equals to nums 1 represented by i okay and then we are going to decrement the value of i okay and k all right that's it this completes the loop now while submitting this question on the lead code website i came across a use case in which there was given no element in the array number one in that case our job is to only assign to the cells of num 1 the values of the cells of the array nums 2. so to counter that use case we are going to write a separate while loop and the condition will be j is greater than equal to 0 because there are no elements in the array nums 1 so it will be nums 1 within square brackets k equals to nums 2 within square brackets j okay and then we are going to decrement the j by one such that it moves to the left and we are going to decrement the k by one such that it also moves to the left all right this is exactly the same code that we wrote over here nothing different now the final step will be to print the array nums one okay so for that we are going to use a for loop so it will be for int let me give the variable as p this time equals to zero p less than nums one dot length p plus and within curly braces it will be system dot out dot println and within brackets it will be numbs one within square brackets p plus space okay and since we are interested in printing the elements of this array side by side hence it won't be println i don't know why i always make this mistake that's it the program looks to be complete let's run it and check the output oh looks like i have made a great mistake over here that is why i'm getting this error this runtime error which i hate the most array index out of bounds exception so let me see what mistake i have i made all right i have spotted it m over here is not going to be equal to the length of the array num s1 it has to be equal to the number of genuine elements present in the nums1 array so this should be nums1 dot length minus n and since n has been declared and initialized after it hence this line of code must appear after the declaration and initialization of the variable n now let's run the program again and check if the error is gone or not and there you go these are the elements present in nums one both the arrays have been merged and the elements appear in an ascending order now this is the same output we reach to during our algorithm discussion phase and don't worry about these two variables m and n don't worry about their declaration or initialization because when you are going to submit the code on the lead code website they will already be given to you as the function arguments this concludes this video i hope you enjoyed learning this problem from joey's tech i hope you coded this problem along with me i look forward to helping you with programming and algorithms and only for this video goodbye and take very good care of yourself
|
Merge Sorted Array
|
merge-sorted-array
|
You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively.
**Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**.
The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`.
**Example 1:**
**Input:** nums1 = \[1,2,3,0,0,0\], m = 3, nums2 = \[2,5,6\], n = 3
**Output:** \[1,2,2,3,5,6\]
**Explanation:** The arrays we are merging are \[1,2,3\] and \[2,5,6\].
The result of the merge is \[1,2,2,3,5,6\] with the underlined elements coming from nums1.
**Example 2:**
**Input:** nums1 = \[1\], m = 1, nums2 = \[\], n = 0
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[1\] and \[\].
The result of the merge is \[1\].
**Example 3:**
**Input:** nums1 = \[0\], m = 0, nums2 = \[1\], n = 1
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[\] and \[1\].
The result of the merge is \[1\].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
**Constraints:**
* `nums1.length == m + n`
* `nums2.length == n`
* `0 <= m, n <= 200`
* `1 <= m + n <= 200`
* `-109 <= nums1[i], nums2[j] <= 109`
**Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time?
|
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
|
Array,Two Pointers,Sorting
|
Easy
|
21,1019,1028
|
774 |
hey what's up guys chung here this time let's continue our lead cold journey number 774 minimize max distance to gas stations all right okay let's take a look you're giving like stations of gas stations and the number K here and you need to return the minimum distance the minimum of the minimum distance between all the gas stations right after you after adding case stations to this array here so the minimum of the max distance between gas stations so basically let's say there are like 10 ways of adding case most gas stations into this array right for each of the scenarios you will have like a maximum distance between the gas stations right and among those ten different max gas stations you need to return the minimum out from them okay and since we are like dividing right since we keep adding distance so the one let's say if the distance from station 1 to station 2 is 1 let's say there's 1 & 2 there's 1 & 2 there's 1 & 2 if you add one more stations right in between them right it's gonna be a cities are like s3 in here right then the minimum station will become the minimum distance will becomes 0.5 right if you keep adding another one 0.5 right if you keep adding another one 0.5 right if you keep adding another one right between them it's gonna be a zero point 2025 and then 1.5 and so on so forth it'll be and then 1.5 and so on so forth it'll be and then 1.5 and so on so forth it'll be girl like keep decreasing until a very small number that's why it says number four here I'm sure within 10 to the minors ^ minors of six of the to the minors ^ minors of six of the to the minors ^ minors of six of the true value will be accepted as correct and so for this problem as you can you guys can see here so it's this is another like problem to get the minimum of maximum right so when you see this getting from the minimum of maximum you know you're either like two ways of solving the problem the first one will be like dynamic programming which will be like the time complexity will be the N squared times M where m is n easier it's a number after the station and M will be the K here that's the dynamic solutions and the second one will be the binary search right the binary search will be like n log what log some log of the upper bound basically right and binary search will be much faster so this time let's try to solve this problem by using a binary search right okay so for binary search right so binary search we need a lower bound upper bound right so left and right so I you reduce Levin right here so left obviously will be zero because that's them the distance right the distance the minimum distance for it's gonna be ideally right basically there's no distance here but we just use zero as a lower bound how about upper bound so the upper bound will be uh mmm so the upper bound will be the last we can either use like 10 to the power of 8 or we can just use the you know let's just use this yeah we can either use 10 to the power of 8 because that's the ranging station or we can use what we can just use the last station position minors to the first stations right that's gonna be the upper bound right so what do we do here right we just do a while right so but in this case remember so we're trying to get close to the answer right basically which means before we can just do our left less than equals to right and then we twist to this right that's the normal like binary search but in this case right since the difference could be very subtle right it could be like way less than 1 right so in this case basically the left and right they may not they may never be the same right we're just trying to get close to that the real answer in this case so in this case we're gonna do what in skated right miners left it's less than right as long it's less than the this range then we know we already find the answer right that was the end it's gonna be a 1 e minus 6 right that's the final answer here meat all right same thing middle here right left + right / - right since we're dealing with like the double types here we will not be doing like double slash here only the one single slash and then what and then we just do a possible we do a check here right I'm gonna define like Harper functions here to check if it is possible right of the distance so what's the what does this function track right it checks with current distance if the current distance is the current distance if it is possible we can use not we can use at most so I mean with the current distance if we can use if we can insert no greater than K stations right so that each station will have at most the distance here at this distance right if that's the case what does it mean it means that okay let me finish this it means that we can our this answer while this answer satisfied our conditions here which means we can continue to decrease this distance because we want to check the minimum right the minimum of them because this way which means this with this distance it can satisfy this K okay conditions here that's why we will be a I try to decrease that otherwise right otherwise we if we you cannot if we cannot we just to if it cannot means if we will be using more than modern case stations to satisfy this distance that means ok we need to increase this distance a bit right so that we can use last K ok so here is the tricky part here okay remember surely if we have this thing here ok we know ok it satisfies the conditions here that so that's why we want me to write because we know ok so this right might be our result right that's why we do a close a closer here but when we do a laugh here we unit what a meet plus 1 right but in his case we can't write since the to meet and since then to meet and the next answer may be in way less than 1 because the type is double so that's why we cannot do a minus 1 here we have to use a meet a middle here if we do a minus plus 1 maybe the answer is somewhere between the middle and one right then we'll be missing that answer so that's why we can only use a middle here and if we use the middle here and since we are doing this kind of track here it's guaranteeing that we will be close to that to our answer and we will not be having this infinite loop because the left and right there they're both like double size and so it so that and here we're also using like this single slash here so there won't be an infinite loop here every time we'll get like a different asthma a different number right in between the left and right so that's that okay so now let's implement this possible right with the distance here how many stations we need to add right gasps new gasps - gasps - add about this gasps new gasps - gasps - add about this gasps new gasps - gasps - add about this right so and we return right that gasps the station's to add it's not greater or it's not greater than K right and then we know okay with this season is possible that we can only it's possible to satisfy this case a condition right then how to recalculate stations to add right we simply do a loop right basically we loop each of the stations in the station right for right I in range and we compare the conversation with a previous one right length the stations - one right since we're going stations - one right since we're going stations - one right since we're going to compare me I mean either one is fine the current one the next one with current one word and what the other way around right and so what's gonna be the new stations here right let's so let's take a look here let's say the we're gonna do a like so the station's so basically where we're doing our stations the next station - the current station we're station - the current station we're station - the current station we're trying to get the distance right the distance between the next station and the current station and to be able to get the minimum the maximum distance of this distance right so how many stations we need to add between those right how could how can we calculate that okay so let's think about this right so let's think the station I plus one it's position let's say is 3.4 okay and it's position let's say is 3.4 okay and it's position let's say is 3.4 okay and I how about I let's say that I the position is 1 and the distance is also 1 and this sense is also 1 right so now the what's the current distance between I'm plus 1 and an is 2.4 right I'm plus 1 and an is 2.4 right I'm plus 1 and an is 2.4 right it's 2.4 and our goal is that the it's 2.4 and our goal is that the it's 2.4 and our goal is that the distance can cannot be greater than this one the comment from this to this how many stations we need to add B in between here so that the distance will be smaller than 1 how right so in this case we can see which we need to add the difference 2.4 divided need to add the difference 2.4 divided need to add the difference 2.4 divided by the distance and then we do a floor basically that's the stations we need to add in order to make the distance from I plus 1 to I is smaller it's not greater than the distance C so if we add one more station right in between here right let's say there's a one station here what's that what's the distance now 2.4 so 4.2.2 right so this disposition will so 4.2.2 right so this disposition will so 4.2.2 right so this disposition will have to point to and after adding this one so the distance between all those three stations will become well from 2.4 to stations will become well from 2.4 to stations will become well from 2.4 to 1.2 right and but this one's still 1.2 right and but this one's still 1.2 right and but this one's still greater than 1 right let's try to add another one let's if we add another one and we amortize it right so like if there are like two stations here right two stations right in between right then if stations distance will be like 2.4 stations distance will be like 2.4 stations distance will be like 2.4 divided by 3 right so in this case is gonna be zero point 8 in this case right then zero point 8 is smaller than 1 then yeah then we just need two stations to be able to make the distance from this I plus 1 to I less than zero less than 1 right another example let's say that I plus 1 and I let's take another example here in this case this example which shows you the decay the scenario that the distance greater than distance right how about the ones if you if it the distance between the eyebrows oh and I there are already smaller than distance then that if that's the case this value here right this value here will be a will be smaller than distance here right and then this divided division will give us 0 all right this floor zero point something right zero point one two three four will give us the zero point a value because this is smaller than that and the floor will give us zero which means it will not it not does is requires zero station to be added in between all right okay cool so let's cut come back here so now since we have that right let's finish this calculations here right so every time when we try to every time we get a different the distance between two adjacent stations which two like what we just saw discussed with your floor right off this thing and divide it by the distance right in the end we just return okay so if this stations to add it's not greater than K and then this is a possible and if it is possible we know okay we might already find the answer right but this may be this part this middle here may not be small enough right that's why we need to keep moving to the left and in the end we simply oops sorry in the end we just simply return either left or right and let's in this case let's just return right okay and that should do it oops let's see what did we do wrong here do we need to return left here probably not no oh I think I found out where what's wrong here so here is to be greater than this one because once the difference between left and right is smaller than this like this range this light cut outta here and then we know we find the answer we can just stop otherwise as long as this one the difference is bigger than this one we know we have to keep looking it keep shrinking the range here right and I think that should station stations okay yeah let's try to execute this thing cool past all right very cool so it's a basically it's using the similar idea of some other problems to get the minimum value of the maximum right basically we simply try to do a search we search to the answer directly write the answer just will be that well whatever it needs us to calculate right in this case it's going to be the minimum distance right then we simply just do a range of this distance from the left to right and then every time we'll with the current distance we need to come up with the condition here right so that we know we can either search on the until on the left side or right side right in this case the condition is with the current distance here can we use less not more than pace distance case new stations so that all the stations will have no greater than distance right if that's the case we know okay the current one works but exists is this one the smallest probably not right so that's why we need to keep going into the lab that's why we abandoned the right half and then we call the left otherwise we know okay this distance is too small which will give us more which means we don't add more we need to add more K and more stations than K to satisfy these conditions here that's why we need to move it to the right side right but remember here since were like I said since we're dealing with the right very small double type integers we cannot do a fast one here right that's why here we do like a divide not like double divide right we simply do a divide here and then when we went close to this far falls into this range and then we know we found the answer all right cool guys I hope you guys enjoyed this video and thank you so much for watching the video and I'll be seeing you guys soon bye
|
Minimize Max Distance to Gas Station
|
maximum-depth-of-n-ary-tree
|
You are given an integer array `stations` that represents the positions of the gas stations on the **x-axis**. You are also given an integer `k`.
You should add `k` new gas stations. You can add the stations anywhere on the **x-axis**, and not necessarily on an integer position.
Let `penalty()` be the maximum distance between **adjacent** gas stations after adding the `k` new stations.
Return _the smallest possible value of_ `penalty()`. Answers within `10-6` of the actual answer will be accepted.
**Example 1:**
**Input:** stations = \[1,2,3,4,5,6,7,8,9,10\], k = 9
**Output:** 0.50000
**Example 2:**
**Input:** stations = \[23,24,36,39,46,56,57,65,84,98\], k = 1
**Output:** 14.00000
**Constraints:**
* `10 <= stations.length <= 2000`
* `0 <= stations[i] <= 108`
* `stations` is sorted in a **strictly increasing** order.
* `1 <= k <= 106`
| null |
Tree,Depth-First Search,Breadth-First Search
|
Easy
|
104,2151
|
438 |
hello everyone in this video we will be solving problem 438 find all animal grams in a string the problem statement is we are given two strings s and p we need to return an array of all the starting indices of peas analgram in s we can return the answer in any order if you don't know what analgram is it is a word or a phrase formed by rearranging the letters of a different word or phrase typically using all of the original letters exactly once if you are still not clear what anal gram is let's look at example number one and understand it here we are given two strings s and p contains abc and in s we have a bunch of letters and between p and s we need to find out if we have set of consecutive letters which is an analgram of abc so if you look at the first three characters of s we have c b and a which is an anal gram of a b and c so if i arrange it in a different way i can get the string p hence c b a becomes an analogue of a b and c similarly at index 6 we have b a c which is again an analogram of abc it's just arranged in a different way because we have two grams in this s input we are returning two indices as an output zero and six we need to return the starting index from where the anagram can be formed this problem can be solved using multiple ways i'll be talking about two such ways where we'll start with a simpler solution and in the second solution we'll try to optimize our approach and get a better time complexity now without wasting any time let's switch to whiteboard let's talk through the simple solution the simplest way to find if two strings are anal grams of each other is to order by ascending or descending and then compare if the two strings are equal or not if the two strings are equal it means it's an analogue or else it will return false for example if i have one text as abc and the other one is bac if i apply the order by operation on that on the left hand side i will get a b c and on the right hand side i will get a b c and because the two are equal they both are anal grams but let's say if i have an input of a b c on the left hand side and on the right hand side i just have b a c my order by would give me a b c on the left and on the right i will still have a b c which are not equal and we can say it is not an analgram to solve this problem using a simpler approach we can use the sort by approach to compare the strings let me give you a couple of examples because the length of p is three the substring that i will be doing on the string s also needs to have three characters so i will start with checking the first three characters so my pointer is going to point at zero i will get the first three characters c b a apply sorting which will give me a b and c and then i will compare it the p string so for p i only need to do an order by once because it is a constant string so after apply sorting i will get a b and c compare these two strings if the result is true i can say this is an analog gram so i will record this index i in my result and once this comparison is done i will then increment my i pointer to 1 so my new string will be b a e do the same operation after sorting i will get a b and e again continue with the comparison check it with p and if i find the two strings are equal add it to the result now with this solution definitely a time complexity is going to be huge because we are ordering or sorting the string at each index thus exponentially increasing our time complexity if you look at the two example that we took just now the first one was c b and a and the second one was b a and e and if you compare the two strings b and a was repeated so we are processing these two characters multiple times between the two iterations if i add one more character over here and if i continue the iteration for a e and b i will be using this character a thrice we need to think about how we can minimize the calculations of these repeated characters and simplify the logic to simplify the solution in improver time complexity one approach is rather than doing a sorting use a dictionary and record the number of characters being that are appearing and the count for example if i want to map the string p into a dictionary my dictionary would look something like this on the left hand side i will add the characters and on the right hand side i will have the count a appeared once b appeared once and c appeared once now all i need to do is build another table or another dictionary with the same columns left hand side would be the characters and right hand side would be the count and compare the two dictionaries if they have the right number of characters with the right count the two strings are anil grams and we will return true or we will add the index in the result variable now that this part is clear let's talk about how we can reduce the duplicate calculation that we were doing earlier let's take the first three characters now if i'm processing it via this dictionary option i will have cs1 bs1 and as1 and continue the comparison if the entry exists and the count matches it means it's an analog let's say i complete the iteration with this input now i need to take the next character which is e instead of doing a fresh iteration from b to e what we can do is remove the first character from the previous one and only add the last character or the new character that we are adding in my iteration i will check the first character in the previous word which is c so i will reduce the count of c in my dictionary so c will become 0 and i will add a new value for e set the count as one once the new string is added to the dictionary compare it with the p dictionary and verify let's take another example after e the next character is b so if i'm adding b here just like before we will take the first character of the previous string which is this b and remove it so i will set this b's count to zero the new character that i am adding is also b compare it with the p dictionary and confirm the value so with this approach we have considerably reduced the duplicate calculation that we are doing only working with two characters at a time the new character that is being added and the old character that needs to be removed with this solution our time complexity is o of n is equals to the string length of s and our space complexity is whatever is the size of this dictionary now if you think about the worst case scenario this dictionary has the key alphabets and based on the given constraints that we can have the string with only a two z characters small case so the length cannot go more than 26 so our space complexity is constant space of one now let me show you how this solution can be implemented using c sharp so here is my c shaft solution in the main method i have initialized this written value variable which is of type links of end which will hold all of the indexes from where analgrams are beginning from string s then i have a validation to check if the string s is not empty p is not empty and the length of s needs to be greater than or equal to p dot length if the length of s is small then it won't have enough characters to build an analog the next step is i'm calling this helper method parse string to map which will convert string to a dictionary of type character and integer so i'm passing p and in the next line i am calling the same method but passing the substring of s starting from 0 to the length of p so it will get me the first three characters based on the example that we talked about earlier the next step is to compare the first two maps that we built so the p dictionary and the first set of characters from s if the two dictionaries are equal we will add the index 0 to the return value variable the next step is to start the for loop in the for loop i am extracting the next character that we need to add to the current string this first pointer variable will hold the pointer for the character that needs to be removed in this section i am removing that character from my s dictionary so i am decrementing the count of that character in s dictionary and if the count is equals to 0 it means there are no more characters left in the string so i am removing that completely from the s string this will reduce the number of iterations that i have to go through when i am doing the comparison between the two dictionaries after this the next step is to add the new character which we identified on line 23 so i am checking if the character exists in the dictionary if it exists then i just need to increment the count and if it does not exist then i am adding a new entry with the count one and after that i am calling this compare method again passing the status of p dictionary and s dictionary and if the two dictionaries match then i am adding the index of i minus p length plus 1 because my eye right now is pointing at the last character of the substring so i need to retrace my steps back and calculate the starting index of the string hence i am doing i minus p of length plus 1 after this is complete i am incrementing my first pointer because now in the next iteration i need to remove the next character after the whole for each loop is complete i will have all the right indexes added to this return value variable and i am returning it on line 55. one helper method that i am using is compare which accepts two dictionary it will iterate through one of the dictionaries and compare if the key exists in the next dictionary and the count also matches if either of the condition is not met it will return false after the forage loop is complete and all of the conditions are satisfied i will return true the other helper method that i have is this parse string to map which accepts string iterates through all of these characters in the string and adds it to this dictionary variable if the character already exists it will increment the count thank you for watching this video i hope you were able to understand my explanation if you have any questions concerns or comments feel free to reach out to me this source code is available on my github repository and the link is there in the description below feel free to check that out and i will see you in the next video thank you
|
Find All Anagrams in a String
|
find-all-anagrams-in-a-string
|
Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "cbaebabacd ", p = "abc "
**Output:** \[0,6\]
**Explanation:**
The substring with start index = 0 is "cba ", which is an anagram of "abc ".
The substring with start index = 6 is "bac ", which is an anagram of "abc ".
**Example 2:**
**Input:** s = "abab ", p = "ab "
**Output:** \[0,1,2\]
**Explanation:**
The substring with start index = 0 is "ab ", which is an anagram of "ab ".
The substring with start index = 1 is "ba ", which is an anagram of "ab ".
The substring with start index = 2 is "ab ", which is an anagram of "ab ".
**Constraints:**
* `1 <= s.length, p.length <= 3 * 104`
* `s` and `p` consist of lowercase English letters.
| null |
Hash Table,String,Sliding Window
|
Medium
|
242,567
|
39 |
Videos related to this torch started and the name of your question and question from blind is this combination song AP's statement on force take you easily and question kahne kaise hain we have kept from the candidate that I represent the messages to the candidate and target Confirm that we have given, let's represent. Okay, so we have been given candidature 2367 and we have to reach the target seven, that is, we have to find some combination of all these which will result in that one will be yours and Pooja is coming. In example 1 this is two three. And in the seventh question, Ajay has used the district board. He is saying that understand the number, it should be the same combination or it should be the seventh. This combination should be there, meaning we have one number and can use it as many times as we want. But we will not repeat a combination like I have said here, guys repeat two and free once, then the sum of all of them is enough, then they can get serious disease, the other one is my tablets 12322 Yes, but both of them are the same, if you fold such things, then it means asking for the combination of your friends, they are imitations, they are the same, inside the combination you have got, you have to keep the beans back to front, this is not allowed, you took a navy approach. The only difference is that from reaching the Tikki 236 73 target till there, one method related to this is the advice that we have reached the intake, the other is that let's celebrate 6216 combinations, see here the rate of every 6 in 6. There are two connections, if it goes above then we will reject someone like this. Now I am talking about how Tulsi will grow from two to 123 to 600 children. How is it okay? It will happen in this way that if I tell you also in this lemon approach. Now let me show you 2019 in to-do, when you will Now let me show you 2019 in to-do, when you will Now let me show you 2019 in to-do, when you will do it, one will come here, two 23 A while and s also you will get two three, one, both of these, wait for the correct owner, got the same combination, if you do MP Dr, then here. It gets messed up. Is there any way to avoid it? Is there a better way than any other? So let's do this. We have kept 2367 with us. Okay, press the targets. We make such a decision free that this question is on the record seat. The minister is such that from the record that on one side we take it as a side effect and on the other side we take it in such a way that if we can't even take it, then how can I accept that if we ca n't even take it here, then come back too. Yogi repetitions can be done in Robert. This combination will be repeated. Loading So we can have two wallets. Now we have only one such that you can come here. If you cannot come from the other side also then it is broken here. If you can come then this is true, is one What will happen to the second one, here one time two will come and let's move ahead, here free time two can come, third second kiss, what will two time toe come here, then will we move ahead with Ajay Devgan or it is happening eight? So wait here brother, let's talk here, we can have two or three in two wallets or one, how can I take all, you will also see that all the ones that are going to be two are two, three have come and then with the second one in which that No one can come like this, you will see this line, it will go acid, see here also, it is 2012, so what are you doing, you can't be free and gas cannot come in front of you for 1 second, so this Now you know going forward here there is going to be six and seven and adding six to two is equal to eight and if they are to be joined together then eight and nine are there, whose is outside that number of two-three is also of two-three is also of two-three is also eliminated. Here we have an option to transfer the governments of the country, otherwise we will have to fly ahead of this, what will happen next, friends, who will have the complaint, the 11th will go, in TMT number 462042, two are connected and two have holes and a pair has been formed. Not allowed in the right way, things are going astray here because from other country, two cannot come here, what can we do, 32 can come brother or there is nothing like that, there is no problem, Spain is at a distance, so it will keep going. Something new will keep on coming, we will do it, okay, three can come, okay brother, let's move ahead, what will I ask in this case, if nothing is coming, that is why if I go into it, then either it will come with me, or nothing will come, meet here at the same time. So this time we are getting the right things as to how we did it, see the decision of 22, either it is there or not, it is superhit, run time, complexity, Mario needs, it is as if it is the target, Jai Hanuman, I am to you, this is our approach. I will pray, okay and you are getting the easy code very simple, so of course, let's make it etc. Let's go, I have already taken the court 108 times, I will show it to you by commenting, then let's talk, okay, so this time is also happening. If it takes time to type, then I will do this so that the answer can be MT, so that we can understand it quickly, not only will we create the function, what is going on, the whole function is running, I will tell you that we will call this function one time and just by calling it, From this, all our work will be done that the values inside the answer will all our work will be done that the values inside the answer will all our work will be done that the values inside the answer will increase which was our actual arm chair. We will return this to the answer. This is such a small thing. Know all this about what is inside Wisconsin. Okay, so I kind of stopped it and That I took a little modification to the candidate directly, took the target roti, when the women's Lokap is easy, then now we took the awakening parameters inside the function, which was pointed, these will appoint two-three, like I had just two-three, like I had just two-three, like I had just shown dysentery, so first two legs. Keep the pointer, so if our total is coming equal to T, then this is the right thing, that is, we understand that it is coming equal to the target, it will be good for us who came together at the end, then the answer is OK, then make the payment now. Why did you make a copy of the map while we are going to update the current? Go below and show how you have updated the map by making a copy of the current because there is sugar in the current. Okay, if you fold the current or the reverse side, then this is the answer. Whatever is pending in the list will be the final answer that now this monkey answer is there for the list, the first task is to return it on this day, if your point goes beyond the candidate's length then all this is useless. If it goes, then our total will be more ahead like mine was coming 10118, so while I was explaining, neither the flame of all that gas, I returned all this as needed, empty, whatever was needed, what was the case that if the eject comes then paint is here. It will be done, if he does n't come then he won't be here, okay, then what will we do in the current, we will up-end the then what will we do in the current, we will up-end the then what will we do in the current, we will up-end the candidate in whom I have put two in the beginning, the current was empty, then if you first made the decision tree, the first part of the decision in which two is coming, okay. There is another second part in which we pop, no, the two milk stations, first I liked that too, then we have the second one, now we are going to sleep, this is going on in a different way, now what have I done in this, as if I am in the figure right now in my mind. Keep what I just explained to you, what was there in one, I will tell you how to do it, 200 that one had this, two, one was empty, went down and what happened to you, here, don't give two, then there was only two here. What were we doing with this garlic, we had kept 13, after that we had kept a blank space in the front, we had made some figure like this, if you want to explain then this is the part of Ju-2, that is, now this is the part of Ju-2, that is, now this is the part of Ju-2, that is, now whatever message is in front of us, many will be connected, right, you say. I did the total which was nothing at the moment but because of adding stitching in it, our total got saved, meaning the total is Jio in the beginning, as it is known that these last three parameters of ours, you are definitely not broken and that means the total has been taken as zero. Inside, we did the first rally in Delhi that after all 28 grams will be put in this line, this kind of work is going on here, in the first one in which work was done with two, in the second one, if you made two of them get blown up then you made it to your house. I took the point forward, let me show you the description of the lights, what power they had, what three there were ahead, we started working with Natin, then people started moving again, this work is being done in a reciprocal manner, they are finally visible to us. It's okay, so I would have liked this method of back tracking and what do you have that you did not understand, tell me which line, I don't think there will be any problem in revising the video once, it is okay, just keep this combination. We are medium type question meaning explanation a little age has become longer it is not necessary to understand anything by the
|
Combination Sum
|
combination-sum
|
Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**.
The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input.
**Example 1:**
**Input:** candidates = \[2,3,6,7\], target = 7
**Output:** \[\[2,2,3\],\[7\]\]
**Explanation:**
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
**Example 2:**
**Input:** candidates = \[2,3,5\], target = 8
**Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\]
**Example 3:**
**Input:** candidates = \[2\], target = 1
**Output:** \[\]
**Constraints:**
* `1 <= candidates.length <= 30`
* `2 <= candidates[i] <= 40`
* All elements of `candidates` are **distinct**.
* `1 <= target <= 40`
| null |
Array,Backtracking
|
Medium
|
17,40,77,216,254,377
|
645 |
Hello everyone should stop this question of second match latest mismatch will happen again description changes question even your that I set of India is visually contain all the number from 128 digit point to time drops number is as defeated to the number wins and which Is the definition of one number and of the number ok and give example this quarter inch tutu fluid and number all that a look at patna vacancy verification form so and the symbol of the number 3 ok sweet friends welcome to maintain your through 200 units Growth rate data status of the set up to draw out the number of tourists to the number trace missing at least 3 and valued advisor for rent in the form of are very well written in that case how they can be heart even tried to avoid you Want To See The Question More To Share Code In Sports Federation President Creative Director 10 Minutes Complete Turn Off Three Types Of Gadgets Now One Innovative Has Answered This Answer And Restoring And Answer Entertain Twist Near Answer Edifice And Decorating This Asset Nod32 * Hydrate And Decorating This Asset Nod32 * Hydrate And Decorating This Asset Nod32 * Hydrate Inspector Middling This Sapoch 12123 Ok 999 Avoid Giving To Subscribe 2002 Subscribe That I Have An Internship Here Already Have To Injured Set The Time What They Are Doing Viewers Will Ask Value In Raavan Select Amazon In This Movie Will Want To Swing The Ball Final Report In Senior Class Located At 125th Element Subscribe Now To Three Do Subscribe Hello Viewers Now This Velvet Within 6 And 9 Inch Award Winners Terms For Love In Speaker Meghraj 1251 subscribe The Channel Please subscribe this one Speaker A
|
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
|
34 |
Ajay Ko Jhali Hello brother Manish Mishra from Falling Swayam Sachin is important but I have to try that question whose name is Find First and Last Position of Element in Spotted. Okay, so you have got the basic question. What would you have got in this question? Found a target, you have to tell the first to last index basic of this target like this is the life target to its foster friends to the last actresses of content police then you have to fill the monthly information and return it to me and if there is any such target. Which is not confirming about you, then you will say that it could not be returned in the nutritious juice, I will meet you, I will make such an ID and return it, both of them read minus one on it is fine, now it would be much easier to do it in oil. We search from the left side to find the first friend of the two. We search from the right hand side as if the first two together stopped thinking that we have finally found this one, okay, we could have done it easily, but basically we do this. If you want to log in or want to take advantage of having a sweater, then for this reason, if we try to connect with such people, then what will we do, I have kept it here, I take it out - if I put it on, it here, I take it out - if I put it on, it here, I take it out - if I put it on, I take it out, but I would like to indulge more in the first, I would like to keep Sachin even after meeting here, that I would like to keep my Sachin even after meeting here, now I cannot do this nor should I put it, so I will put the second last point to do this, you found this search. So let's say that because friends - I have that because friends - I have that because friends - I have n't found it yet, Sambalpur will be completed because you idiot are seeing the target every minute, Rafi, I will update that at least I saw an index of two, so we are stuck and have updated from NIFT. But now we have not stopped, we have kept the setting contribution on the left side, due to which I have increased the hike and kept it at minimum. This time you have again taken out the minutes, so this time your matching index number is correct where you see the target small value. If it is coming regularly, then people will find it in the search direction, pick it up and put it on middle schools. Okay, here when you searched, you saw the index number two on which two is ignorant. So, from what was posted last time, now the currency on the left side of the course must have come. If again you are able to see tu then update it to Chennai Express Mid-day update it to Chennai Express Mid-day update it to Chennai Express Mid-day and still remember the setting left side font in 'Hi' as you font in 'Hi' as you font in 'Hi' as you keep it on management, the searching will stop because it has gone ahead of the iron so you have to You will get a four sequence of 10 and it is right on this number. It is very similar from now onwards. If you are extracting the juice till the last of June 2, then let's quickly look at it and fold it. Okay, so like I will do something strange now. So I did not give the last index of the bat, I put it in the last but what will you do about them and you will keep it here, people will keep it here, oh that removed it, I can see Mitthu, I have updated it, I can see you intact from the to-do list, see you intact from the to-do list, see you intact from the to-do list, you can see the dead body. Put four in the lace and to keep Shakti continuing on the right hand side, I will pick up people and put them on mitt plus one that if they take me out last then I will keep Sachin continuing on the right hand side. This time you have basically taken out the comment. So I will be visible to you, six exercises, just by doing small twists, if you see two again, then I can update it and still continue searching on the right side, people have picked up and kept it on plus one, okay, this time you will bring out your So I am on this line number 7 which has a value bigger than the target, so when the value is bigger than the target, you have raised the hike and placed it on Mirchi Ayan and your Sachin group will go, okay, you have a perfect post index, keep the red mark. Do, we just apply these small benefits, then log in properly and show it. Okay, so let's fold it quickly. Okay, so look at this, basically, you have to get the return and one answer is to get the deposit done, which is the size, so the answer is 10 sentence post. The index will tell and the existence of darkness will make changes in the free mode. Last minutes is that element. Okay, so I and first of all the answer here should be to make the end. I have made the answer of two sizes, I will make it for you - one minus. One is fine - one minus. One is fine - one minus. One is fine because if you make 'A' then it will because if you make 'A' then it will because if you make 'A' then it will read 'zero' at both the places. 'I am an alcoholic', if it read 'zero' at both the places. 'I am an alcoholic', if it read 'zero' at both the places. 'I am an alcoholic', if it is not found anywhere in the middle then '-' is not found anywhere in the middle then '-' is not found anywhere in the middle then '-' is mentioned. It is fine on export. ' mentioned. It is fine on export. ' mentioned. It is fine on export. ' In his life, he has been deprived of it.' People have In his life, he has been deprived of it.' People have In his life, he has been deprived of it.' People have placed some obscene advance at zero - placed some obscene advance at zero - placed some obscene advance at zero - on force and now have started extracting their first index. A binary search file first index. Ok, how long will this work till you take this lesson in course? Hi, what will be the work - it will be extracted. Take what will be the work - it will be extracted. Take what will be the work - it will be extracted. Take out the jagi, take out the plus cribe, is n't it, and now saw that it was cut on the area of the minute, n't it, and now saw that it was cut on the area of the minute, n't it, and now saw that it was cut on the area of the minute, first my slave lineage would increase, then get the changes done, if I got the target on your feet, then forgot that yes metal, I got the target, and look ahead, if the target is bigger than the admit. If seen then you will find that go here quietly and search on the right hand side, if you find the target then people were boasting about Laxman and if the admit in the target is seen small then they pick it up and fry it for a minute. This used to be your regular water search but I If I have to score points today, first of all, what will I do here, should I say that I have targeted well, if I have taken it in the conference, then go to the answer of zero, make me fortune next and do this for more minutes and keep it continuous. If you search on the left side, then continue searching. These left hand sides are lifted, you click on continue, keep your searching, what has to be done for this, profit - keep the exam profit - keep the exam profit - keep the exam clear in mind, similarly, the board of your last reference will also be visible, so you can bring it, for this, I take this I am coming and what changes do we need to make here, first of all fix the low height but if it has got damaged then keep people on the districts and Raghu again add the ad entrance - close it at ad entrance - close it at ad entrance - close it at this time and after that here. But there will be a change here, I want to keep a container in my diet. If I take out the last one, then if I meet the target at the airport, I will keep my Sachin's continuation on the right hand side. Okay, so to keep the Sachin's continuation on the right hand side, you have to pick people up and meet me. It has to be kept on plus one, rest of the things, how was it found? Okay, so see here exactly both - by applying, we will let exactly both - by applying, we will let exactly both - by applying, we will let you log in a proper. 2 - I thought this is just the first you log in a proper. 2 - I thought this is just the first you log in a proper. 2 - I thought this is just the first - if I get the element posted in - if I get the element posted in - if I get the element posted in that you get this on 1 minute. What to do: that you get this on 1 minute. What to do: that you get this on 1 minute. What to do: Click on continue on the lift, I have continued searching because it has been removed from you. Similarly here, if you have been tweeted on the left minute, then I have continued to Sachin on the right hand side because you have to remove this in the last or I made a small mistake. I have done the answer to the last index. Become a send expert and get it done. Watching is on x100. The last stage is on the answer option. It is okay. If you ever don't get a chance, then consider self- consider self- consider self- selection. I will continue studying. Secondly, finally, I will definitely report this answer. Right, one photo is correct, final, let's run it and see the control as before with color, it is good, yes, it is the right answer, just submit, so what side is there, okay, then login, let us do this, okay, if we win. I hope you liked the solution, if you liked the solution then it is okay to like it and if you are new to the channel then please subscribe so that you get the notification of the upcoming question. Okay, in the next video. Let's meet Ajay with this question
|
Find First and Last Position of Element in Sorted Array
|
find-first-and-last-position-of-element-in-sorted-array
|
Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value.
If `target` is not found in the array, return `[-1, -1]`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[5,7,7,8,8,10\], target = 8
**Output:** \[3,4\]
**Example 2:**
**Input:** nums = \[5,7,7,8,8,10\], target = 6
**Output:** \[-1,-1\]
**Example 3:**
**Input:** nums = \[\], target = 0
**Output:** \[-1,-1\]
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `nums` is a non-decreasing array.
* `-109 <= target <= 109`
| null |
Array,Binary Search
|
Medium
|
278,2165,2210
|
1,079 |
hey how you doing guys it's ilya bella here i recording stuff on youtube chat description for all my information i do all legal problems make sure you um subscribe to this channel give me a big thumbs up to support it and this is called leather tile possibilities you have a set of tiles where each style has one letter thus an i printed on it return the number of possible non-empty sequences of letters possible non-empty sequences of letters possible non-empty sequences of letters you can make for example we got this input which is aab and we return eight because the possible sequences are a b a and b a right here we return uh 188 because of that input the length of that tiles is greater than or equal to one and is less than or equal to seven does consist of uppercase english letters well i'll show you how to solve this problem recursively and first you need to create the dictionary which is an array of the type integer which is the frequencies new int 26 time to that array is equal to 26 because there are 26 letters in english alphabet uh we create for loop uh char c uh tiles dot 2 char array uh and at the position of the current character minus uppercase a because of that ascii table right there are different representation into that table and you can see from the description of this problem that uppercase english letters and we increment the value by one the number of times each character appears into that tiles next we return uh the helper method and we pass the frequencies uh all you need is implement this helper method which is return time integer helper um in ensure let's say frequencies um int count is equal to zero you create the for loop and i is equal to zero is less than um 26 because there are 26 letters in english alphabet we got letters in this problem and at each iteration you increment count by one each time you see that the frequency is not equal to zero if it's so then we continue we say frequency at the position of i is equal to zero then we continue we go on looping um and we say frequency at i minus count plus equal and we call this method which is the helper method recursively robust frequencies and uh you know we do the depth for search and then we when we are at the bottom we start back dragging and we increment uh the value at the position of i by one and finally uh we return this count that's the whole problem let's run this code let's submit okay good thank you guys for watching leave your comments below i wanna know what you think follow me on social medias on instagram on snapchat um give me big thumbs up to support my channel and i'll see you next time bye
|
Letter Tile Possibilities
|
sum-of-root-to-leaf-binary-numbers
|
You have `n` `tiles`, where each tile has one letter `tiles[i]` printed on it.
Return _the number of possible non-empty sequences of letters_ you can make using the letters printed on those `tiles`.
**Example 1:**
**Input:** tiles = "AAB "
**Output:** 8
**Explanation:** The possible sequences are "A ", "B ", "AA ", "AB ", "BA ", "AAB ", "ABA ", "BAA ".
**Example 2:**
**Input:** tiles = "AAABBC "
**Output:** 188
**Example 3:**
**Input:** tiles = "V "
**Output:** 1
**Constraints:**
* `1 <= tiles.length <= 7`
* `tiles` consists of uppercase English letters.
|
Find each path, then transform that path to an integer in base 10.
|
Tree,Depth-First Search,Binary Tree
|
Easy
| null |
412 |
hello everyone welcome back to Alico problem solving session today we're going to be doing probably the most infamous interview problem is dare I say extremely easy if you do know how to code if you don't know how to code then I could see it just understanding exactly how to write the code to do this would be a problem but if you are familiar with coding at all it should be pretty straightforward so here we are given an integer n return a string array answer where answer I equals fizzbuzz if I is divisible by three and five answer I equals Fizz if I is divisible by 3 is our I equals buzz if I is divisible by five answer I equals I as a string if none of the above conditions are true so in n equals three we would return one as a string two is a string and then Fizz n equals five you do one two Fizz four buzz and then n equals 15 you know all the way through 15 and then 15 since it's divisible by three and five you would return Fizz Buzz so we're going to have our answer array and then for Iron Range 1 to n plus one now we need to figure out exactly how we want to do this so well if it's divisible by 3 and 5 if I mod 3 equals zero and I mod 5 equals zero then answer dot again fit LF I mod three equals zero answer dot append oh sorry first is Buzz is it both this one will be fizz and then otherwise it's five divisible by five we can end a Buzz keep in mind you don't want to do separate ifs here you do want this L if because if you do separate ifs then both let's say for 15 both this would execute and this would execute actually as well so you don't want that you want to make sure you're going this is only going to be this is code we only want to run if this is not true so we need this L if here but then finally we have an else where we just append E string of I and then we can return the answer so if we just click run one tooth is yeah all the test cases that they provided let's pass one thing I like to do when solving this problem is because there is kind of repeating a repeating use of constants people might be wondering what the constants are for you can define a Fizz number and a buzz number and then just change all of this to be in relation to that so if they ask you oh what about if we made it six and 13. well you have code that it's very easy to change you just change this business buzz you could also I guess have a Biz string where it's sort of like an abstraction same thing with Buzz it's an abstract it's an abstraction of Fizz and Buzz obviously these names might be a little bit weird given is being changed but I think for the most part just changing your solution so that it's more flexible will show that even with an easy problem that they give you are thinking about proper design principles when it comes to maintaining your code you know things like that you don't want to kind of black off actually we don't even just this string bus string and let's just double check it still works awesome so yeah this is the final code that I would probably have written I think it's you know obviously not they like it looks a little bit more complicated than the typical Fizz buzz and most people aren't going to implement it like this so you will be kind of setting yourself apart if you are asked this as someone who is thinking ahead in terms of oh what if they change certain requirements of this problem how am I gonna deal with that so probably even if you knew how to solve this was a little bit instructive uh yeah thank you so much for watching if you guys have any questions about the solution in the comments please let me know and yeah please like And subscribe see you guys next time
|
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
|
1,657 |
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is determine if two strings are Clos so in this question we given two strings and they're considered close if you can attain one string from the other using the following operations the first operation states that you can swap any two existing characters in the string and make a new string so for example B and E can be swapped and the positions are interchanged and you get this string and in option two you can transform every occurrence of one existing character into another existing character so it's not any random character that character should be present inside that string and we can do the same with the other character so all occurrences of a are transformed to B and all B's occurrences are transformed to a and you can perform this operation any number of times on any of the strings and finally our task is to return true if word one and word two are closed else we have to return false now let's take a look at these examples and see how we can solve this question so let's take the first example I've taken the same example as example one we have two words word one and word two now we have to count the frequency of every word right so I created a frequency array called freak one of size 26 because the input contains only lowercase English letters and there are 26 letters inside the alphabet right so this frequent will contain frequency of words from word mod and we create another frequency AR called freak 2 of same length as 26 which contains the frequency of words of word two so we iterate through all the words and we pick one character at a time we pick a we increment its count by one I'll show you during coding how we are inserting that position frequency now we are at B increment is frequency we are at C increment is frequency let's do the same for word two B's frequency is incremented by one C's frequency is incremented by one A's frequency is incremented by one now we have the frequency array of two words now we use a for Loop to iterate from zeroth index position to 26th index position and we use a single for Loop to access both the frequency ARs and we compare the index position 0 to 25 so this for Loop will run for 26 times and we access one character at a time from the array so we compare this and this we check if one of them if frequency 1 element is equal to Z and frequency 2 element is not equal to Z rest of the elements are zeros right so for example if e was zero here but here e was 1 there is no way we can get a new e inside word one so that is why we return false in this case and similarly for example if this was 1 and H was 0 here we check if frequency 1 element is not equal to Z and frequency 2 element is equal to Zer then also we return false because we cannot bring a new H inside word two we can only swap the elements once in operation one and we can swap every occurrence of that element with every other occurrence in operation 2 so our task is to check these two conditions and for example if J was 2 here and J is three here that is fine because there means there are some occurrences of J in word one and some occurrences of J in word two we can swap the elements and make both of them equal so how are you going to check it you are going to sort this frequency array from ascending to descending so if you sort the F1 we get 23 zeros and in the end there'll be ones and if you sort FS2 there will be 23 zeros and in the end there will be 3 1es since these both are same after sorting we can return true as the output so I've taken the third example now let us fill the frequency array so this is F1 of size 26 and this is F2 of size 26 so this will represent word one and this will represent word two now let's fill word one frequency we iterate from left to right we pick one character at a time increment C's frequency now it's a increment a is fre frequency it's B increment B's frequency then B again B's frequency is incremented to two then B again B's frequency is incremented to three and then there's a again so A's frequency is incremented to two and the rest of the array is zeros now let's do the same for word two we iterate from left to right we access one character at a time increment A's frequency increment B's frequency it's a b again increment B is frequency to two it's a c again increment C's frequency it's a c increment C's frequency to two it's a c again increment C's frequency to three and rest of the characters are zeros now if you directly sort this string you can't directly compare if there are both close so this after sorting all the characters will be sorted in ascending order and if you sort this it will be sorted in ascending order and now you can't directly compare them and make them as true or false in this case it's false but the answer is true so now you have to compare the frequency of those characters so if you check a character's frequency and if it is zero in FS1 and more than one in FS2 then you can return false because you can't bring up that new character for example if there was I in word one there is no I in word two then you can't get a new I in word two using free operation one or operation 2 so that is why if there is a match at any index position inside the frequency RS then you can directly return false as the output for example in Reverse case if this was if M was 1 in FS2 and if m is z in fub1 then also you will return false because you can't get m in word one by using any of the one or two operations so that is why you can return false and if you after you perform these two checks if you haven't returned false you have to sort these arrays into ascending order so here in this case you can see a is equal to 2 and B is equal to 3 and C is equal to 1 and here in this case a is equal to 1 B is equal to 2 and C is equal to 3 the frequencies are not matching but both of them are having frequencies so you can perform operation one and operation two and make these both frequencies equal so how are you going to do that you will sort this array of 26 size in ascending order so after sorting all the zeros will come in the front so after sorting these both in ascending order the sorted arrays will look like this all the zeros will come to the front and last three elements are 1 2 3 and this is also 1 2 3 now these both arrays are same right so you can return true as the output because you can perform operation one or operation two and make the two frequencies equal so let's Implement these steps in a Java program so here you can see there is a edge case here if the word one length and word two length are different you can return false as the output so here a is equal to 1 and a is equal to 2 so after sorting F1 the frequency arrays of size 26 will have 25 zos and last element will be one and here also there will be 25 zeros and last element will be two since they are not equal it will return false but here only we can directly return false as the output if the lengths are unequal so I'm comparing word one length and word to length and checking if they're unequal I'm returning false now I'm creating the two frequency array of length 26 because they are only lowercase English letters first I'm iterating through word one by converting it to a character array I'm accessing the character by character so for example if we take word 1 equal to ABC character array will make it a b c and I access one character at a time and then place it inside frequ one array so CH will be the character which I'm accessing minus a will sort it at its uh index position so a has the asky value 97 since we are accessing a this is also 97 - 97 is index position 0 so fub1 97 - 97 is index position 0 so fub1 97 - 97 is index position 0 so fub1 of 0 will be incremented by 1 for a so F1 of 0 represents a and FS1 of 25 represents Z so I'm doing the same for word 1 and word two we have the filled array now I'm iterating through the frequency RS using a single for loop as both the lengths are 26 we can use a single for Loop to iterate through both of them and this is the condition I'm checking one character is not present inside frequency one and that character is present inside frequency 2 or if that character is present inside frequency 2 and it's not present inside frequency one it means you cannot get that character from any of the operations so you can return false and if you haven't returned false here you sort the two arrays in ascending order you compare the two arrays if the two arrays are equal then you can return true else you will return false if they're equal it will return true else you will return fals so the time complexity of this approach is O of n where n is the length of the word one or word two the longer of the two and the space complexity is of 1 because we using constant space so in t of size 26 right so this is a constant space AR because for every question the space complexity is O of 26 which is constant so o of one is the space complexity so the time complexity is not o of n log n because we're sorting the arrays here and the arrays length is of constant space right so the space complexity will be of O of 26 log 26 which is constant so that is why you can use o of n as the time complex that's it guys thank you for watching and I'll see you in the next video lady
|
Determine if Two Strings Are Close
|
find-the-winner-of-an-array-game
|
Two strings are considered **close** if you can attain one from the other using the following operations:
* Operation 1: Swap any two **existing** characters.
* For example, `abcde -> aecdb`
* Operation 2: Transform **every** occurrence of one **existing** character into another **existing** character, and do the same with the other character.
* For example, `aacabb -> bbcbaa` (all `a`'s turn into `b`'s, and all `b`'s turn into `a`'s)
You can use the operations on either string as many times as necessary.
Given two strings, `word1` and `word2`, return `true` _if_ `word1` _and_ `word2` _are **close**, and_ `false` _otherwise._
**Example 1:**
**Input:** word1 = "abc ", word2 = "bca "
**Output:** true
**Explanation:** You can attain word2 from word1 in 2 operations.
Apply Operation 1: "abc " -> "acb "
Apply Operation 1: "acb " -> "bca "
**Example 2:**
**Input:** word1 = "a ", word2 = "aa "
**Output:** false
**Explanation:** It is impossible to attain word2 from word1, or vice versa, in any number of operations.
**Example 3:**
**Input:** word1 = "cabbba ", word2 = "abbccc "
**Output:** true
**Explanation:** You can attain word2 from word1 in 3 operations.
Apply Operation 1: "cabbba " -> "caabbb "
`Apply Operation 2: "`caabbb " -> "baaccc "
Apply Operation 2: "baaccc " -> "abbccc "
**Constraints:**
* `1 <= word1.length, word2.length <= 105`
* `word1` and `word2` contain only lowercase English letters.
|
If k ≥ arr.length return the max element of the array. If k < arr.length simulate the game until a number wins k consecutive games.
|
Array,Simulation
|
Medium
| null |
890 |
hello everyone welcome to day 21st of my lead code challenge and today's question is find and replace pattern so without much to do let's look at the question and the solution why the presentation that i've created for this and let me just start the slideshow let me just take a pen i hope all of you are enjoying these everyday ds algo questions and let's focus on the question find and replace pattern lead code 890 let's get started the question says we are given a pattern and we need to find out words that match that particular pattern the pattern and the words are both given in the form of strings of english lowercase characters and we need to identify those words which abides to these this pattern so let's walk through the solution by an example i have taken a slightly simpler example here so that you get a better understanding of the logic here the pattern is a b c d and we need to find out words which are similar to this pattern the first one is f of 4 d f double o d y the second word is india the third one is beefy oh so this is nothing this is beefy the first thing that i am going to do i will be extracting the pattern in the normalized format from this input string what we will do we will start from the zeroth integer value and start assigning values to uh this pattern so a gets the zero value so this gets zero b gets one value again we encountered a b so b gets one c gets two value and d gets three value so the pattern here that we generated from the input string is of a kind integer and it is something like 0 1 2 3 and let's try to do a similar kind of a thing for the words as well also we created a map here which states that a maps to 0 b maps to 1 c maps to 2 and d maps to 3 although the map is only used for generating this pattern it has nothing to do with the rest of the elements so let's try to generate similar kind of a pattern for the words as well f maps to zero o maps to one and again we got an o so we get another one then we have d it's a new character so it maps to 2 y maps to 3. so what is the pattern that is generated out of 4d it's 0 1 2 3 which again is a matching case so since both these patterns match with each other this would be part of the answer set let's walk through the another case so if maps to zero n maps to one d maps to two again we encountered an i which will make it one here instead of a new character new integer value higher integer value then we got a and e maps to three so what kind of patterns generated here 0 1 2 1 3 which is not matching with our input pattern so it's a mismatching case we'll ignore this value let's try another example we have bc here so b maps to 0 e maps to 1 again we got an e which maps to 1 a new character so we will assign a higher value to it 2 by again a new character will assign a higher value to it so the pattern that is generated out of b fee is 0 1 2 3 which again is a matching case with that input pattern therefore b would be part of the answer i hope this approach is clear to you what will the time complexity of this approach the time complexity for generating the patterns order of length of the input word and you'll be doing it across all the words that are there in your data set so the total time complexity would be order of n into length of each word so let's try and understand it by the code the first thing that i am going to do is to identify a normalized pattern that is in the form of integers instead of string so i have created a normalized method here that will return me the normalized pattern for any string and next i created a variable that will store my answer set i traded over the words array and for each word i calculated a normalized integer string and in case it matches with the uh input pattern a normalized string then i'll add it into my result set otherwise i'll reject it in the end i simply return the answer now the question reduces to writing the normalized function efficiently so it has the return type as string and the accepting parameter is the input string what we are going to do will create a hash map that will store character comma integer mapping and i've created few variables here the first one is length and for the length of the input string the second one is the answer set the normalized string and let's start the iteration starting from the zeroth index up to the length of the input string will add the new character in the input string only if it is not already present so here it should be str dot car at i if that character is missing from the map then only we'll add it into our hash map and the value here would be map dot size initially the map size would be 0 and it will be auto incremented whenever there is a new entry in the map apart from this we'll append it to the answer whatever value is there at that particular character in the map so answered equals to answer plus map dot get str.cara type pretty map dot get str.cara type pretty map dot get str.cara type pretty straightforward and in the end we simply return the normalized string so let's just try this up looks good and let me submit this accept it i hope you liked today's session thanks for watching if you did please don't forget to like share and subscribe to the channel have a great day
|
Find and Replace Pattern
|
lemonade-change
|
Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**.
A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word.
Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.
**Example 1:**
**Input:** words = \[ "abc ", "deq ", "mee ", "aqq ", "dkd ", "ccc "\], pattern = "abb "
**Output:** \[ "mee ", "aqq "\]
**Explanation:** "mee " matches the pattern because there is a permutation {a -> m, b -> e, ...}.
"ccc " does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.
**Example 2:**
**Input:** words = \[ "a ", "b ", "c "\], pattern = "a "
**Output:** \[ "a ", "b ", "c "\]
**Constraints:**
* `1 <= pattern.length <= 20`
* `1 <= words.length <= 50`
* `words[i].length == pattern.length`
* `pattern` and `words[i]` are lowercase English letters.
| null |
Array,Greedy
|
Easy
| null |
983 |
welcome to august leco challenge today's problem is minimum cost for tickets in a country popular for train travel you have planned some train traveling one year in advance the days of the year you will travel is given as an array each day is an integer 1 to 365. all right so that's simple enough now we have three train tickets sold in three different ways a one day pass is sold for cost zero seven day pass cost one and thirty day pass for cost 2. now we want to minimize the total cost for our days of consecutive travel so in other words if we're given a list of days like this 1 4 6 7 8 20 we know that the minimum cost can be 11 because we want to get the seven day pass for one through seven and then just get one day passes for eight and twenty and that's going to equal 11. now immediately when i saw this problem i knew that it was a dynamic programming solution because you can already see that we could probably solve it recursively in a brute force matter just checking through every single day and every cost option that we have and trying to get to the very end seeing what the minimum cost is going to be we'd have to pass in the days that it would be good until um but obviously that's going to create a lot of different combinations which gets expensive so what if we had some sort of dynamic programming structure to help with this say that we had our list of days here and we had like for instance an array and we could say uh how about what's good what's going to cost for a one day pass seven day pass and for 30 day pass each day we can kind of check to see how much we're at so at seven days we know that we could either whatever the cost of this is i think it was two seven fifteen so here would be two here with the seven day pass would be seven and here it'd be fifteen uh so obviously the two is the minimum number now moving forward we can say well we have four days this would be six should be eight you know 10 12. we already know that's fairly straightforward but the trick here is once we get to the point at which we see that we could have bought a seven day pass we want to check at seven days what was a cost that we could have paid instead so instead of eight we see that seven days prior we could have picked seven days right so at that point if we're having some sort of like this is the minimum cost here then we could say all right here it's two four six here we know that well actually we could have paid seven we got paid 15 as well but seven is smaller than eight so we picked seven so that's kind of the idea now if we used a like a matrix every time we calculate the minimum cost what we'd have to do is go back the number of days looking at the array values up here to check okay which day is going to be our the last one that we could have paid for and that doesn't really work because you can imagine that it's no longer going to be of n we have to like calculate that each time and so that starts becoming really expensive again so that's not going to work so this really confused me for a while like what could we do exactly and finally i saw that instead of using like a matrix what if we used a q for these two structures like we had a q instead then we could pop off the numbers that as soon as we've exceeded the number of days that we could use it for so for seven here once we get to this point and when we check to see what's the uh minimum cost we could have paid instead what were all our alternatives we could pick the very first one and once we passed that date we go to like eight days then we pop that off we say well we can no longer use that so now we have to use whatever is here and this q needs to get built up every single time we calculate our minimum cost so here would be like 9 11. and so on and so forth and every time we like find that the number of days have exceeded we just pop that off we say nope can't do that anymore when we get to 20 we pop this off and that's going to be what allows us to use our dp structure which is going to be a queue so hopefully as i start coding this out it'll start making more sense let's start with initializing two data structures and they're just both going to be queues empty queues for now one for the seven days and one for the 30 days we'll also initialize the total cost min cost all right so now for all the days in days what do we want to do well first we want to pop off everything that we can no longer use from our dp arrays right so while there's anything inside of db7 and these queues will make them a tuple what we'll store here is the day as well as the total cost so far okay so while dp7 and dp7 the very first one and the very first object the day is greater or greater i guess less than or equal to the current day will pop it off top left and we'll do the same thing for the 30 days now we have to make sure that this one's going to be 7 so this will be plus 7 and this will be plus 30 right well i'm sorry i'm getting this confused it's minus 7 and minus 30. and we'll pop those off so let me see we can do that in a one-liner in python so can do that in a one-liner in python so can do that in a one-liner in python so that's good all right now we want to append to our dp7 and we want to append what uh well whatever cost well no not the cost it's just the current day as well as the cost that we calculated so far which is going to be calculated here plus the cost of well the cost of a seven day ticket so that's going to be the second one on solder inside of our cost list same thing with 30 we'll add cost plus cost with the cost of the 30 ticket all right now we need to calculate our cost so get the minimum of either whatever cost today with the cost of a one day pass or the very first tuple on our queue and we will bring in the what the second object so that's the cost as well as this right here oops that's same the 30 pass so whatever the minimum is between these three that should be the minimum cost so it's kind of like a greedy method we're going by each day and calculating what's the minimum kind of storing the past information and once we do that we can just return the cost all right so let's make sure this worked i may have made a mistake uh dp out of range okay that's just a silly typo there hmm okay so dp3 yeah so this is one of the problems with copy pasting kind of lose track of that kind of thing all right so 11 looks like it's working let's go and submit that and there we go so what is the time complexity on this well uh you can see it's all then sure we do these little popping things so technically there's going to be an additional um amount for the days but in overall it's oven and space complexity i think is actually o of n times length of cost so three so i'm not sure okay yeah i think the time space complexity is also of n i'm not entirely sure about that though okay so that's it i mean i know i explained it very quickly and it seems fairly simple but this is not an easy problem this took me some time to figure it out and once i realized that instead of using a matrix we should go ahead and use something like a q that made it a lot more easier to get this down so that's it thanks for watching my channel and remember do not trust me i know nothing
|
Minimum Cost For Tickets
|
validate-stack-sequences
|
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`.
Train tickets are sold in **three different ways**:
* a **1-day** pass is sold for `costs[0]` dollars,
* a **7-day** pass is sold for `costs[1]` dollars, and
* a **30-day** pass is sold for `costs[2]` dollars.
The passes allow that many days of consecutive travel.
* For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`.
Return _the minimum number of dollars you need to travel every day in the given list of days_.
**Example 1:**
**Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\]
**Output:** 11
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
**Example 2:**
**Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\]
**Output:** 17
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
**Constraints:**
* `1 <= days.length <= 365`
* `1 <= days[i] <= 365`
* `days` is in strictly increasing order.
* `costs.length == 3`
* `1 <= costs[i] <= 1000`
| null |
Array,Stack,Simulation
|
Medium
| null |
38 |
Hi gas welcome and welcome back to my channel so today our problem is count and say so what have you given us in this problem statement, here we have been given a wait number and according to that what we have to do is a sequence of digital distancing. If you have to find it, then how will you find it now, let us understand through the example. Okay, if you have N1, then the sting that will be made will have only van in it. Okay, when you have N2, what will you do? Here you will look at pay and van, what is there in n1, then you will see that van is given in it, what is the frequency of van, if there is van, then what will we do, we will write the frequency of van and we will write van, the number is ok, we have written it. Then when we have to find n3, we will find it from N2, so what is there in it, you will see that it is WAN, it is continuous WAN, so how much is its account, then you write here and which character will be here, then how will you find it, so here Here you will see, if you are there, how many accounts do you have, if it is a van, then first write this count and here you write this, okay what is his account and which number is this, then you will come here, then if this is a van, then how many accounts does he have? If there is a van, then we will write 1 as its account and we will write this number, this becomes when I have to find n5, then it will depend on what and on four, here we will see what is the count of van, so you have written continuously in You will see, not that you would have seen the overall but if we look continuously, here you are after the van, so here you will see only for the van, how much has been in its account till now, its count is yours, so the van is the van count and whose van is this van? We will write there is van, after that we will write there is van then we will write your account is van and this is you ok then here we will see continuously two are one then you will write here and van will write here this is counted and this The number is done, okay, you will find it like this, okay, so now how will we solve this problem, you see that when you are searching for you, it is dependent on you, finding it when n3. If you are searching for N2, you are depending on it. For end four, you are depending on what is on N3. For right and five, we have What will we have to do, whenever we have been given a number, we will have to come to the number by forming it from the initials and we will return the final answer we get there. Okay, so how will we solve this problem, see, for this we have to do What will happen is that here you have to find for n four, okay so first you have to find for n1, then for N2 you have to find for three and then when you come to n4, whatever you find for this will be yours. The answer will be okay, so whatever you find for n1, then you guys are okay for the answer, after that what will you do now here i0 okay now what will we do we will take one more k which will be equal to i okay now what will we do this You will see from where the number is, okay it started from here, it is equal to K, now it will move forward and you will see from where it is in the sting, so as far as you get from it will keep filling, but as it will move forward, when it comes to the van, you will see that This string is finished. Okay, so now how will we find the count? For N2, we have to first append the count here. So Jay - I, whatever happens will be your count. Okay, Jay - I, whatever happens will be your count. Okay, Jay - I, whatever happens will be your count. Okay, so this is on Kiss, this is on Van, and I is on Kiss. If your pay is zero, then how much is its count? So first you write the count here. Then what will you do? Whatever number you find for it, whatever will be on your pay is fine, whatever number will be on your pay, you will append it here. What is i pe is van so here you have done it okay this is done these now we will find for n3 okay from here we will process from here i will take zero and k will take i k ko okay It is done, now it will move ahead, it is equal, it is ok, it has gone ahead, the account is yours and whose account is this, whatever will be paid on I, what is the van, so van, you will pay up here, it is ok, now you have N When you have to find for four, then your 21 on n3 has been formed, what will you do, here people are zero, here and ki are equal to, ok, now you will solve it further, as soon as you are here, congratulations, you found out that These two are different, so now you will stop there and come up with 'K' mines and after seeing this number, you guys will come up with 'K' and come up with 'K' mines and after seeing this number, you guys will come up with 'K' and come up with 'K' mines and after seeing this number, you guys will come up with 'K' mines here, where is your van, now 1 - 0 will be 1, what will be its count? And - 0 will be 1, what will be its count? And - 0 will be 1, what will be its count? And which number is there on I, so you are here, you are ok, after that your I is here, now there is a different number here, so I will have to be updated and equalized, JK will have to be equaled, okay now this Here A Gaya then we will move forward to K Ja A Gaya Tu Pe and will see kissing is over and Ai Kahan Pe Van Pe is ok so what will Ja-I do here, this so what will Ja-I do here, this so what will Ja-I do here, this will be 2 - 1 and whose Which number will be 2 - 1 and whose Which number will be 2 - 1 and whose Which number is this on i, which number is on i, if it is van, then we will write van here, then it will become 1 2 1, this is it, for and four, when your n will be 5, then what will we do, and 5, then we will see this as van. You Van Ko, here we will take I first and here we will take K. Okay, so I is now equal, then now move K forward but you will see that here Pe is different, so okay, what will we do here? First frequency of both. We will find this WAN, then the K mines will be I WAN, its frequency will be which number is on I Pay, add the WAN here, people are ok, it has to be done in the sting form, then what will you do to I by updating it equal to K? Then what will you do with K? Then you will say badhaao further. Okay, I went ahead and saw that it is different here too, so what will we do here? Who will add to the frequency of both, the frequency will be your 1, which number came and which one? If the came and which number came and which one? If the number is you, then you will also add it. Okay, it is done, then you will update the account here, then you will send further information to this person. This is ok, then you will add further information. If the person will come here then it will be my account. How much will be the mines I will be equal to your 2 then IB which number is Van so here this is done then what will this finally become Van Tu Van is this neither is this nor this is formed we have to keep finding by doing like this So for how long will you do this n1, you guys, but to fine this number you will run volume till n - 1 fine this number you will run volume till n - 1 fine this number you will run volume till n - 1 and to fine this count also you will have to run a look. Okay, so now come the code people. In this part, I understand you. Okay, so what are we doing here? Answer: We have taken a Okay, so what are we doing here? Answer: We have taken a Okay, so what are we doing here? Answer: We have taken a van, now why have we taken a van because look, whatever your N is, it will start from 1 and go till 30, so in the initials you can say Lo, if your end if ≥ 1 will not remain i.e. it will be equal to van then ≥ 1 will not remain i.e. it will be equal to van then ≥ 1 will not remain i.e. it will be equal to van then this will be the answer, what will we do, find it, ok, we will start from I2 and take it till n, date min, for how long will this loop run, end -1 times then it will run ok. run, end -1 times then it will run ok. run, end -1 times then it will run ok. What will we do if we take the last string in the string, then what will become of the last string in the string? How much is it because if you walk here, what you are seeing is the easy, you are seeing how far you cannot go outside the length, so what will we do, what is the length of the previous testing, we will see that, then we will take the length in L. And we will take this zero, okay this is zero and what will we do again to slice the answer, enter here OK because now a new sleeve will be made, give lace till L, okay and we will take the count, this will actually fine the count and give it to you What we will do with this is that we have started from zero and G is your lesson till the end will be L and the last string will be J and the last string will be K and equals tu equation lasting count till it is equal we will keep adding plus the count i.e. here which We were i.e. here which We were i.e. here which We were telling you in the form of IG, I actually have written the code, I have actually taken k equal to k and to k we have shown the count. Okay, so what are we doing here till we have not found Right, you are doing like this, so count plus, whatever will be, it is doing less than that, this count plus, as long as you keep getting equal, it is okay, then you will keep doing plus, then what will you do in the answer, you will also make a new answer, right? What will you do, in the answer you will give me the cent count of mines i.e. this answer you will give me the cent count of mines i.e. this answer you will give me the cent count of mines i.e. this count will be given to you will change it in sting, people plus whatever element is there on your G, you will add it here, this will be added in the settings, this will be one of your testing. It will be created, then you have to update the equal of the account, like here what do we do, we are aperating the equal of the so here what we have to do, we have to update the equal of the count because we have done a little bit here. Took a different version of what I had explained to you, it was different, ok so I hope you have understood. If you liked the video, please like, share and subscribe. Thank you.
|
Count and Say
|
count-and-say
|
The **count-and-say** sequence is a sequence of digit strings defined by the recursive formula:
* `countAndSay(1) = "1 "`
* `countAndSay(n)` is the way you would "say " the digit string from `countAndSay(n-1)`, which is then converted into a different digit string.
To determine how you "say " a digit string, split it into the **minimal** number of substrings such that each substring contains exactly **one** unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.
For example, the saying and conversion for digit string `"3322251 "`:
Given a positive integer `n`, return _the_ `nth` _term of the **count-and-say** sequence_.
**Example 1:**
**Input:** n = 1
**Output:** "1 "
**Explanation:** This is the base case.
**Example 2:**
**Input:** n = 4
**Output:** "1211 "
**Explanation:**
countAndSay(1) = "1 "
countAndSay(2) = say "1 " = one 1 = "11 "
countAndSay(3) = say "11 " = two 1's = "21 "
countAndSay(4) = say "21 " = one 2 + one 1 = "12 " + "11 " = "1211 "
**Constraints:**
* `1 <= n <= 30`
|
The following are the terms from n=1 to n=10 of the count-and-say sequence:
1. 1
2. 11
3. 21
4. 1211
5. 111221
6. 312211
7. 13112221
8. 1113213211
9. 31131211131221
10. 13211311123113112211 To generate the nth term, just count and say the n-1th term.
|
String
|
Medium
|
271,443
|
1,936 |
hey everybody this is larry this is me going with q2 of the weekly contest 250 at minimum number of rungs so hit the like button to subscribe and join me in discord let me know what you think about this farm and so forth um so this one is just greedy um basically you're trying to get from zero to the last element and you cannot have any gaps right so the idea here is that okay for every length that is not long enough meaning that it is longer than distance you always greedily put the next one uh you know you fill it in as lazy as pos as minimal as possible and that means that if the gap is distance away you add one or well you add none but if the gap is distance plus one array you add one and so forth all the way up um and that's basically the idea i have here um i put in zero so that just as the first chord chrome run so that you know makes the math easier and then here i look at okay for every two adjacent um elements i basically do this um round down of the delta minus one because you want to round down and if it's exactly just uh multiple distance then you get that minus one right so that's basically the idea um and this is going to be linear time and technically linear space the way that i do it but of course you could just add some if statements and some pointers to make it constant space but yeah that's all i have for this one um i hope that this is this makes sense you basically if you have trouble visualizing just draw it out um and just you know play with some small numbers to figure out for example if you have a space of five um how many rungs do you do with if the distance is two in position in three then just play around with it that's how i did it in my head um you could watch me sub it live in the contest next but that's basically the idea um yeah and is there anything else for me to say yeah i think that's all i have um yeah i think the greedy comes from that you always want to minimize that ratio and that in a way this is memoryless in that don't look at adjacent elements because um once you get to a realm you assume that everything before that step is already good right so and you and it doesn't impact the future so that's why you're able to do greedy with just a jason or the last one if you will so yeah um yeah so you can watch myself live during the contest next let's see give it a submit okay that's good uh okay at minimum number of rounds you're given a strictly increasing height of your current on four zero you want to reach last one you're giving an energy distance if the distance between where you current at and the next one is almost say one okay let's see can i wish to ask for add one that's seven and eight okay so you wanna add stuff i mean this is gonna be greedy for sure this is great decide zero or one you're at zero okay um and what's distance again what am i doing again okay so distance is the number of steps that you can jump and you want to get to the last one okay so this is for sure greedy once i was going to see if i need to sort it's already strictly increasing so i'm okay there uh and i'm just going from left to right and then yeah okay so now for we just have to look at adjacent ones um where is the zero so we start at zero so let's just start at zero then so um i know that i'm writing this kind of this is technically linear but i think it is a linear algorithm anyway so for a b and sip of wrongs once uh some do so adjacent elements um v minus a round down i think let's see if there's five x i think i have to minus one but um if it's two exactly it's none okay i think this is this but i could be wrong it's strictly increasing i think let's also set this to but in case that it gets negative for some weird reason but let's run it real quick oh well i should return it run it real quick two zero one zero i think this is okay am i don't wanna rush it that's why i'm thinking about you know i think this is mostly okay i'm just trying to think about the edge cases i think this is okay though unless i've been off by one that's the only thing that's given a spin okay that's good okay q3 maximum but yeah hit the like button to subscribe and join me on discord let me know what you think about this problem explanation whatever you need to do uh i'll see you later stay good stay healthy and i'll see you later bye
|
Add Minimum Number of Rungs
|
maximize-number-of-nice-divisors
|
You are given a **strictly increasing** integer array `rungs` that represents the **height** of rungs on a ladder. You are currently on the **floor** at height `0`, and you want to reach the last rung.
You are also given an integer `dist`. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is **at most** `dist`. You are able to insert rungs at any positive **integer** height if a rung is not already there.
Return _the **minimum** number of rungs that must be added to the ladder in order for you to climb to the last rung._
**Example 1:**
**Input:** rungs = \[1,3,5,10\], dist = 2
**Output:** 2
**Explanation:**
You currently cannot reach the last rung.
Add rungs at heights 7 and 8 to climb this ladder.
The ladder will now have rungs at \[1,3,5,7,8,10\].
**Example 2:**
**Input:** rungs = \[3,6,8,10\], dist = 3
**Output:** 0
**Explanation:**
This ladder can be climbed without adding additional rungs.
**Example 3:**
**Input:** rungs = \[3,4,6,7\], dist = 2
**Output:** 1
**Explanation:**
You currently cannot reach the first rung from the ground.
Add a rung at height 1 to climb this ladder.
The ladder will now have rungs at \[1,3,4,6,7\].
**Constraints:**
* `1 <= rungs.length <= 105`
* `1 <= rungs[i] <= 109`
* `1 <= dist <= 109`
* `rungs` is **strictly increasing**.
|
The number of nice divisors is equal to the product of the count of each prime factor. Then the problem is reduced to: given n, find a sequence of numbers whose sum equals n and whose product is maximized. This sequence can have no numbers that are larger than 4. Proof: if it contains a number x that is larger than 4, then you can replace x with floor(x/2) and ceil(x/2), and floor(x/2) * ceil(x/2) > x. You can also replace 4s with two 2s. Hence, there will always be optimal solutions with only 2s and 3s. If there are three 2s, you can replace them with two 3s to get a better product. Hence, you'll never have more than two 2s. Keep adding 3s as long as n ≥ 5.
|
Math,Recursion
|
Hard
|
343
|
974 |
That in this problem where to find account of all the amazing maze special news like share subscribe button to subscribe this Video Please subscribe and subscribe the to know what will happen and effective way to return to all the black 06 that this wi-fi switch is simple Return Gift that this wi-fi switch is simple Return Gift that this wi-fi switch is simple Return Gift 5G Phone 1.5 Visual Five Simple Defeated This And 1.5 Visual Five Simple Defeated This And 1.5 Visual Five Simple Defeated This And Share This Page - 500 to 1000 To Do Subscribe To Hai Are So Lets Se Bhi Hai Thursday Late Evening Index And Online Web Content That AIIMS And Number On The Contrary Is Want To Front In The Morning That Time Visual Basic Knowledge Se Odd From Which Keep Track Of What Is The Meaning Of This Subscribe For Lakshmi 028 Pass Inside 020 For This Is This K Five List A Simple Example Thism Pregnant Hair It's Pintu Ki Suid F5 Vikas Jahi Hai To Extra And MP3 listen to and deficiency of trees to tarsem singh they can solve using both but sir plus readymade call login programming languages which are clearly 2205 return from here.the sure subscribe to from here.the sure subscribe to from here.the sure subscribe to subscribe and subscirbe ya ki hum laddu is sure ki to Again From 0001 From Big Chill Hair Subscribe From Big Chill Hair Oil subscribe Video Subscribe Ride Extra To-Do List To Ko Subscribe Ride Extra To-Do List To Ko Subscribe Ride Extra To-Do List To Ko Pure Marine Region Will Be A Your Husband So Normal Delivery Meanwhile Find Some Repeating Reminders And Vikram Shudra Between States Away After 10 Minutes Till December 2015 Subscribe Our Solution Will Start From Running Subscribe Now To The Number Of Units 5004 Subscribe Only In General English That Only White Susbscribe Must Subscribe Share That Electrolyte Will Give It 240 2345 Se Zameer And 9997221774 9764 Subscribe To The Boat Builder Lobby You Are not bothed about 10 minutes just they also want to keep it share it in for expansion of that will just need to keep track of the previous value level these emotions from zero do a text in order to calculate edit busy-busy One Adhere Subscribe Molu 44 Ki Jis Again For This Is Two Places For This Thank You The Quantum Of Vs Wave Day 1.10 Hai Quantum Of Vs Wave Day 1.10 Hai Quantum Of Vs Wave Day 1.10 Hai Tu Dil One Year Stree Nothing 4th Floor Ki Nau Using The Only Way Can Find The Greatest Number Of Paris Main To Late From also Rafi surplus of two different share this and then share let's that fluidic from Britain his team moment Sudhir for Indians that odd from being selected dictionary extra then this heroic website election minutes come subscribe and subscribe the I soft special net after this from Here to this will be completed by 5 wickets in logic same will be true for ific any to this show how many and true Interview Will Not Give Winners List to subscribe our Channel subscribe to be c2c Times - Wave 2K subscribe to be c2c Times - Wave 2K subscribe to be c2c Times - Wave 2K Ki And Avnish 200 Case Separately 120 B 420 Laxative This Let's Move Will Be One With Welcome To Two MP3 Love But Withdrawal Sau-Sau 1502 This Is it MP3 Love But Withdrawal Sau-Sau 1502 This Is it MP3 Love But Withdrawal Sau-Sau 1502 This Is it subscribe to just apna se sure decision ka lead savere from winning chal be similarly for this is that point sw0 case will and will right that in choose how to plus in all r rate cases will hide in churu to drops dislodge 21 clear and 12121 -1.2 subscribe and like subscribe 12121 -1.2 subscribe and like subscribe 12121 -1.2 subscribe and like subscribe for 00000000 Subscribe Hello Friends Idea Hai Vinod Singh Reminder Semester Value Day Pintu Ko Pic nd True Values and Traditions Ko Pic nd True Values and Traditions Ko Pic nd True Values and Traditions and Events Away After Which Still This is the Number of Units for One More Thing Will Be Different in Different Languages Subscribe Different in Different Languages Subscribe Different in Different Languages Subscribe Days In This Is A Like R 12th Model Over Five Minutes Ago How To Modify Which Does Not Take - To Modified How To Modify Which Does Not Take - To Modified How To Modify Which Does Not Take - To Modified Returns - 250 Negativity Turns Returns - 250 Negativity Turns Returns - 250 Negativity Turns Negative Inflation Spikes Term And Long Distance Between 0 And 435 Effective Negative And Positive Channels subscribe and model as positive a ki chutki mode once will be indore range effective indore range minus one two - then effective indore range minus one two - then effective indore range minus one two - then you get ots 90 to remote negative suid less positive energy can take lot 20 to take off but in the mid-day one Ansh Plus Will Make A Tree By Taking Molu And Adding Tweet Suicide Note Service Ki Gangotri Saiyan Tekchand Saini Rampal Ji Ka Safar Spirit In C Plus Sudhir Will A Need A Vector Of K Size Servi Only Place Value Subscribe Values In General Place Value Subscribe Values In General Place Value Subscribe Values In General Merge Values And Somewhere calculative Merge Values And Somewhere calculative Merge Values And Somewhere calculative rates like this one special also of ki and time will be one of account size ke slice 250 swami 20 at this time plus equal to ki x molu ki ke sweet molu and ne Twitter suid negative vikram positive pati fit body positive things Which Will Make You More Than 500 600 800 24 This Subscribe To Hai Next Ki Times Mein Invest Body Whatsapp Models Notification Plus 2 And You Will Find The Different Hai Kar Do Ki Sugar Tweets And A Ki In Multiple Advani And Minus One By Two All In This Case C Multiple Admin Which - Close That Divided By Two And Ise Medium Seervi Subscribe Now To That End Ubbut Special 40 To Hand Delete In Special Visit To St December Hai Main Surat Which You Have Any Size Ka 90989 Blood Slideshow Under Return Result That Electronic A Play List Which Pass So Let's Submit That And Solutions Accepted And Which Blesses That Angry Submitting Didn't Help Tomato Let's Try Ones More 29334 Increasing Time Now This Time Which Got It Too Better Than 98% And Were Happy That were pushed Got It Too Better Than 98% And Were Happy That were pushed Got It Too Better Than 98% And Were Happy That were pushed 20% 9 bluetooth setting in 20% 9 bluetooth setting in 20% 9 bluetooth setting in jobs in python don't thing and at this time when code word loot lo Ajay got a great site setting in java a nervous system in the country it's quite a few cents again open run time and work Nobel price setting infection minister in space and don't need this tomorrow morning in this also one in this will always return vitamin B heroine 's life minus one record of respective 's life minus one record of respective 's life minus one record of respective positive and negative blue have done in the flats pick Hai Jai Hind is requesting the division of the project will return 02019 you to change the best the independence is also accepted
|
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,449 |
hey everybody this is Larry I'm doing this problem as part of a contest so you're gonna watch me live as I go through my darts I'm coding they've been explanation near the end and for more context there'll be a link below on this actual screencast of the contest how did you do let me know you do hit the like button either subscribe button and here we go thank you for form largest in the drove of digits that add up to target so this one I knew right off the bat after waiting a little bit dad was just dynamic programming I could keep track of the max and genuinely speaking I would yeah it in a general sense you apply use a path reconstruction to keep track of the last digit that you use at each node and then go backwards to construct the path that you took yeah and that's what I was thinking about but I was like there's only five thousand digits Python digit Python is pretty fast let me just use pick int in Python numbers because there's only five thousand digits but it's you know it's only 500 integers so something like that so it's kind of risking it to be honest but I knew I was also right now at this moment pretty fast I was like that's let's give it a go and then you know that's risk it for maybe you know a good finish in terms of not doing the path we construction and just do it for it and store it on each node and that's pretty much all I needed to get started this is a relatively standard dynamic program form and the idea is that for the recursion is that for each target it is just a max of taking one each of those digits one of those digits and then adding it to the or subtracting it from the target do you matter how much were you which direction you go I guess but that's pretty much it yeah and I think I'm still a little bit thinking a little bit on whether this is fast enough at this point ah oh yeah but now this is actually pretty straightforward dynamic programming and honestly even though I got this in about eight minutes I should have gone faster even not in not counting the mistake that you'll see me do pretty soon yeah I was just it's been a while since I wrote this dynamic programming I guess so I saw a little bit slow but I really chef Cantus faster considering I didn't have to do powerful construction which everyone else probably did I was oh yeah I was here I was thinking whether there should be nine or ten and I was like I don't know but I was like yeah this disco doesn't really make sense but I mean I was still I was focused a lot on the recursion and not I mean for the most part to be honest so during this farm I'm just worried about the running time and that cost a penalty that you see and it was just a big lapse because it's not a hard thing and I think for me the biggest problem for this problem was the running time so I was like ok let's see how long it takes for the diverse case and this should be the worst case but well yeah and I think because of deaths I did not but just this is just so silly I should have gotten this yeah I counted to nine ones by one code so right now my focus was just on running time for some reason like for the reason that makes sense and then as soon as I looked at the answer I was like I only looked at the last and output and then I was like oh wait that is not right they're still not right clearly so definitely just wasn't practiced enough I think this is pretty straightforward for a lot of for someone who is practiced this should be a five-minute poem especially if I don't five-minute poem especially if I don't five-minute poem especially if I don't have to do the path week instruction but I think I've definitely watched it a little bit given if it doesn't seem like it and yeah and at this point I think the pending tests also kind of got me a little bit because it kind of threw me off and as soon as I saw the last answer I was like god that's good let me submit I was gonna do something about to check the length I was like yeah okay let's go that should be okay whatever let's just submit and then as soon as I hit I was like oh no wait I didn't look at the other answers and I was like oh what silly mistake I made a mistake yeah and that was like the first test case so like do you think really should have gone that one especially since yeah I would have been second in this contest so that's not that's terrible but it's really not clutch and I was like girl yeah you just it's just that for this one so what happened was that I didn't keep track of the fact that so basically I did what happened was that I did target or less than target instead of target strictly and that's the difference and also I think I didn't handle well I think I handled they're not reasonable but let's have a typo here a bit but that's pretty much the only thing is that I did that's it to dinner instead was focused exactly timing because I didn't keep track and that cost me you know from whatever from drop from second place to what you'll find out later at the end of the video because I don't think it's finished updating anyway but yeah the facts are watching I pretty much that's all i refresh I was like ah only one person finished so I actually had time for this and is still waiting pending so the system testing was also a little bit slow it double-checked also a little bit slow it double-checked also a little bit slow it double-checked hands at this time and that's it hang out the other Larry bye who q4 form largest in the job of digits that add up to target so I think the intended solution for this one to be honest is its dynamic programming with construction of with path reconstruction I did not do it that way I and that's why I was watching it I took a little bit of a gamble to save time but then I cuz I think that I worry most with the way I did it so basically what I took advantage of his that in Python these num numbers can go directly to big int or big numbers so that's what I did and because they could be at most five thousand digits so that's why I had that case where I had a test case where it was just everything is cost one and because I will and five thousand digits and because I was so fixated because I was so like worried about the running time dad I didn't look at the result I didn't look at the answer and I here I did this instead of that I think as a result and I or something like that I don't remember what I did but it was some really silly thing where yeah but the idea is that this is dynamic programming and the recursion is you know the cost of each digit so this is your cost target and then due to these cost you just go backwards counting what's the biggest number that you can get if you have to do pad construction I would have to do some tracking I'll have to check I would have to track which digit was to apply a digit that we added for this one and then we do a path reconstruction but I didn't have to do that because I well I was gambling a little bit on running time that's why I did what I did but then I watched it because I was just so excited about getting it or getting the running time to be fast enough that I submitted a little bit prematurely with fellow contestant as soon as I said me I'm like wait I didn't actually look at the test because I was so excited that you know when I saw the test I was like oh this is obvious and well like obvious that it was incorrect and also obvious to effect so I knew how to fix well I knew how to stop the bomb in general it's just that yeah it's just that I rushed it a bit so and because I was really thinking that I had a good chance of placing really highly so yeah that's all I have for this problem but yeah if you have trouble this is actually relatively straightforward in terms of dynamic programming the only tough part is the path can path reconstruction point and I urge that you just take a look at the path reconstruction at somewhere and you could you know figure out how to get the plyo digit one pigeon at a time and that's how you get it back and reconstruct
|
Form Largest Integer With Digits That Add up to Target
|
print-words-vertically
|
Given an array of integers `cost` and an integer `target`, return _the **maximum** integer you can paint under the following rules_:
* The cost of painting a digit `(i + 1)` is given by `cost[i]` (**0-indexed**).
* The total cost used must be equal to `target`.
* The integer does not have `0` digits.
Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return `"0 "`.
**Example 1:**
**Input:** cost = \[4,3,2,5,6,7,2,5,5\], target = 9
**Output:** "7772 "
**Explanation:** The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost( "7772 ") = 2\*3+ 3\*1 = 9. You could also paint "977 ", but "7772 " is the largest number.
**Digit cost**
1 -> 4
2 -> 3
3 -> 2
4 -> 5
5 -> 6
6 -> 7
7 -> 2
8 -> 5
9 -> 5
**Example 2:**
**Input:** cost = \[7,6,5,5,5,6,8,7,8\], target = 12
**Output:** "85 "
**Explanation:** The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost( "85 ") = 7 + 5 = 12.
**Example 3:**
**Input:** cost = \[2,4,6,2,4,6,4,4,4\], target = 5
**Output:** "0 "
**Explanation:** It is impossible to paint any integer with total cost equal to target.
**Constraints:**
* `cost.length == 9`
* `1 <= cost[i], target <= 5000`
|
Use the maximum length of words to determine the length of the returned answer. However, don't forget to remove trailing spaces.
|
Array,String,Simulation
|
Medium
| null |
1,903 |
hello guys my name is assalam welcome back to my channel and today we are going to solve a new lead code question that is largest odd number in a string so we will be solving this question with the help of Python and the question says you are given a string num representing a large integer written the largest varied odd integer as a string that is a non substring of num or an empty string if no odd integer exists a substring is a contigious subsequence a sequence of character within a string okay so just before starting solving this question guys do subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so that you can get the updates from the channel okay so let's begin and with example number one you will try to understand some concept of the question here that we have what we have to written actually so an example number one there is a number 52 it's an even number we all know that a number which ends up with 0 4 8 4 6 8 it's an even number and the question says that if there exist if this is an even number we have to check value plus value from it so this is the first value means this was the first value because we will be checking from the last so this will be first and in the reverse order we'll be checking this so this is first value this is second value so the first value is even number so we will uh move to Second and then it is an odd number so we will return that value because this is the largest value in this okay then we will move from here to here okay see this these are all even numbers so we will return an empty this thing so because 6 0 2 4 are all even so we will return this as an empty string moving on to example number three this is complete whole as an odd number because 7 is an odd number so if you have noticed this thing that uh in between 52 and this lower this number 3500 400 3000 30 427 that 52 is an even number and this is an odd number because this last this value is even this is an odd number so this if we compare the last digit we will convert this whole uh as a odd so we will be what we will be doing we will be checking the last index of these string okay see so it if this is an even if this isn't even we will move to the if that value it's an even we will check value just before that so the value just before that is 5 so we will return that value and if it is not even if it that value is not uh an odd we will check for the value before that and we will if that is also not then we will move to that and if all or not we will return an empty string so let's start solving this question so just before starting solving this question guys do subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so that you can get the updates from the channel okay so I will be creating my n variable here which will be my Len n minus 1. line number minus 1 which will be my n and I will be creating a loop here while and is greater than zero if int because this is a string here we need to convert this whole into uh num and this whole into uh integer so that we can apply a mod function here so we are saying that if it is an even number for if it is an odd number then what we have to do we will be returning a return num 0 to n plus 1 okay if it is an odd number then we will returning n plus 1 because n is len minus 1 so we will be indexing from 0 to n plus 1 okay then else we if it is not an even odd number then we will be saying that n is equals to n minus 1 okay so n is equals to n minus 1 we have written here now this it's created now one more thing I will be doing is that and if n is equals to 0. we haven't applied when n is equals to zero so we will again checking this that if it uh if it is an odd number or not instead when n is equals to 0 that value is odd or even if it is an odd int numb and uh mod 2 is not equal to zero then return num zero so if it is an odd number then return num 0 else return an empty string return this so let's run this code and check for an answer so I have put some okay so I have to put mod instead of five I haven't pressed the shift button so see it's working fine now and we have got our answer here so this was all in the question guys if you have any doubt ask in the comment section and I will try to sort it out thank you guys for watching the video and see you next time
|
Largest Odd Number in String
|
design-most-recently-used-queue
|
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** num = "52 "
**Output:** "5 "
**Explanation:** The only non-empty substrings are "5 ", "2 ", and "52 ". "5 " is the only odd number.
**Example 2:**
**Input:** num = "4206 "
**Output:** " "
**Explanation:** There are no odd numbers in "4206 ".
**Example 3:**
**Input:** num = "35427 "
**Output:** "35427 "
**Explanation:** "35427 " is already an odd number.
**Constraints:**
* `1 <= num.length <= 105`
* `num` only consists of digits and does not contain any leading zeros.
|
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and update it (i.e., O(sqrt(n)) per operation), and move this element to an empty chunk at the end.
|
Array,Hash Table,Stack,Design,Binary Indexed Tree,Ordered Set
|
Medium
|
146
|
1,291 |
hey everybody this is larry this is me going over day 19 of the leeco dairy challenge uh hit the like button hit the subscribe button join me on uh discord let me know what you think uh got a haircut uh i don't know just feel like people are vlogging or something right anyway uh sequential digits let's get to it uh a ninja is a secondary digits if each number is one more than the previous digit okay uh so i think for this one what i would recommend is just uh generate the entire list and then go for the entire list to see whether they're low or high uh within the lower high uh the reason why i can say that is that if each so i did a lot of back of the envelope or back of my head uh calculations uh maybe it's a little bit hand wavy right now um but for example if you are looking at three digits well and this isn't even correct but you can say that there are most nine or ten numbers within three digits right because uh because it can only start with one or two or three or four and actually obviously it's actually less than that because uh 789 is the biggest number uh because you can't do 8 nine and ten obviously because then there'll be more um so roughly speaking for each digit there'll be about ten numbers and for you know and you look at the constraints um and i was just thinking about ins in general but it can have most half and can at most have uh 10 digits or something like that right so that means that there are 10 numbers 10 digits um that will be 100 numbers so you could do a linear scan uh you can maybe even binary search if you really want to be fancy but for 100 numbers i would be too lazy to do it um but yeah but that's how i'm gonna start doing it um yeah and there are a couple of ways you can probably start doing to do the actual construction itself uh i think i'm just going to do a breakfast search type thing where i start with one digit and start from one to nine and then just keep on building to it so yeah um yeah okay basically i'm just gonna put everything in a set um yeah i hate using single wearable names for a set uh for anything but uh my numbers are all numbers maybe i don't know that's better naming things are hard you know but um but yeah so then maybe i'll do something like current is equal to a list of um let's see right x for x in range of one from one to nine inclusive so that's ten um and then that's pretty much then we just get started uh so then now i just do it for each digit you could do some math to kind of bound it but i'm not going to right now so that just looped this 11 times say uh because basically you probably do 10 times but i'm always like for stuff like this where you if you're just doing 10 extra operations i don't want to count uh off by ones and stuff like that right so i'm just doing 11. and you can even do 12 in the value okay because you don't overflow in this one um but yeah so all numbers uh for number and current uh or numbers dot append or dot add i guess because it's a set uh number and then now for each number in it we want to add um we want to add a new digit to it right if possible so we go for a number in or okay let's just do also oops next candidates let's go to new away let's call these uh current candidates so we can do that we add the current number and then the next candidate is just equal to the number uh let's say mod 10 right or well okay let me break that down a little bit i was gonna do it one line a bit um but last digit is equal to you know number mark 10 um if last digit plus one is less than or equal to nine uh and you could maybe do it the other way then next candidate dot append um number times 10 plus last digit plus one right uh and to show how to you know see for yourself why this works uh and basically we just take the last digit if we take the last digit and we add one to it which is you know literally what the problem statement is asking for uh it's less than nine um then we just do this thing where we shift it by one by ten um or multiply by 10 and then add that last digit plus one since we know that this would be from uh one to nine or whatever it is maybe not even one percent um yeah and then at the way and we said current candidates is equal to next candidates uh and then at the very end we can just do a simple count from between low and high right so then now we do return and maybe i would show off a one-liner one-liner one-liner um oh maybe does it count let's just do lan of x for x in or numbers if x is between low and high and that double check that six exclu inclusive uh okay it is inclusive so that should be pretty much all the things that i need to test uh oops oh some of these are string so i might have to maybe i don't know i have to take a look at the error message uh and also just test um one and ten to the nine so oh it starts at ten so it's three four three one two do anyway uh okay it's about to return a list of industries all right for some reason i thought i had to return um to count so that's my actually even use it well straightforward to what we had to do uh do we have to sort it uh i guess it doesn't say but it should be okay uh we don't have to in the right order uh i don't know if i need to sort it so i'm just going to sort it just in case because i mostly like i said it's going to be 100 numbers so i'm not going to worry too much about the performance of the sort um though it just depends on the statement um and of course you can also add things in a way such that um but this doesn't actually have to be a set right um because we know that we're not gonna repeat numbers so this could just be a list so you don't have to sort that way okay fine do it that way then um yeah so that looks good uh let's give it a nice submit and yay uh so yeah so the again to go over the complexity because well we know that mode is going to be 10 digits so let's say there's of 10 or one uh and then we just go through all the candidates and again each lev for each digit there are at most 10 candidates so this does at most 10 operations uh or it goes for 10 iterations of the for loop uh these are all one operations so yeah um depends how you want to count the digit shifting and stuff but for me i'm going to count this over one so that means that this is about or 10 times 10 or some or maybe another notation be all of the number of digits uh times 10 so of d um so yeah so and then we just go for this and again this is about all of the number of digits times 10 per digit or something like that right and technically beyond 10 it wouldn't even get higher so you want to help you want to talk about it but yeah uh yeah that's why i have this problem uh so definitely think about using this technique i think uh the queer uh i think you know it's probably natural to go do a folder from low to high uh but when you see these constraints it's very uh obvious that's gonna be too slow because uh a billion is too slow uh you wanna keep something in at most like a million ish maybe 10 million ish range uh depending on what you're doing and how much work you're doing um but yeah uh cool 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
|
Sequential Digits
|
immediate-food-delivery-i
|
An integer has _sequential digits_ if and only if each digit in the number is one more than the previous digit.
Return a **sorted** list of all the integers in the range `[low, high]` inclusive that have sequential digits.
**Example 1:**
**Input:** low = 100, high = 300
**Output:** \[123,234\]
**Example 2:**
**Input:** low = 1000, high = 13000
**Output:** \[1234,2345,3456,4567,5678,6789,12345\]
**Constraints:**
* `10 <= low <= high <= 10^9`
| null |
Database
|
Easy
| null |
94 |
um hello so today we are going to do this problem binary in order traversal which is part of this week's um this uh daily challenge litecoin daily challenge so we have a root of a binary tree and we want to return the inorder traversal in you know the traversal is just means the order from left to right so we have left first and then the root node um or the parent let's call it and then after that we process the right node and so if you take a look at the first example here the left side we go all the way to the left so the left side for one it's empty so we don't need to do anything and then we do one and then we want to traverse the right side and for the right side sub tree we start also with the left side so we have three so that's why we have one three and then we do the parent two um and there is no right child so we that's it for that tree um yeah so that's and if there is just one node we just return that node um yeah so that's pretty much it for this problem we can um we can solve it with dfs uh we just need to traverse the left first and then the root and then after that the right and collect everything into a list so pressure forward so what we need to do is first define our dfs function it takes a node and our base case needs to be if no node we want to return empty list and then we want to dfs first in order traversal means left and then the node itself and then the right side okay so the left's first since it's a list we need to concatenate so we add and then we add to the list the node so left and then the node itself we want the value and then the right side dfs on the right side okay and we write an empty list here so that the concatenation ends up working so let's say if the right side is an empty node we will add an empty list here which would make the addition work if we return something like none or zero that won't work because you can't concatenate it with a list right so that's why we start with the empty list and we can just return this and then we call our function with dfs under root and we return that so pretty straightforward um let's run it and we can submit yeah so that's pretty much it for this solution um let's just for the sake of like example say think okay what if it was pre-order of think okay what if it was pre-order of think okay what if it was pre-order of also so pre-order means also so pre-order means also so pre-order means um right left node first and then left right well in that case we can just put node value here instead right and do plus one plus uh what if it was post or the traversal which means left right and node well similar thing we could just have move this here as well right so yeah you can solve all kinds of reversals with dfs like this yeah so that's pretty much it for today's problem and yeah please like and subscribe and see you on the next one bye
|
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
|
93 |
hello guys my name is vishwas itan I hope you all are fine so let's solve today's lead code daily challenge restore IP address uh question says a valid IP address consists of attractive food integers subtited by a single Dot so each integer is between 0 and 255 okay and cannot have a leading zeros so it cannot have a leading zero for example 0.1.2.0201 and 9 19 to 192 and 0.1.2.0201 and 9 19 to 192 and 0.1.2.0201 and 9 19 to 192 and 1268.1.1 is a valid IP address 1268.1.1 is a valid IP address 1268.1.1 is a valid IP address but here 0.0 here the here it is a but here 0.0 here the here it is a but here 0.0 here the here it is a leading here this case 0 1 it is a leading zero here so we can't this is an invalid and for this case 312 is uh more than 255 that's the reason it is not valid here and here we do have a attribute so that's the reason it is not valid it should have only numbers integers okay let's solve this problem the problem given here is two five one and three five so this is it is given in the string so we have to find a valid IP address in for IP address it should consist of uh four integers which is updated by a DOT and okay so if the length can be up to 20 okay let's start this so we will use we will solve this by an approach of backtracking so first for this case we will take only single two and for the another we will take 2 5 and for this guy we will take 255 and another it is 250 5 and 2. in this case this all three are valid this is valid and this is valid but this is not valid why it is not valid because it has 252552 which exits the value given here 255 so that's the reason we will not use this guy we will use only that okay we do so we will not use this guy fully so same thing we have to do for this guy again so we have here start from 5 and it will be 55 and another one will be 52. 5 2 which yes this is not valid so we have to remove this and we keep on going there and we will when one case it will be in one case if you go five here and if we go again here five and if we take again here 2 which will have 5.52 but the string is here out of 11 so 5.52 but the string is here out of 11 so 5.52 but the string is here out of 11 so we have to fully fill the string so that's the reason we will not include this guy and for this case if you take here it like it will reach till here but it can't it will notice till full it will not cover full strength so then that's the race we will omit this and this was this is also same case we also amid this it will not go fully to the string so we have to go fully to the string to find the valid IP address so let's do for this guy now so two uh 255 here so again we will have 255 which is valid because it 255 included so it is a valid string here so we will go again here to 255 and here we have two cases which has one and another case we can take here has one and in this we have to take three five which will have which how many dots we have here one two three four so this is the valid uh IP address and we will have same thing for this guy one three five and this is one is also a valid IP address so remember these are two rules here so one is it should not uh it should not be more than 255 and another one is there's no leading zero so there's two rows and we have to follow the two rows I hope you got the question here let's solve the problem by coding so we are starting with the coding here so first what I have to do we have to have our input uh we have to have a answer where answer variable so we will create our answer variable which is that it's a string okay so we created a string here and we will name them as answer and the sign has an error list ready list done now what we have to do we have to check if the string length is more than 12 why we have to check if a string length is more than 12. the reason here is just in case if we have a maximum value just say here we have here uh wait now we have a 12 here 2 5 we have a point here we have a 2 5 another point two five in this case this is a maximum IP address we can get and what is the length of this one two three four five six seven eight nine ten eleven twelve this is the maximum IP address we can get from this string why this is maximum because in here the maximum element is 255 and we will have a maximum of four integers that's the reason what is the length here if there is a if is any number here more than if we have a seven year also this IP address will be invalid that's the reason we have to take at most it will have a 12. so uh like uh it should have at right at most well if it goes more than 12 it will be an invalid IP address so we have to return a empty string so I hope I am clear here so if the length of a string is more than 12. then do one thing just return the answer which is an empty I hope I am clear here so now what we have to do we have to have a temporary string so we will create a temporary string and we will use that to put into the backtracking so temp will be equal to a empty string we created an interesting now what we have to do we have to take help of a back strength uh backtracking element so we will name them as a pack for simple case and first we will put a string here I will minimize this guy and I don't need this guy now okay no this is not happy with it so again now so STM now what we have to take here another string which is temp and we have to take a indexed so we are using backtracking obvious we have to use index which will start from zero and another case here they told we have to have maximum four dots uh there will be a maximum photos here is the adjective four integer separated by a single dot so obviously it will say a four dot here so we will have a DOT also and we will have a answer also I hope I'm clear and I will return here answer okay and now we will create a back uh back tracking uh this one function for that we will use verbally avoid why void because we don't want to return anything we just want to manipulate the value okay so the function name is back and first variable is a string I will name the message string and another variable is attempt and another is an INT which is index and another is a another is Dot and another one is um list answer ing answer okay we created it now what we have to check if it is invalid if it is unvalid uh if it is an valid IP address then what we have to do we have to add it to the index let's so we have to add it to the answer here if here what I have to see if Dot is equal to Capital dot is equal to 4. so it should have maximum 4 here and the length should be equal here I am mentioned here the length should be equal then only it isn't valid so what we will do we will check if index is equal to the length of the string here as not length the method we will use here okay then only we will add to the answer so what we will add here we will add a temp but here what they are what did what they did here is one point here is another one point here but at last they don't have any point so we have to remove that point we will use here a substring here a function called a substring we start from 0 and end still temp Dot length minus 1 which ends at the one before n minus 1. so we will omit that last doubt here there is no mention of a last dot we will have to omit the last dot okay we did it here now what we have to check if the dot is more than 4 if so we are using backtracking so it will be more than four and also we have to return this guy we have to return this we don't need to do after this if the DOT is more than 4 then what we have to do here we have to return we don't need to go further just return it's already an invalid IP address now we have to use a recursive backtrack we will use requesting again for backtracking so here four end will start from index and the main point here so it should be it should have only three here so what we will do here we have to find a minimum if the length is here minimum so here in this case it has real but if uh if you consider this one it has only two now here it is history we have to consider a minimum value so what we will do here I less than so V1 only 3 here so 3 plus index or so I have to use max minimum Max minimum yeah and I have to see the which one is minimum if s length is minimum will be considered excellent so s dot length this one okay so it should have a maximum about three value uh let's see if we are here let's assume one two three four five six seven eight nine so nine plus three it can have this much only or here this length of using in this case the length of the string is lower so that's why it will take consider for the length here I hope I'm clear here so now what we have to do we have to this bracket is a headache this is finished okay I plus okay we have closed it here we will find it's okay now what we have to check if the dot um first we have to check if the uh like here uh here the number is 255 it should be less than 255 to use to go to the back tracking so first we will check if the three variable is less than backtracking so what we will use here if condition if integer okay we will use a function called pair face int okay we'll use this and we will start from Subway we will start from this substring string not an array we will start from a substring from where till where we have to start here so we have to start it from here index comma till how much I plus 1 here I Plus 1 okay we have to start from index till I plus 1 so we will have a variable here and it should be it uh it should be a should be less than 256 or equal to 255. okay we have reached we have uh took we have taken control of uh one condition here I think so we have to do a test guide here okay a bracket okay now what we have to do here we have to use an N operator why we are using n operator here in this case we have 0 1 we don't want zero one this is an invalid so for that reason what I will use if I is equal to index then okay or to make it valid the x dot character at index should be not equal to zero I hope I am clear here it should not be equal to 0 now we will enter the loop so back will have now as now here the time will be changing to um stamp Plus from where to where it will change we will use sub we will use a substring from Battle well from index till I plus 1 okay here also we took here variable I plus 1 okay from index comma I plus one and what after that what we have to add a DOT so Plus we have to add a Dot I hope I'm clear we have manipulated the temp here now what is the next value which is index 2. now index will be how much index will be I plus 1 so we have to go forward after that the dot will be increased so dot plus 1 okay and last one is ask Ed I hope I'm clear here let's run it if there's a mirror maybe yeah we do have error substring oh I didn't mention any guy so it will be as Dot okay see yeah it is getting accepted so let's submit and see and we will do a dry run for this problem no need to worry we'll do a try turn it's getting accepted day 21 completed we copy this guy we will copy this guy and do one thing I have made already a uh this one so we will go here we will paste it here and I have to make this static uh why this is uh this is main static so we have to make I don't want to make object that's why I'm making static so now what I will do I will return here the uh sot to make this we will return this guy and okay so in every case you will return here we will add 2 here and what else I should return I will return temp also this guy right I start from here till here okay um okay let's run this and I will have some of this one also for more clearity sod a okay we copy this guy and paste here also so we will run this so here I should have mentioned I don't know also right I should have mentioned that also so let's do that also now so we will do here um we will do here uh add and here damn okay now we will run this now it will be more clear okay so this is a very long thing this will take two raised to three I think so it will be 3 raised to n so we have three variables okay so temp two here the time will have first two then 2.5 then time will have first two then 2.5 then time will have first two then 2.5 then 2.55 then 2.55.2 here in this case it is 2.55 then 2.55.2 here in this case it is 2.55 then 2.55.2 here in this case it is not fully completed so it will be omitted now again we will be going here and it will be going here it will create again here so till now we didn't find any variable which will be which will satisfy this condition this is satisfied easily but this is not certified easily so it will keep on going there till it find a satisfied Einstein answer here I think so he will find it will yeah and I know it's a very long code okay so it got added at here where he found 255.255.11.315 and here also he got uh 255.255.11.315 and here also he got uh 255.255.11.315 and here also he got uh it will get oh it got added and it now will be it will be removed now it will put only three here it is not valid because it is not complete and again it will be 3.5 it is not valid yeah it will be 3.5 it is not valid yeah it will be 3.5 it is not valid yeah it will come to uh to light this guy and this is an valid uh string so that they get it get added and it is a finishing this is the last screen and will remove last dot here and we will print out this I hope this is clear it is fully Diagon and it will be at last we can we will get this substrate okay I hope you like this video if you do like please uh press the like button and also comment and if you didn't understand any single line of this code please do come and comment I will try to help you and bye thank you for watching bye have a nice day
|
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 `"[email protected] "` 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
|
46 |
hello and welcome back to the cracking fan YouTube channel today we're going to be solving Elite code problem number 46 permutations given an array of nums of distinct integers return all the possible permutations you can return the answer in any order so let's now look at our example one two three and remember that permutations are just the ways that we can rearrange these numbers um using you know the numbers that we have available so the easiest permutation we can make is actually to do nothing right which is just the original input which is going to be one two three so if we fix this one what other permutation could we make well we can swap the two and the three so we could also get one three two and what if we now put the two first well we could have two one three and then we could also swap the one and the three to get another distinct permutation two three one now if we have the three first we could do three one two and then we could also swap the one and the two and we would get uh three two one so these are going to be all of our uh permutations that we can actually build here now what we want to do here is like you saw we basically put one of the numbers at the front swapped it with whatever is at the current front and then we can just swap around the elements um in here right it's essentially what we've done right we've fixed one element in the beginning ensuring that it's Unique each time and then we simply just swap the other elements for as many elements as there are right so there's two elements here so that way we had to do two swaps and that's the general intuition behind the algorithm you want to fix one of the elements at the front and then just swap the other ones and then obviously you need to change which one gets fixed at the front to generate all the permutations and the way that we're actually going to do this is using the backtracking formula because that way we can fully explore all the ones then swap the two and then do the twos and then do the threes and this is a perfect backtracking formula so let's now actually go to the code editor and type this up you'll see that it's going to follow a very familiar pattern for backtracking and it's very similar to how we would do the combinations problem which is I guess the cousin of this one except now you're doing permutations and it's slightly different but the algorithm is essentially the same so let's go to the code editor and type it up so we're back in the code editor let's type this up the first thing we want to do is actually Define our output results so we're going to say res it's just going to be an empty list oops and now what we want to do is we want to essentially Define our backtracking function which is going to perform uh the logic here so let's say def backtrack and this is going to take basically our current index position so we know which one we're at so we can basically swap things accordingly so we're going to say Cur index and this is going to start at zero so we take our current next and what we're going to do now is if the current index actually equals to the length of nums then we know that we've actually exhausted all of the numbers um because we'll be moving our current index to indicate which number we need to swap right so say we have like one two three if the current index is at pointing at the two that means that we need to swap the 2 with the front so that way the two will now be fixed and then we need to swap the one and the three around similarly when the index points at three that's the one that needs to get fixed at the front and then we're simply going to um you know move the other ones around so what we want to do is uh if we've actually exhausted the entire list then we need to basically just um you know add it to our solution so we're going to say uh res the append so we're actually going to be moving things around in nums so we're just going to make a copy of nums right um so we're just going to you know take all the numbers from nums from the beginning to the end and then we're good to go so we're just basically going to make a copy of it and add it to our result all right now what we want to do is uh remember that we need to go through um from left to right from basically current index to the end and then make all those swaps so we're going to say 4i in range from the current index to whatever the length of nums is we want to swap some things around so we're going to say nums of our current index and we want to swap it with whatever nums of I is right so we're going to be swapping the current index with the other indexes um so that way we can fix current index at the front and then we're good to go so uh we're going to say nums of first nums of I is going to equal to nums of I and nums of first right so these will basically just swap the values at the current and not first sorry uh current index um we'll basically be swapping what are the values at current index and I um so that way we can rotate things around and basically generate the permutation now that we move things around we need to call our backtrack function and remember we need to move our current index up by one and once that runs it will go to completion uh at which point actually we can return here um and then what we want to do is undo the swap that we did right so we just need to undo it because when you do backtracking typically you make some sort of change to the you know the order you fully explore that path with the change and then you undo it so that way the next one will have its orders messed up so we're going to say nums of the current index so we basically just want to undo the swap so we're just going to do the exact Swap and this will undo it right so nums of I and nums of the current Index right and that's really all you need to do for the backtracking function um we just want to call backtrack and obviously we're going to be starting at the zeroth index because that's the beginning of our nums and we will call backtrack at the end of which all we want to do is simply return our results so let's just make sure we haven't made any silly syntax mistakes here and run this and looks good to go so let us submit this and accept it so cool uh now that we see that it works let us now think about the time and space complexity here so obviously we need to generate all of the permutations and for each of the permutations remember that we need to basically make a copy of whatever the current ordering of nums is because that kind of represents um you know the current state of the permutation right we're going to be modifying uh nums moving it around uh and then when we get to this stage where we actually need to add it to our result copying that we know that it's going to take Big O of n time to copy it and how many times are we going to have to make the copy well it's going to be however many permutations there are and if you remember the permutations formula which is like n p k right so you have n items and you want to permute it in K ways um basically if you remember the formula for math if you don't worry it's actually n factorial uh divided by um n minus K factorial so that is going to be your overall time complexity the Big O of n is actually you know adding your result here because you need to make a copy and this is the number of permutations that you're going to generate so um let's see for the space complexity we basically just need to store uh the elements right so how many results elements are we going to be storing well it's going to be the number of permutations so again that's n factorial over uh n minus K factorial which is basically just our factorial formula here right where n is the number of elements in nums and K is actually the size of um you know however many uh how large you want the permutation to be so there you go um that is the time and space complexity uh of this algorithm hopefully that makes sense and you guys can see how the backtracking formula is I mean it's really this simple uh template here right you basically just iterating forward through your numbers that you want to backtrack over um you do some sort of operation then call backtrack and then undo that operation so then you can continue so very common um template here for backtracking and yeah hopefully that makes sense anyway I'm gonna stop rambling if you enjoy the video please leave a like and a comment really helps me out the YouTube algorithm if you want to see more content like this subscribe to the channel if you want to join a Discord Community where we talk about all things Fang then I'll leave a link in the description below otherwise I hope to see you in the next video bye
|
Permutations
|
permutations
|
Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** \[\[0,1\],\[1,0\]\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= nums.length <= 6`
* `-10 <= nums[i] <= 10`
* All the integers of `nums` are **unique**.
| null |
Array,Backtracking
|
Medium
|
31,47,60,77
|
264 |
hey everybody this is Larry this is the fourth day of the July litko daily challenge it's like button hit the subscribe button join a disco let me know what you think I'm gonna go into the explanation right now and then afterwards you could see me attack this farm life but they say I agree numbers - you're given three prime agree numbers - you're given three prime agree numbers - you're given three prime numbers and you're trying to find the cave number that is there was a book by a combination of those three numbers right and in a sort of the way that I would think about it's just blowing up from you know one by one way and the way that I would think about is now you have you know three cues you start with one on each of those three cubes and then you slowly with a skewed EQ from that number you go okay let's say you have the number one well now you know that from number one that 2 3 & 5 know that from number one that 2 3 & 5 know that from number one that 2 3 & 5 are agree numbers because by definition 2 & 5 definition 2 & 5 definition 2 & 5 you know goes off that and then well next more in them the next smallest ugly number then in that case is 2 right and then to you go okay Stu is an angry number the next ugly number or the next possible agree numbers next add the two will be 4 6 and 10 and then the next number after that will be 3 and then to where you go okay 3 is an ugly number so the next up and the ugly number possible is 6 9 and 15 why does this work well the way that this work is just it tries to build 1 prime factor at a time meaning that you know if you have 3 you know it's ok to do 2 times 2 then that keeps the invariant and the invariant is always something that I talk about in my stream the invariant is that every number that we process our every number that we process is an ugly number and from an ugly number we can generate more additional ugly numbers the only thing that's a little bit tricky about it is that well you have to constraint or you have to construct them in increasing order because if you don't then you may miss one where like if you did the three before the - well then maybe three before the - well then maybe three before the - well then maybe you're gonna miss four and then you know miss 12 or something like that wait and there's a lot of you know so it makes sense to kind of keep them in a sorted order and as I got a X to my explanation of visualization I go from left to right from small to higher sway and so then the Train of darts should be done okay I need a data structure that allows me to get the smallest number every time and then there's one additional problem the initial problem is that well the number six right for example it is two times three so you could go from two and then three or you could go home to worry and then two but if you have if you do in a naive way and you put it you know if you try to processor twice then you may get the wrong answer if you processor twice so we kind of put them putting all these things that we said together the thing that allow us to keep on getting the minimum element of some container or some container that let's just keep on getting the minimum element well a priority queue or a heap will do that for us and then make sure that we don't put the same thing in to the party queue multiple time we would just use a set in that and actually I think you can that's the way that I implement it but I think in certain so this is in pipeline of course I think in C++ you could use of course I think in C++ you could use of course I think in C++ you could use something like a set to get the smallest number and also possibly of binaries oh sorry a balanced binary search tree where do you know make sure that everything you add is unique so there are other options used whenever is familiar with you but the point that I want to make is when you solve a problem you don't start with a static or the way that I don't I do it is I don't necessarily solve the data structure in my I keep on trying to find myself to ask the why do a better question a question that I could rephrase and I keep on rephrasing make an observation and then I ask myself well yeah I'm like okay what do I know that fits these criteria all right and for me like I said I'm trying to find the main element every time with no duplicates right imp I find it that could be part EQ and an asset in C++ it could be part EQ and an asset in C++ it could be part EQ and an asset in C++ it may just be you know asset and other languages may have you know different variants and that will affect how you implement your code but still the idea is that you know if you have a perfect half-track data type then you perfect half-track data type then you perfect half-track data type then you could just plug it in right and yeah and that's what I have for this problem in terms of explanation I'm gonna go over the code right now so as I said in Python I did it with priority queues as I said up to particu I set up the set of things that we've seen as I mentioned I start up by pushing and revving up one it's just an identity from what vacation right so then now every time I make a loop I take the thing off the top I pop it and them instead I have one number off the list and if it's if all the numbers are done then we but then we're done and we could be turned to current X otherwise for the current number we just multiply by 2 3 and 5 and if we haven't seen it already we put it in the heap and then we market us dad we don't want to add it into the hip again in the future so this is also something that you know we make sure that everything will be under in the heap at most once yeah in terms of complexity you could ask yourself well because each number that's on the list can only create three additional numbers and so when n is at most seventeen hundred ish then at most I'll be five thousand ish numbers on the in the list so that's how I come up with o n is equal to about mom just o n I make this claim as later we're usually in complexity theory or complexity analysis or whatever n is actually the input size so even with and in this case the input size is the number of bits which is you know don't eat 2 bits for normal end say and that means that given if this was control of n it's not linear in the size of the input so just one really pedantic about it because it might be something that you've thought about and then now because at most each number is gonna be in the party queue once because we made sure of it by having a sinner weigh them instead each number will only be processed one so we have all of n numbers to be processed and for each number we make a heap query we make a hip hop we may make up to three he pushes and we do some look-up three he pushes and we do some look-up three he pushes and we do some look-up on a hash table which you know depending on your language and stuff or your present to implementation preference let's say it's you know one way so each number we'll do our vlog and work and together that means that you know the number of things we need to process itself and each processed item takes o of n well of log and so together it takes all and again and then in space is large easier to analyze which is that you know well we're set so of and space rather heap that goes up to all and numbers so also over n space so yeah so now we have an O of n log N and O and algorithm again this is n in terms of the input parameter not to be confused of the input size okay but yeah but although this is a bit of a tricky problem if you have never seen it before because it's a little bit mathy but once you've done it and you play around with it I think it should be okay I think they're observations that I've made already over to with going from smallest to hires and then also just you know from each number multiplying by two three and five I want you to do it you probably okay at it but you know try to get it as much understanding as you can get oh yeah but it comes up here in there but I'm all kind of it I'm not a fan of it but you know it comes up okay that's all I have for this prompts and explanation stay tuned for the live portion or by coding portion right about now hey everybody this is Larry this is the live portion of the video on the 4th day of July the code le just let me know what you think I agree number two write a program to find an ugly number I'll be numbers are the positive numbers Cruz factors only include two three and five okay and n is less than 1690 okay so yeah so the idea behind this one is just using so if there are more numbers ten three numbers you would use something like a party cube but I think for now we can actually just use a regular two and not it you could do it as a sort of an implicit cube you will but you could still do a particular okay maybe I will yeah maybe I would do a priority to you just to kind of do how to do it let's think about how we'll do a good party queue but that basic idea is that you start with one and then for every number you times two three or five and then you just put the next numbers in the priority queue yeah and that's pretty much it yeah and I think that's pretty much it I think this is a technique that I learned a long time ago so I don't know if it's well known per se but it's definitely something that people - mm-hmm something that people - mm-hmm something that people - mm-hmm but yeah okay let's get started odd let's just go PQ is you gonna this is Python is a little bit weird quality Q syntax and it's a min kyu or min priority queue aside but yeah so then now we just may start with one now language here is greater than zero well that will always be greater than 0 and greater than zero of everyone that we probably minus one and then we just let's build a number of sets well let's blow is setup numbers we've seen and now we just do four let's cry mote multiplier maybe in two three five now I have to get the number so let's get X is equal to PQ of zero I'll pick you time pop PQ and then now we just well we see if the next number is equal to x X and then if next number is not insane then we just put in the heap and we also sexiness because we set tunics the scene to be seen and that's pretty much it and then at the way and I think if we could do it in a number of ways but if n is equal to zero then we return X I always may be a little bit off by one depend on how they define the first number and so forth oh yeah oh my don't wait I think I said what I was saying aloud but yeah keep you I always forget it little bit okay so let's try well let's try that last number I suppose and just numbers in between is there a wider number let's see it's not too big no let me guess okay one of them is not rounded I suppose it's a single one just wanted to make sure okay positive numbers okay yeah it looks pretty good timing looks pretty okay so that's submit cool uh yeah and there you have it so what is the UM where's the complexity of this way that's a little bit tricky to do what is - where's the bit tricky to do what is - where's the bit tricky to do what is - where's the last number anyone actually didn't notice but you could actually look at it as a sort of dynamic programming of sorts by going from left to right but I just using hip queue this numbers pretty big actually but at any given time each number that you relax we'll only have were only insert up to three numbers so that means if your n is up to 1,700 then you only go up to this you 1,700 then you only go up to this you 1,700 then you only go up to this you know the number of items in the set or in the heap in this case will only go up to 5,000 or give or take right I mean we to 5,000 or give or take right I mean we to 5,000 or give or take right I mean we could play around just put it out actually now PQ o so this is there until my computers a little bit slow but yeah so that the time complexity will be roughly three times n because we only relax three times n numbers or we create three times a number sonic thing so it'll be three times n so we hold and again I'm a little bit pedantic about these things so that usually when people say n even though the N in this case is the input of the method and in common terminology and complexity theory or whatever it's all usually input size and in this case the input size is actually the number of bits which is well in this case like 32 whatever way to eat 2 bits or even less than that I guess we want to squeeze it and but my point still is dead so in theory it is not linear it is o N and that is o of small N in their input but it's not linear just want to be clear because some people get caught up in that sometimes I put this inside the loop that's why I was taking away let's put it right before we return this is just for illustration but in terms of space for the same reason because we only look at each number once oh sorry I forgot about the heap point so it'll be all of so the number of numbers that we process let's actually break it down because I think I was just a little bit sloppy in saying it you know I because I was trying to get to the pit size portion but yeah so let's say this one there's o and num number is to be processed where n is 2 input not input size and again we said it someone like 3 times n and then for each one will take about log of 3 n which is about log of n right so log of n o of log of n anyway per number processed so the total running time would be O of n log N and again just to be clear and it's not two input size it is the number that is the input variable okay yeah so it's actually huh so it's actually way smaller than that even because of the number of yeah so my really pessimistic numbers is that it doesn't even match up but so it was really fast but that's my back of the envelope went up in that just three times and I mean I knew that there would be you know overlaps but just for the Big O I just want to be pessimistic and talking about it and your worst case is 5,000 and it doesn't really matter how 5,000 and it doesn't really matter how 5,000 and it doesn't really matter how much smaller it is in terms of space like we put each number in the set once and each number in the heap once so that'll be all of O n for this n again that the input size is the input parameter so yeah so that's the running time and the space complexity and this comes up I would say roughly once in a while for competitive programming this kind of philosophy but it's not a thing and I think for individual it'll bit awkward because it requires a little bit of knowing mathematical algorithms which yeah you could debate where the bar is that it's not something that would necessarily play around with because it deals with all these things but once you get the idea once then maybe we'll be doing without necessarily knowing order how this works which I hope that I explained earlier in the preview version but yeah that's all I have for today and that's why I have for this problem let me know what you think let me know what your questions are and I will see y'all tomorrow
|
Ugly Number II
|
ugly-number-ii
|
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`.
Given an integer `n`, return _the_ `nth` _**ugly number**_.
**Example 1:**
**Input:** n = 10
**Output:** 12
**Explanation:** \[1, 2, 3, 4, 5, 6, 8, 9, 10, 12\] is the sequence of the first 10 ugly numbers.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
**Constraints:**
* `1 <= n <= 1690`
|
The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
|
Hash Table,Math,Dynamic Programming,Heap (Priority Queue)
|
Medium
|
23,204,263,279,313,1307
|
148 |
Hi riven welcome back tu turn off in this video c r covering a problem statement from lead gold which is salt linked list un so in this question we have given the head node of our single digit list and we have to salt it linklies meaning sorting So we have to sort in kismelon. We have to sort in sending order. Okay, so this is our problem statement, so let's see how we will approach it, so we will do it technically. Okay, so basically what is my sort? What is our approach? What will we do in our lincol? Okay, and we will keep it as our face that the function from the record will solve our right and bring the left list by sorting it and here by calling both our sorted link list functions, we will get these links. I will sort the list so let's see how we will do it. Okay, so this is my handmade and this is my link lace. One, I have to get the middle out of it, so first of all, the road in ours will be there, this will be my note and my new head. What will happen next? Okay, I have to break the link from here to the middle and then what will I do from here, I will divide my link list into two parts, one will be my left question and one will be my right question. If it comes, I will leave the question. How will it be 6 4116 and 4, okay, there will be a call to the left, so from here, what will happen to me, again I will calculate the middle in my link list and my new head will be the next, okay from here, then I will calculate the next to whatever my meet will be. I will do it, I will tap it and from here it will be English, again what will happen is that six will go to a different mode and my four will go to a different mode. Now see like what will be our link list, in which there will be only one note in our link list. If present then one note is automatically sorted so what will I return from here six will return note 6 and from here again this will come to the right then what will be my return to the right will be 410 okay and when I come here in date So see what I have kept, from the beginning to the middle and from the neck of the meat, if we sort it, then it is 600, it is 440, then here I will call my meat, you short it, then what will it return from here four and six. Okay, now I will make my I for whom chalangi for right, then my four and six, and how much will be mine on the right, 1 and 8 note will go on my right side, I will say this, I am on the right side. So this meter will remain a van and new head will remain. When I come, what will I do? I have to tap my friend's next and what I have to do is I will make two calls from here, one left question will be solved and from here my right question will be solved. Now what from here? I see that my van is automatically sorted and 8, my van by itself, will come in the answer and my link from the right will come in it. Okay, now see, I have kept a phase in this, the left out will be sorted to the right automatically. If both are short, then here I will call you sorted as per my wish, then Van and 8, from here I will return my list, so in this condition, did I put you, the left position will be short on my own and the right position will be short. My position has become a bit short, so this is my left question has become short and this is my right question has become short, so here I am, if I call it again in my English, then van and this will be my four and here after four, my 6 will come, after 6 my at will come, okay this is my left question, which was the left of English, it has become short, now what will we do, will we call on our right, how will you become mine on the right, the next note of 911 and 7 will be on the right, ours. The mid will be short, my turn will be there and the note will remain in the new head and I will make the next of my mid's and then again I will send my left and right here for sort. You and nine are okay and when I am here pahunchungi aisa what is my list there is a single note left in it so from here I will return my tu and from here I will return my line note see this is the left question right question will call the shortcut so this is my tu and nine Will merge and bring it, okay now from here, what was mine, if it was the right one, then how will the right one go to me, where will it go to van and seven, then how much will be my mid here, 11 and new head, what will be my seven and then from here I will go to the next of mid. What will I do, I will tap it and then how will my note go? 11 This will automatically be sorted by auto 7. Then from here, what is both the lists? 11 There is only one item, it will be sorted. 7 From here I will return 7 and from here I will return 11. Okay in this question my left question is right question in short so from here I will call sorting so from here it will return 7 and 11. Look here is the left question short for this one. I went and the right question got short, so here I will call Mars tu sorted again, how will it become nine, sorry, you are seven and nine 11. Okay, so watch the live question from here, I already had a right question too. It is short, now I will call Mult2 here again, then van ke mein tu note will be placed next to you, which of my notes will be placed next to four, six will be placed next to six, 7 mode will be placed next to six and my eight will be placed next to seven. Note will be placed and next to 8 there will also be nine node and so what has become of my list, it has been sorted in the sending order, so this was the elbow of my short, like this, if we talk about the time and space complexity of the die. The one that remains short is I, its time complexity is my n log and the space complexity is of one. Ok, this is how we will analyze the time complexity. Some equations will be formed and this will be my n mid time for calculation. It will take time and my tu t and by tu because I am calling two sequences, one on my left and one on the right and plus n my type will take time. It will take time to list both of my sorted, so this difference lesson should be something like this. It will be 2n + 2tn by you. If we this. It will be 2n + 2tn by you. If we this. It will be 2n + 2tn by you. If we solve this then this is our time complexity. Let's type something. If you want to understand this time complexity and this analysis in depth then please tell in the comment section. I will make a separate video for this and its time. I have liked the complexity and space complexity, so let us code it. First of all, what will we need, we will need a function, it is explained in the previous video, so you can see from there, but I will write it once for here, okay. This is so that you people do not have much confusion. Head = N. not have much confusion. Head = N. not have much confusion. Head = N. My head's next note equals tu equal tu n. If I find it, how will I return it? Advise my head, what do I have to do, I have to get 2 points. I made this video of my note. I have explained to you that we will point to the first point head and the second point, what will be the fast, that too my head, someone will find it, Inshallah, then Wille my fast dot next equals next, you will take me to the next and will go to the next of fast. And when I come out from here, what will I return, so my function from here is that I have calculated the meet, so from here I will return my list van, in respect to whom will I return. If this is not my case then what will I do, I will make my own note, what will be the dummy, it will remain for reference, the dummy is okay, so what do I do from here, now I am serious, that is, I have to merge it, the gift value to the younger one is mine. Which is smaller in value then whom will I attach you next to my previous one? I will attach my C1 and move C1 next to C1. If it is not so then in that case I will attach my C2 next to the previous one. What will I put next to the previous one, you will put this note and I will put C2 next to C2, okay and then from here onwards I always take the point next to the previous one because each and every value is in the list as per my wish. When I come out of here, I will be in the next of my previous ones because what can happen here, any of the two can have air break anyway, so what will happen to me here which is not equal, you respect vice and from here Who will I return to? How will I call my from here? The next point was the calculator. Okay, and I am tapping my meet 's next. This is 's next. This is 's next. This is important to do because I have to break the list into two questions. Okay, so from here I What were you doing with your list Note L You mean whom will I return from here, before returning it from here, I will call the sorting function, what will it do with my list and I will return it after sorting it and if my Out of the two, what condition did I tell you, if I have two heads, they are equals, you are null or my head is next, in that case, I will return it to someone and then I will return my ad note. Okay, so this is my shot function. Done, if we look at my meet function, then meet function is, if there will be a note or there will be no notification and my sorry, I will move my fast point to the next fast point, I am moving both the points one by one, so this What is happening to me, it is not being calculated, both my pointers will become null at the same time, so I have done two steps, otherwise in this case, it must have been mine, maybe let's see, accepted submit and thanks for watching video.
|
Sort List
|
sort-list
|
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_.
**Example 1:**
**Input:** head = \[4,2,1,3\]
**Output:** \[1,2,3,4\]
**Example 2:**
**Input:** head = \[-1,5,3,4,0\]
**Output:** \[-1,0,3,4,5\]
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 5 * 104]`.
* `-105 <= Node.val <= 105`
**Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
| null |
Linked List,Two Pointers,Divide and Conquer,Sorting,Merge Sort
|
Medium
|
21,75,147,1992
|
1,814 |
hey how's it going leite code 1814 count nice pairs in an array you're given an array nums that consists of non- array nums that consists of non- array nums that consists of non- negative integers let us Define rev X as the reverse of the non- negative integer the reverse of the non- negative integer the reverse of the non- negative integer X for example rev 1 2 3 is 3 2 1 rev 1 120 is 2 1 a pair of indices I comma J is nice if it satisfies all of the following conditions 0 is less than or equal to I is less than J is less than nums plus length nums plus I plus rev nums of J equals nums of J plus rev nums of I return the number of nice pairs of indices since the number can be too large return at modulo 10 to the 9th + large return at modulo 10 to the 9th + large return at modulo 10 to the 9th + 7 okay so let us set up the modulo first 10 9th + 7 now we got to generate 10 9th + 7 now we got to generate 10 9th + 7 now we got to generate the reverses so we're going to say uh reverse equals I for I in nums and then uh we're going to have to convert it to a string and we're going to have to reverse it and then we're going to have to turn it back into a string um here I'll show you what that looks like uh print rev and then uh return zero so it doesn't give us an error um I'm still not used to the Run button being moved okay so you see we had uh 42 now we have 24 we had 11 well that's 11 and 97 becomes 79 uh then we just need to convert that back to an integer and there we go so now full disclaimer I did look at this problem for a few minutes before I began so I'm not as brilliant as it might appear but let's start off by implementing this naively um length nums and then i+ length or i+ one excuse me two then i+ length or i+ one excuse me two then i+ length or i+ one excuse me two length nums um probably the first thing you should notice is that this is symmetrical called the only thing that this condition is doing is saying that you shouldn't count things twice so oh there can be more than one can't there oh I wasn't thinking of that all right okay we're gonna have to use a counter but that's fine um all right let's take a look here so for I in range length not we're going to say if nums of I plus reverse of J equals and then it's basically the same thing but it's just uh nums of J reverse of I um if that's the case then we're going to have some counter t equal 0 I mean how big could it possibly be 10 5th * 10 5 um 10 to the 5th time 10 to the 5th minus one that's not even that big is it just is it bigger than uh okay that's why they want the modulo is so that it doesn't overflow uh there's no reason that we can't do this as a final step though it's not like gonna like blow up or anything okay um uh then we're just going to increment this by one plus I don't know why I'm having trouble pressing equals but whatever all right run all right now when I was looking at this before I got this far and then it's like okay now what how do you simplify this on actually uh this is the trick that I came up with combine just little basic algebra here we're going to combine all of the eyes in the JS you can verify that you still get the same number you know um yeah so it looks something like that and we can calculate this we can call this um I don't know a diff equals um nums of I minus rev of I for I in range length nums and then all we have to say is if diff I equals diff J then we increment it should give us the same value all right but this is still n squ so it would time out for big numbers how are we going to do deal with that well like I said this condition is only preventing us from doing duplicates so there's no reason that we have to go through this array more than once so let's say uh counter and we'll call this uh scene whoa apparently I thought I was writing Java or something scene equals counter um and it'll just be uh diff values um in fact I don't think we need to do any of this we can just say diff so we want to see existing diffs of the current scene so t+ the current scene so t+ the current scene so t+ equals diff uh no equals scene of I and then scen of I equals c of I + 1 so that it can be used again in I + 1 so that it can be used again in I + 1 so that it can be used again in the future and we're going to run this and hopefully I didn't screw up cuz that'd be really embarrassing uh looks like it's good hey that was uh that was pretty fun all right see you hey I'm sorry I couldn't leave it like that this was going to drive me insane um so uh first off let's put this down here and let's make this one in line so um if I do that then this will have to be nums of I guess uh and then I'm going to take this and this is going to be rev right here so there's no more rev is gone still give me the right answer I haven't screwed anything up yet have I all right cool and then yeah not uh not this so T equals sum of itimes IUS one they're the same thing we already have the counter we don't need to do that nonsense whatever we're doing for I in scene do uh values the counts and it doesn't even matter what the numbers are and uh we could can I put this directly in here invalid syntax okay I guess I can't put it directly in there unless I make it a list which I think is kind of silly uh what did I do I oh wait is that what I was mad about not this there oh boy oh look at that it's uh it's doubled that's because I forgot the Symmetry whoopsie actually integer divide by two first yeah this can come down here this can go away run work all right that is better okay I'm happier now
|
Count Nice Pairs in an Array
|
jump-game-vi
|
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions:
* `0 <= i < j < nums.length`
* `nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])`
Return _the number of nice pairs of indices_. Since that number can be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[42,11,1,97\]
**Output:** 2
**Explanation:** The two pairs are:
- (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.
- (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.
**Example 2:**
**Input:** nums = \[13,10,35,24,76\]
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
|
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value in the heap is out of bounds of the current index, remove it and keep checking.
|
Array,Dynamic Programming,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
|
Medium
|
239,2001
|
474 |
hello guys welcome to another video in the series of coding today we are going to do a problem which is called ones and zeros so you are given an area of binary strings strs and two integers m and n you have to return the size of the largest subset of strs such that there are at most m zeros and n once in the subset uh set x is a subset of a set y if all elements of x are also elements of y let's try to take an example to understand this okay suppose we are given these three uh strings i have written down the number of zeros and ones in each string so the first string has one zero and it has two ones the second string has two zeros and two ones the third string has no uh one but it has one zero right so now let's say we are um asked to find out the maximum subsets we can take with some given m and n right let's say uh it's given that m is equal to 3 and n is equal to 2 that means that we are allowed to take only three zeros and two ones in our entire subset so how do we solve this problem so we are going to go step by step right so we are going to consider at each step we have two choices whether to take the first string or not similarly to take the second string or not similarly to take the third string or not okay let's see it with the help of an example so in the first case okay if we take the first string right then we will be left with how many zeros if we take the first string we had three zeros but if we take the first string three minus one is equal to two right so we will be left with only two zeros because out of three zeros we are going to use up one zero in the first string because first string is 1 0 right so 3 minus 1 is equal to 2 so if we take the first string we'll be left with only two zeros and we will be left with 2 minus 2 which is equal to 0 once right so this is one of the choices that we have if we take the first string okay now if we take the first string uh we are at i equal to zero currently and there are three strings right corresponding to i equal to zero i equal to one and i equal to two okay so if we take the first string we can move forward to the next index which is i equal to 1 okay but we have a second choice it's not necessary to take the first string let's say we decide not to take the first string we can continue forward right without taking the first string in that case we'll be left with same number of zeros and ones as before because we are not using any such thing so m is equal to three and n is equal to two will remain as such and we can move forward to the next index these are the two choices that we have in case we decide to take the first string we are taking one sub one subset right in our solution so whatever answer we will get plus one is going to be our answer because we are taking the first string in the second choice we are not taking the first string okay so whatever max value we get out of these two is going to be our answer because we need to return the maximum number of subsets that we can take so we have two choices among these two choices whichever choice returns the maximum answer that is what we are going to return finally okay similarly we can expand this function call further we have the function called m equal to 2 n equal to 0 i equal to 1 right so we can expand this function call also further now we have choice for the second string okay now note that we cannot take the second string because we have n equal to zero means we don't have any ones at all to use but the second string requires two ones right so we can never take the second string okay because n equal to zero does not allow us to take any sec any second string further right so we will just continue with the function call and we go to the next index i equal to 2 now let's um see the next case now we have the second condition for the next function call which is for this function call right in the function called m equal to 3 n equal to 2 i equal to 1 this function call we can take the second string in this case right when we did not take the first string in this choice when we did not take the first thing we have sufficient number of ones and zeros to take the second string okay so if i take the second string then i will have three minus two which is equal to one right one zeros remaining i will have two minus two which is equal to 0 once remaining and i can go to the next index and since i am taking the second string i am writing 1 plus ok now this is one of the choices but it's not necessary that i take the second string i have one more choice where i don't take the second string also in that case i have the same number of zeros and ones that i started with and i can continue to the next function call right now similarly this function call also i can expand as such i can take the third string or not if i take the third string then in that case 2 minus 1 is equal to 1 i will be left with 1 0 once and i'll be i'll go to the next index but it's not necessary that i take the third string i have a choice where i don't take the third string right so similarly i can expand all of the remaining function calls as such and i can build the entire recursive tree after building this entire recursive tree right when i reach the condition i equal to 3 in this case i can exit because i have only three strings right so when i reach i equal to 3 this entire function call will exit and it will return 0 so i can return 0 here okay so i am going to return 0 from this function call similarly from this function call also i am going to return 0. so let me quickly write so i am going to return 0 from this function call and in this function call also i am going to return zero okay similarly in this function call this entire function call will also exit and it will return zero similarly this entire function call will also exit and this will return zero this function call will also return zero okay so i have uh the same conditions in all of them i am going to take maximum of one comma zero so maximum of one comma zero is one right so all these three function calls will end and all these three function calls are going to return one okay so this function call is going to return one back to its parent call so this will return one here so let me quickly write one there when this function call ends it will return one okay similarly when this function call ends it's going to return 1 so let me write 1 here similarly when this function call ends it's going to return 1 back now this function call is going to see maximum of 2 comma 1 right we have this max here so maximum between 2 and 1 is obviously 2 so we are going to return 2 back to the main function call ok so this function call is going to return 2 and this function call is 1 plus 1 this is also 2. now the maximum between 2 and 2 is again 2 so we are going to return 2 back to the main parent call so the answer for this case is 2 right so the maximum number of subsets that we can have is 2 how are we getting 2 see we got 2 in 2 ways right we got maximum of two comma two why did we get that because we can either take the first string and the third string right if we take the first string one plus one is two right so we can use up two zeros we have three zeros similarly two plus zero is two we can use up 2 once we have 2 ones right this was one of the choices and the next choice was you take the second and the third string okay in this case also 2 plus 1 is equal to 3 2 plus 0 is equal to 2 you have three zeros you can use it you have two ones you can use it so we got two cases and in both the cases we are getting maximum subsets as two so two was our answer okay this is our logic this was the recursive code let's write the recursive code then we will see we will get the time limit exceeded error we will see how to optimize this recursive code okay so first of all let's write the recursive code we have to write the function to find the maximum number of subsets so let me pass strs let me pass m let me pass n and let me pass something which is the index which is the current index that i am traversing so initially i will start with 0 right because i am starting with the 0th index and i will go until the end of the string ok so i have a function find max whatever that function returns here i am going to return okay so let me copy the parameters quickly from here and i have one more extra parameters which is index now what is my base condition is very simple whenever we saw index was reaching the end of the size of the sts in that case we are returning zero otherwise it is very simple right first of all we have to count the number of zeros and ones so let me give one condition to count the number of zeros we can use the count function uh so wherever we are at the current index in the string it will count the number of zeros for that particular string how will it count in the third parameter i can give zero so this will count the number of zeros if i specify this parameter right now i have to also count the number of ones so i need not count the number of ones again using count function i can just give the size of the string minus count zeros because both are complementary right the string consists of only zeros and ones so i can use this now i have two choices right what are the two choices at each step either i take the string or not if i take the string then i am reducing the number of zeros that i have okay i had to use m zeros now since i have used up zeros by taking the string then i have less zeros remaining okay i can just give m minus count zero similarly i can give n minus count once and i can go forward to the next index this is one of the choices that i have okay what is the next choice that i don't use up this string i try to look for better answer later right so these are the two choices that i have now if i choose the first choice then i will also have to give one plus this because i am taking the string if i am taking the string then i am already taking that string i am already taking that subset so i can give one plus whatever this function returns okay otherwise i can take the second choice now whatever i get right maximum among these two choices that i can return is the answer because eventually i want to return the maximum number of subsets okay now this choice is not always valid right because my m and n can never be negative so i will have to give the condition check here that m n should never turn negative so i will have to give that condition check okay if it is possible to use up the zeros and ones then only i use up if it is not possible then it's very simple i cannot use up the string so i can just give this same function call again okay that's it this is a simple recursive code so now if i run this code let me first of all submit this code and see what error it's going to give time limit exceeded error right let's see it's giving time limit exceed okay how can we optimize this code okay let's think about it see we are using three parameters right s we are using actually uh three things which are determining our solution m n and index okay now you can see let me try to uh write down the function calls again and when i write the function calls again right let's quickly let me write the function calls again see when i write the function calls again you can notice that some function calls are repeating m equal to 1 n equal to 0 i equal to 3 is repeating again m equal to 1 n equal to 0 i equal to 3 so since some function calls are repeating again and again you have to do some calculations right this is where you are getting time complexity problem so i can optimize this piece of code how can i do that is i am entering into recursive calls again and again right so i can just store the answers of this recursive call into a matrix and whenever i have already visited the given function call i need not again enter it rather i can just see the answer from the matrix so that is our logic okay so we are going to use dynamic programming and we are going to store the answer that's why i'm giving the matrix name as dp and i'm going to resize my matrix so dp dot resize it's having three parameters right m n index so i am going to give that as the sizes okay so vector so i am declaring a 3d matrix because we have three parameters and i am going to resize the given matrix accordingly and initially in the given matrix i am going to give all the values as minus 1 now the logic is whenever we are seeing the function calls right and whenever this function calls finish and return before returning we are going to store their answers in the dp matrix so here i am just giving additional line of code here i am going to give return dp of there are three parameters m n and index so i am going to store the answer before returning in this dp matrix so that next time whenever i see a function call with the same parameters m and an index instead of calculating these values again i am just going to see them in the dp matrix so if dp of m n index is not equal to minus 1 why am i checking for minus 1 because initially i have given the value minus 1 right so if the value is not minus 1 that means i have saved the answer and i've changed the answer i can just look it up in the dp matrix and i can return the answer i need not calculate the values again and again by entering into recursive function calls okay that is the logic so now let me submit and see now this should not give time limit exceeded error okay so it's getting accepted but there is a better way to do this and we can do it using the bottom up approach also this was the top down approach okay let's see the bottom up approach now let's see how we can do it now we can also solve this problem in a better way and that is bottom up solution right so we can build the dp matrix from the very beginning so let's start building the dp matrix from the very beginning we need not use any extra function we can just do it within this function itself so i have str dot size okay plus 1 and then i have vector in so this is the way to declare a 3d matrix i have to give the size parameters as such so i am just giving all the parameters right so i have built my dp matrix now once i have built my dp matrix what i can do is i can start building the answer in it from the very beginning okay so i can just start i have three parameters right one is the current string at which i am that is the first parameter i second is the number of zeros that i have right so i'm giving that as uh j so the number of zeros in this condition can be from zero to m okay and the next parameter is the number of ones that i have so that i can give as k and k can go up to n okay so now again as similar approach we have seen again we have we are just doing the same thing but in a bottom-up way we have to again give the bottom-up way we have to again give the bottom-up way we have to again give the count function we have to calculate the number of zeros that we have right so i can just uh use the same count function as i had used previously and i am just counting the number of zeros that i have and again i can declare the same variable count zeros and to calculate the number of ones after this i can just use the logic that the number of ones are complementary to the number of uh zeros so i can just subtract that from the size now once i have built this right what i'm going to do i again have two choices right what are the two choices that we had at each step we saw it from the recursive solution we know that we have two choices right similarly here also we have two choices either you are going to take the subset or you are going to not take this subset right if you are going to take the subset what is going to happen you are taking one right you are taking one subset so you are taking the current subset you are taking the current string so you are definitely taking this current string so for that i have written one plus now whatever you previously have stored answer right in this matrix so in the previous index whatever answer you have stored okay but since you are going to take this current string that means you are not going to have the same number of zeros as before right so whatever the number of zeros you have from that you can subtract the number of zeros as before right as before so you can take j minus count zeros and similarly you can take k minus count once okay so you can see the answer in the dp matrix whatever value you have calculated before right 1 plus this corresponding value this is the case when you are going to take this subset right so this value is going to give the case when you are going to accept this subset whatever till now with the remaining uh coins that you have available with the remaining uh number of zeros and ones you have available with that how many subsets you can build and then since you are taking the subset you are adding one to that okay now this either this is going to give the best choice or if you don't take this subset at all if you don't take this string at all you will be left with the same number of j and k right so you can use up those okay use in other strings either this or this any of these choices are going to give you the maximum answer whichever gives you the maximum answer that you can just store so dp of i j k will be equal to whatever maximum value you're getting from the two choices now this will not always be valid you have to give the condition check this should be greater than equal to 0 otherwise it can go out of bounds similarly this should also be greater than equal to 0 now if we are not entering into this condition then it's very simple then your dp of ijk will be simply whatever previously you have computed the value right it will be that simply okay so this is the simple three for loop code that you have and this is a bottom-up code that you have this is a bottom-up code that you have this is a bottom-up code that you have right so after this is done you have to return the answers so the answer will be stored finally in the last value so you can just check given all the possibilities what is your final answer so you can just return the last value in your matrix okay now let's submit and see if this code is going to work okay there is one thing in this uh which i just saw see in this case what we are doing we are taking i up to str.size right i less than equal to so str.size right i less than equal to so str.size right i less than equal to so in this case what we'll do we'll take i from the first string so corresponding to the i is equal to 1 means we are looking at the first string so here i will give i minus 1 okay so here i will have to give i minus 1 for it to be valid otherwise in the last index it will not be valid right so uh if we are taking i equal to 1 we are actually at the zeroth index or the first string in the uh given input right and then this will work for all the test cases okay now let somebody see it should work so again it is giving some problem let us see let us try to see where the problem is okay here i guess we should give m plus one let me submit and see again whether it's fine now it's accepted okay thank you for being patient
|
Ones and Zeroes
|
ones-and-zeroes
|
You are given an array of binary strings `strs` and two integers `m` and `n`.
Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_.
A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`.
**Example 1:**
**Input:** strs = \[ "10 ", "0001 ", "111001 ", "1 ", "0 "\], m = 5, n = 3
**Output:** 4
**Explanation:** The largest subset with at most 5 0's and 3 1's is { "10 ", "0001 ", "1 ", "0 "}, so the answer is 4.
Other valid but smaller subsets include { "0001 ", "1 "} and { "10 ", "1 ", "0 "}.
{ "111001 "} is an invalid subset because it contains 4 1's, greater than the maximum of 3.
**Example 2:**
**Input:** strs = \[ "10 ", "0 ", "1 "\], m = 1, n = 1
**Output:** 2
**Explanation:** The largest subset is { "0 ", "1 "}, so the answer is 2.
**Constraints:**
* `1 <= strs.length <= 600`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists only of digits `'0'` and `'1'`.
* `1 <= m, n <= 100`
| null |
Array,String,Dynamic Programming
|
Medium
|
510,600,2261
|
884 |
hi my name is david today we're going to do number 8 for uncommon words from two sentences this is an easy level problem on lead code and we're going to solve it in javascript so basically we have a function that takes an a and b they're both strings and you get those sentences and they're they want us to return an output which is an array of strings and it wants us to return all the unique words within this so in string a suite is unique is not in b and it also only appears once and b sour is unique it's not in a and it only appears once in b so it returns sweet and sour and here another input a apple so even though apple is unique it's not i mean it's not in b it's is in there twice so we don't count that and b banana is in banana isn't b but not in a so we return banana so how we're gonna solve this one is that first this is a string it's hard to is very inefficient to manipulate strings so we want to turn it into an array so turn one step one turn a into array two turn b into array and it wants unique so whenever everything unique we wanna use objects so create and then we're going to create an object for a and then we're going to create an object for b create map object for a b and now let's fill this out for a so we loop through a and then when we add the words ask keys in math and the frequencies as values so this map a will have the characters the words in a and how many times it appears so i'm going to use that to compare later on and then we do the same thing for b so six loop through b and then we will also add the words okay now we have the maps for a and max or b and now we also we're gonna need a output array for what we turn create and let's stay in chat six seven eight and now we'll have to loop through map a and see if it's unique to push it to the output array so we loop through map a and inside of this loop if the frequency is 1 and the key doesn't exist in map b we push the key to output and then we'll have to do the same for map b and get all the unique ones from there and after that we return output great so let's put this in code so first thing we turn this to a array so a equals a that split but draw a reminder empty split by the empty space and we do the same for b dot split empty space and now we create the map that map a equals empty object map b sorry equals empty object and that output equals up the array and now let's loop through a for that i equals zero i is less than a dot length i plus and then map a index of a i equals so if it doesn't exist we create it and set it equal to zero and then we also increment one and then we do the same thing for b and we can console.log this here you can see it gets this value and then we're going to compare it this map a might be the keys in the count so now we loop through map a for that key in map a and then the conditions if map a key has a value of one and it doesn't exist in b we push this to output dot push key and then we do the same for a map b that we loop through and lastly we return output great we got it so the time complexities we know that we're looping through a and b and then so we're going to be o of n plus m for each of the inputs and then for the space complexity it will also since we're creating this map as proportional how long it is and then this output is going to be o of n plus and that is how you solve this problem thank you
|
Uncommon Words from Two Sentences
|
k-similar-strings
|
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters.
A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence.
Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_. You may return the answer in **any order**.
**Example 1:**
**Input:** s1 = "this apple is sweet", s2 = "this apple is sour"
**Output:** \["sweet","sour"\]
**Example 2:**
**Input:** s1 = "apple apple", s2 = "banana"
**Output:** \["banana"\]
**Constraints:**
* `1 <= s1.length, s2.length <= 200`
* `s1` and `s2` consist of lowercase English letters and spaces.
* `s1` and `s2` do not have leading or trailing spaces.
* All the words in `s1` and `s2` are separated by a single space.
| null |
String,Breadth-First Search
|
Hard
|
770
|
1,790 |
hey folks welcome back to another video today we're looking at question 1790 check if one string swap can make strings equal though we will be solving this problem is by keeping a track of all the indices that we need to change or possibly swap um and check if the number of indices are greater than two or not but before we get into that there are a couple of Base cases that we need to cover so let's say a string of string one equals string two as in both of them are equal nothing needs to be swapped in this case you would just return true as it is one of the requirements and the question uh where to say it says at most one string so basically uh even if you don't swap anything they'll be equal so you return true the next thing that you need to check is that if S1 dot dial length as one of the sizes of both the string that are given to us are not equal that means regardless how many ever times you swap they will not be the same so you just return false as if awesome so these are the two base cases that we care about the next thing that you need to do is actually keep a track of um the number of indices that are different so to keep a track of the number of indices that are different we need um a data structure that can grow in size because at this point we don't really know how many integers um sorry how many indices would be different so we create an array list for that and we say indices and let's call it and then initializer array list right once we have that let's iterate through all of the letters and both the strings that's an S1 uh actually let's just get the land prior so it's in size increment I so if um that's Wonder character and I if it is not the same if the character is at a given index are not the same as then they are different we need to keep a track of that so we would just say indices .ri .ri .ri awesome so once we have that we know that we can swap only two integers right and we can swap only two indices so if the size of indices um every list is greater than two that means even if we swap it uh it doesn't really matter because the strings won't be the same so you do one quick check whether if it is greater than two or not if it is you just return false else now what you need to do is that if let's just actually get the indices index one oh it's actually it is not equal to 2 actually because it can be one as well so index of one would be equal to indices dot get zero and then and index 2 will be equal to indexes dot get one awesome so you need to check if you swap them they'll actually be the same so how do you check that right so if S1 note character add index one um is equal to um S2 dot capture at index two and then you just need to swap them and check so you need an unconditioned because you need to swap both of them and then both of them uh when you swap them it gives you the same string so if they are equally with return true if this is not the case you would return false that is the entire problem it's a pretty simple problem it's marked easy as well awesome so let's try combining this and see if it's okay the first few test cases are okay everything else is okay as well awesome so let's talk with the space and the time complexity of the entire Solutions so the time complexity is off and since we are going through every single array in the two strings that are given to us and the space complexity is also open but that's the worst case where all of the indices are different and we need to store that in indexes awesome if you have any questions about the problems please let me know in the comments below don't forget to subscribe to the channel and like the video I would really appreciate that it definitely keeps me motivated to make more videos um thanks so much and I'll see you folks in the next video peace
|
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
|
239 |
hey friends welcome to the new episode of code with Jess so today let's do leap code number 239 sliding window Maxima if you haven't done this question before please feel free to pause this video and try it yourself I'll put a link in the description box so this question is given an array of numbers and given the window size K the output will be a new array with each windows maximum number so let's take a look at the example this is the array of numbers and our window size is 3 here so my approach is to use a deck which is just a double-ended a deck which is just a double-ended a deck which is just a double-ended queue so we can easily access numbers from both ends and here we have the result we have a pointer pointing to the first number how that works is that whenever we get a number we're checking the deck and delete all the numbers that are less than this current number then at this number in the deck that way the very front of the deck is always the current maximum number so right now when I is pointing to one since our deck is empty we just add 1 and we move the pointer to 3 so now 1 is less than 3 so we remove one and actory now we'll move I to the next number which is negative 1 nothing in the deck is less than negative 1 so we add negative 1 when I reach us here we reached our window size so we take the very front number from the deck and that should be our result for the current window so we add 3 here move our pointer to negative 3 nothing in this deck is less than negative 3 so we add it to the deck and right now our maximum number in the current window it's still 3 so a actually and then we move this window again as you can see now this 3 is moved out of the window so we need to delete this 3 from the deck and add 0 or as 0 we can see the negative 1 and negative 3 are both less than 0 so we delete this and add 0 and our current maximum value is 0 move the pointer again so negative 1 is out of the window and it's not in the deck so we don't need to remove it and this eye is pointing to 5 and 0 in the deck is less than 5 so it removed this 0 and add 5 and right now our new maximum value in this window is 5 so we add it to the result now we move the pointer again so negative 3 is out of the window and is not in the deck an eye is pointing here 3 and the 5 is not less than 3 so we're just a dream here the maximum number is still 5 we move the pointer again and 0 is out of the window it's not in the deck and I is pointed 6 is greater than both 5 and 3 so we remove these 2 in that 6 that makes our current maximum value in this window 6 so we add that move to the pointer again you know 5 is out of the window and it's not in the deck I is pointing to 7 and 7 is greater than 6 so we remove six and that 7 that makes seven the current maximum and we get our result now let's write the code first of all as usual let's check if the inputs are valid nums can be no nums length has to be greater than zero and K needs to be smaller or equal to the numbers Ling if the input is not valid we just return empty result now we need integer array as our results and the length will be the length of the number array - the length of the number array - the length of the number array - the size of the window plus one so if the number is three our window size is two means our result will have two numbers which is three minus two plus one also we need our deck and our pointer so when I is less than numbers lengths will go into this loop so first in the lower pointing to check if any of the numbers in the deck are getting out of the window to do that in this deck we need to save the index instead of the real number if the deck is not empty and if the first numbers index is getting out of the window then we remove it out of the deck so next up we need to check from the right side of the deck and remove all the numbers that are less than the current number so while the deck is not empty and the very right number is less than the current number now we remove the last one and after that we put our current number on the last position of the deck so that we have an ascending order deck and keep in mind we're adding the index so when the pointer is moved to a position that's big enough for a window we can start adding the maximum values to the results so if I is greater than or equal to K minus 1 that means when K is 3 I needs to be at least two to produce maximum numbers to the results so we get whatever is in the first position of the deck and get that value and after that we move the pointer and after this wild look and after this loop we just need to return the result now let's take a look at it from the top so first of all we try to check if the input is valid if it's null or has length of zero or the window size is bigger than a rate length then we'll return an empty result otherwise we create in result array a deck and a pointer so if the pointer is less than the length of the array would come and check if the deck is not empty and if any number is moved out of the window if there is then we pop the first one and we start from the right side of the deck and check if there's any number that is less than the current number if there is then we will move this number and after that we add the current number in the deck then we check if is big enough to form a window then we grab the very first two value from the deck and get the corresponding value from the Nam's array and assign it to the result and went over the pointer and after everything we return the result now let's try to run it no typos so this is a result it won't and let's run the example that we just talked about all right and let's test some edge cases all right our output is actually better and let's try this maybe an empty array all right let's submit it okay great that's about it today I see you guys next time
|
Sliding Window Maximum
|
sliding-window-maximum
|
You are given an array of integers `nums`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position.
Return _the max sliding window_.
**Example 1:**
**Input:** nums = \[1,3,-1,-3,5,3,6,7\], k = 3
**Output:** \[3,3,5,5,6,7\]
**Explanation:**
Window position Max
--------------- -----
\[1 3 -1\] -3 5 3 6 7 **3**
1 \[3 -1 -3\] 5 3 6 7 **3**
1 3 \[-1 -3 5\] 3 6 7 ** 5**
1 3 -1 \[-3 5 3\] 6 7 **5**
1 3 -1 -3 \[5 3 6\] 7 **6**
1 3 -1 -3 5 \[3 6 7\] **7**
**Example 2:**
**Input:** nums = \[1\], k = 1
**Output:** \[1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
* `1 <= k <= nums.length`
|
How about using a data structure such as deque (double-ended queue)? The queue size need not be the same as the window’s size. Remove redundant elements and the queue should store only elements that need to be considered.
|
Array,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
|
Hard
|
76,155,159,265,1814
|
1,254 |
Hello gas welcome you me channel number one tu five four okay the name of the question is number of close okay Google asked this question and by looking at the input of the question and understand what is the question okay you must have given one you the great. Okay, if you pay attention in the 2D grid, whatever is forest or not, that is water, okay, I mark it with blue, whatever is forest or not, these are all water, this is water, okay, this is water and this is water. It's yours, it's zeros, that's land, okay, there's land here too, and look, there's water here too, okay, then it's getting dirty, but one is water, and zero is your land, okay, and whatever else you take as mother. This is the land, this is the land, it is four dimensionally connected, it is connected from the top, it is connected from the bottom, right and left, here, on the right, there is water, there is no brother's water, so it cannot be connected to that. This land will be connected to this. This is fine. So what I am asking you is that how many number of such islands are there which are closed. So what about the Irelands which are closed? There is an Ireland, it is okay, on which there is water on the left side, there is water on the right, and it is surrounding, it is okay with water, this means that it is okay in counting, but yes, it is closed only with water. It should be like if you look at this Ireland, it is okay, there is water on the left, forest is okay, if water is visible on its left, then it is okay, but there is little water on the right, if it has gone out of bone, then the boundary on this is a guarantee. Let's not put that close, it is okay if it is on the boundary then we will put a close, so let's see it is from the concept of closure, let's pay attention like look at this, we will put a close, why there is one on the left, here on the left, I on the right, I on the top, I on the bottom as well. Okay and look at this, will you put this close, this one, this close has water, there is water on top too, but look below and on the right, there is no water, it is auto bound, okay, so one, I got this close, it is Ireland, okay and Let's see and come here, read it, lay it down, it is important, water is seen on the right, there is no water above, but if you go higher, there is water here, if you look, it is close, look, go left here. It is also closed, look here also, it is closed everywhere, okay, so if I draw the parameters of this closed iron, it will look something like this, then pay attention, okay, it looks something like this, okay, because this is the Irish connect, is n't it the ground connector? All of them are connected, they are fine, they are connected, I am now standing at 0, this is water, so I do n't care, I have to find Ireland, brother, if I want to find Clojuran, then skip this one, this is also water is water, skip this. Do it, skip it, found zero land here, okay, so now what do I have to see, brother, if I go to its left, water should be shown, if I go above it, water is on the right, water is still below, then water should be seen, okay, I have gone to the outer bound. So brother, it cannot be closed, okay, keep going to the left, if water is seen then it is very good, it means it is closed, you go up on the left side, if water is seen, then close from the top too, keep going down. I am going, see the water is closed at the bottom and it is okay here, so if you pay attention here, as soon as I saw that it is zero, I looked to the right, to the left, is there water, so from the left side it is closed, okay. So I write it like this, it is closed from the left, it is very good, it went down, it is also closed from the bottom, look, I got the forest below, on the way, it is closed from the Dr too, okay, but not closed from the right and from the top, it went out of the bomb. And it is not even close to the right, okay, and what I said is that one Ireland is upper right, so you have to pay attention to this thing, okay, so it is an obvious thing, when you come upon one of the Irelands, then what you have to do is simple. Hit DFS, you can also do it with BF, you can make it with BF, I will tell you simple from DFS, here, if I hit DFS, what will I do, first of all, I will go to the left as far as I can, when it becomes yours, ok water mill. If I go, it is very good, I will return brother, I got water here from the left side, so I closed your left, okay, after that I will hit above it, okay, I hit above this too, I hit DFS on top, DFS hit from above. If he went out of band, then I wrote, is it now, is it close or not, did he burn it? Okay, similarly, I will hit him right. If he went out of band with the right, is he close or not? Did he burn him? Dr Gaya Downpe, when he hit DFS, then here. I went here, it is closed, brother, okay, if the doctor is closed, then I have made it true. Okay, you can get it closed from the doctor, but look, even if you have seen it from the doctor, it is not closed, because look, when you came here. So look here also, here it is not closed from all four directions, it is closed from the left side, it is closed at the bottom, but look here, it is not closed from the right side, and so the bound is gone, story, no story, the auto band is gone, no, I want close everywhere. If you go out of bounds even on the story, then brother, this is not closed, isn't it? There is no auto close on the story too, it is simple, brother, DFC is to be believed, if you look at it, there is no need to do anything fancy, it is simple, okay, now mother, I am here. When it came, I hit DFS here, okay, so first I will hit DFS from above, I got one from above, brother, if there is one, then it is closed from above, then close is happy on its left, ours is also happy from here, if I hit it on the right, then one is not there on the right. But if there is water, then let's go ahead and flood, then here A went above this, ours is here, remember, you started from here, now you started from here, you hit the rest of the DFS, okay, then come to the right of this, above here, happy. It is closed from here to the right, above is happy, it is closed, it is right here too, it is close, so you are happy, okay, then you will hit below from here also, this is closed, you are happy, then you will press back, otherwise it is obvious that you will come back here and If you come here then again if you go down from here, then it is zero, here it is zero, if you go right, it is closed, if you go left, it is also closed, if you go down here, it is closed here It is closed here too, it is closed everywhere, it is okay and yes, remember one thing, one important thing, remember that like a mother takes you, when you came here from here, when you went here, it is okay, then when you come back here, it is okay. So, I had to hit in all four directions, I hit, okay, then when I came here, the crowd was asking in all four directions, will you hit or not, will you hit here, do n't hit back here, now by the way, from where you have already visited, mark your visit. How will you mark Vidit? Brother Vidit Mark, will you mark it as one? If it is visited then it is fine so that when I come here and come back, after seeing one here, I will say yes, it is closed again. What am I saying that I was standing here, my DFS, our DFS, went back up, there was one, will come here, then here this banda of ours can also go up, right dr and left, why are you going back left, now that is where you came from here. If you had come, what will you do, we will mark it as one, okay, as soon as you visited, we will mark it as one, okay, there is going to be a very simple code like this, okay, what did I say, as soon as I get an Ireland, I will be here. I will kill DFS from it, okay and I got close from everywhere, so it means it is closed, close balance is fine, so if we look at it, then we will put two closes, right, ISP, look, this close is complete. Close was the story but also not out of bounds, and which is Ireland? I have seen this end here, so I started above, close here is close, went here, got this also close, went here, this too is close. Got a close here too, if it went here, then this close, from here, this close, there is also a close up close from here, there is no auto band on the story, neither is every If the place is close then it is not out of band, is it? And if you go back to whatever place you have done, what will you do by marking it as one, yes, it has been visited, I have made it water, mark it as one. Okay, but so that again you will get stuck in the loop, you will go from here to here, then from here to here, again from here, you will get stuck in the loop, that is why mark it as a widget and make it a hey. 2D Hey visiting, do this and then change this one. If you have to say in the interview that you cannot change this input then you can also reduce the size and make it dear and in the beginning, fill the military in everything which has been visited. To cause trauma, you already know all this, we have already gone through so much, now see how simple its code will be, the score will also be like the story told, see how, see what I told you. I will go to each cell and as soon as I get zero, that zero, as soon as I get zero, that means I have to assume DFS is ok here and when I hit DFS, like here I went to the next step, if I hit DFS then now By the way, I will have to look all around, up and down, right, okay, I will have to look all around, so if I am out of time on the story, okay then brother, burn the return, it is not close, it is ok, so it is very good, what will you do? Left side is fine, left is right, mother, it is fine if it is true from everywhere, it is fine if it is not true from everywhere, then if it is true from everywhere, then brother, we are closed, isn't this one which was Ireland of mine where I started from zero. That will be my close and I will mark everyone and the whole of Ireland as visited so that I do n't visit it again in the future. Okay, so I will mark the silent one as detailed. I will mark everyone as 11 that they are visited. So if I have got close from all the directions, then it means I will close it, okay, I started the return here, like it came true, I made my account plus one, okay, then next big sale, next big okay and From there again we will hit DFS on all four directions, okay, if we look at it, here it is big, ahead, but on the story, I did not get the land, like it came at zero, okay here it is at zero, I hit DFS on it, okay when DFS. I will hit you and check you, close should come everywhere, okay DFS, our above depression, our brother got out of closed, return from here only, this guy who is out of, is not closed, okay, so this will increase the ability to do DFS everywhere. I will hit above here too, I will hit here below also, so now by the way, this furder will hit DFS everywhere, so by the way, I have marked this entire land as a visit so that if I go again, do n't hit DFS on it here again. If not, then you will have to mark the visit. It's okay. It's a simple story. Sorry friend. Let's convert it into code. Line by line, is n't it? I will write the code directly to understand the code. No, as the live balance increases, I will write the code as you understand it. Okay, so let's go. If we code this, then let's code it. The code is going to be very simple. Pay attention to the most important thing when we code. It is very important to understand each and every line. Okay, so first of all let's keep two variables which are What will mine store, how many days and with how many pens, so let's populate it M = great of zero Dot size is ok, I have given it in the girlfriend, brother, the length is the length, pay attention here, it will be bigger than the one, nor the grid's. Length is that one or it will be bigger than that then great zero dot size taken out is safe here right code will not burst here ok this is done after that brother count this equal you keep zero in which I will increase my results I will know how many close islands are there. Okay, now let's put the fruit loop. Foreign tire is equal to zero i < mi + 4 and g = 0 equal to zero i < mi + 4 and g = 0 equal to zero i < mi + 4 and g = 0 j < on which DFSMroge when great i and k my is equal to zero na zero means the land of Ireland. If they consider it as DFS, then count plus it is equal, okay, let's do it like if in DFS, hit on whom, hit on great, hit on I, comma J, okay, if from here, true, A, what does it mean that this which It was Ireland, it was close, so I did the plus count, okay, and what will I do in the last count, I will do the return count, okay, now what do I have to do, just write DFS, just say DFS, okay, what all are you passing, great, so pass. We will have to do it, okay, we are hitting DFS on this and on which row should the brick be and which pen should it be on, now you are there, so you will have to send that, okay, and what did I ever tell you, that is, if R is greater then equal, you are M or Then and < 0 is done equal, you are M or Then and < 0 is done equal, you are M or Then and < 0 is done or else pen is greater dene equal tu n done or else pen is less den zero is done okay if any cell already I have marked visited okay then either if I got one i.e. Great of I was hitting DFS, I was i.e. Great of I was hitting DFS, I was i.e. Great of I was hitting DFS, I was dying, I went on one, okay, that means what did I get, I got water, okay, from this side, okay, now okay, if we take mother, it must have been zero, then it is a land, meaning further on this, I And if you have to hit DFS, then first mark it as Visit. Okay, if you mark it one, then you mark it. Mark Visited. Okay, Visit. Marked it. After that, forget Left Close. Is it okay? DFS is great. If you have to go, what will you do? So, we will turn on the columns, okay, similarly, we will check the left close, similarly, the column will change, if going up, the row will decrease and the pen will remain common, if going down, the row will increase and the pen will remain common, okay and When will we return, when all will become true, this also becomes true and this is also true, what does it mean, I will add account, then you have seen, Ireland base, so many questions have been kept, so this is one of them. Neither was there much, there will be R and C here, nor will there be R and C here too, and look here, you should have written equal, it was a mistake, now let's run it and see after submitting the example test in IT lesson, okay great. I will pass the details that please, you can clear it from DFS also. If you have doubt in BFS then ask me and if it is possible that you can clear BFS from here also, BF is given in its solution, so I don't think it will definitely happen without seeing now. Okay guys, what I have understood about DFS is here already and it is a very long explanation but I hope you have understood my extension. Okay and if you pay attention, what is its time complexity, M is cross. Because we are visiting each cell only once. Okay, so my purpose was that you can create BFS by yourself, so I explained it so that the question can be understood and we are visiting each cell only once. Its just M cross M ok next video thank you
|
Number of Closed Islands
|
deepest-leaves-sum
|
Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.`
Return the number of _closed islands_.
**Example 1:**
**Input:** grid = \[\[1,1,1,1,1,1,1,0\],\[1,0,0,0,0,1,1,0\],\[1,0,1,0,1,1,1,0\],\[1,0,0,0,0,1,0,1\],\[1,1,1,1,1,1,1,0\]\]
**Output:** 2
**Explanation:**
Islands in gray are closed because they are completely surrounded by water (group of 1s).
**Example 2:**
**Input:** grid = \[\[0,0,1,0,0\],\[0,1,0,1,0\],\[0,1,1,1,0\]\]
**Output:** 1
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1,1,1\],
\[1,0,0,0,0,0,1\],
\[1,0,1,1,1,0,1\],
\[1,0,1,0,1,0,1\],
\[1,0,1,1,1,0,1\],
\[1,0,0,0,0,0,1\],
\[1,1,1,1,1,1,1\]\]
**Output:** 2
**Constraints:**
* `1 <= grid.length, grid[0].length <= 100`
* `0 <= grid[i][j] <=1`
|
Traverse the tree to find the max depth. Traverse the tree again to compute the sum required.
|
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
1,416 |
Hello everyone welcome back to my channel once again here we are going to talk about the problem of lead code daily challenge which is today's problem okay and this lead code is one of the hard part which is where the question name you are seeing. This is one of the hard questions and here we are going to discuss it, so before moving to the question, if you are new to the channel then definitely subscribe to the channel, here we will explain this question very well along with you. Here you will find the video of every contact on delete code forces and there are many more, so visit the channel, if you like it, if you find it useful, then definitely subscribe. So, first of all, let me tell you one thing that I have done here. But like, when we go to the code part, okay, when we go to the solution, when we go to the logic, then you will not have that thing, but in the implementation, if you see, if you don't see the submission, then I have one color submission here for the time, so here I give two likes and two tips. I will give you one or two suggestions that if you are going with him, then you should not do it in this way at all, it is okay, I will tell you when we come to the court, I will tell you now, if you do not understand that thing, then we People have to read the question first, what is the question saying, what do you have to do, an S is given, okay, this is how we read simple questions, this program just suggests that you print and wait area, then you have to create a wait area. And what is there in this is that the program that was printing the wait, it escaped the comma which is special there, okay what have I said that I am writing an error, okay I am writing an error late. Suppose one you three four but it is like that the program read 1234 and it used space and whatever you are doing to separate it like Delhi Me I escaped it so what I did was I did this When it becomes difficult to write a string, it becomes difficult to use it on a simple limited story. If you make it 1234, it is not doing many possible things, then basically this is the point, so what you have is that the program made this mistake and what the program did about it. Made the concatenation, now there you had the restriction, meaning whatever you did, you know that it is okay in which element I have done that which is the Erica element, it has a range of 12, this both inclusive one will be within that. Meaning, every element of this is your mother. Okay, so every element of this is your li, give equal tu did and greater give equal tu right on the side of one and you have done the perfect number with mains no leading zero. Where if you had to write 10 then you would have written 10 was not written in this way, it was wrong, you did not want it, don't tell me how many like this, it became possible, if this value was very big, then for that you have got as much possibility as there is in it. Do all that, I will give you the value of K, okay, so that you can get the information sir and also understand that in this leading zero, no leading zeros are to be kept, so keep both these possibilities in mind. Calculate the total number of arrays and take its model of 10.9 plus 7 and of arrays and take its model of 10.9 plus 7 and of arrays and take its model of 10.9 plus 7 and tell me the answer. Okay, so this is basically the question being asked. Right, now see what will happen basically, the method will not be different, if you paste everything then it will be the same, okay. Here I say basically 1234 whatever will be made will be unique but this one is okay, how can this one be with you 123412 but when it is big enough to come from here, if you have it then you will get everything in it. There is something to think about, many people directly look at this question and there is a question, but a little bit, first of all, we have to think about where the problem lies in this and if we think about it in our example, then I think there is definitely gold, okay. It is not like this at all, top dr bottom up, you are thinking of sleeping, think beautiful like this and see what you are, DP, if you know the story or the story, then if you are representing her, then it is okay or for her or you are doing it in table form. If you are in it then basically you will get state transfer in stage transfer. I would say this is fine, it is important for you to pay maximum attention to this, it takes most of the time for me to sleep in this. Now I am DPFI Calculator. The problem is this, state transfer is done to this. I am saying that this is the most important thing for you to think and you understood this thing completely, everyone understood it when we are talking, okay, we had 1234, you think like this, there is nothing in the string, now you have only one, so there is only one. So you are keeping simple interest, I and you have done it, one account is done, there is a way of our own, when this is 12, okay, there is one more character, we moved ahead in the string and checked, when we reached the first character. We only know the meaning of one character, I don't know any further character, so right now I am rating one, okay, I am looking ahead, moving forward, so one came, now this is two. Possibilities are either two which will be added along with it, okay then it will become 12 or two will remain alone, so first of all I want to talk about alone, so if you are clear, then there is a problem, meaning it will become like this, basically when it remains together, it is okay together. If it remains, then it will ask, yes, is it like this or is it not equal, if you are equal, then this is another problem, then the story, no story, this is what you are, there will be as many ways as this forest can become, along with it, this is as many ways as it is. With that, just add me two every time, I have taken it further, when one, two, three came, then what is there in it, but take this, if it is not 100, then we will not count it, so the counting situation is not this. Similar kid of question which is similar kid of logic which you must have asked him many times, so what are we doing, we are making contact with these 3, now 3 can be possible with whom and with whom, it is okay with empty. If empty has its own method, then there will be only three, just one method, if there is a net with this 3, 2, then you will have the same method as you, for this you will have a story, not a story, even in the morning, or in the least, there is a problem of this method. If you add the form of DP from here, then all the ways to reach this Tu will be there. If it is being added with this method then it will happen, then basically if it has come and you can live in any way. If there is also a position, then what will be added to the DP of I, what will be added, so for this one position, take this mother, now we are keeping something, DP of Unknown State, let us see it, right, if we see this I state, then basically, what should we say? Whether the new character is A or the new character is A, if you want to see two possibilities with it, then it is fine, otherwise there is only one possibility on the other side, I saw it with clay and then after that I will see with a length. Meaning, after that, I took one character, then I took two characters, then I took three characters, I took 5 characters, in this way I went as far as possible, from here I got 3, with whom did I become three, if he got with you, then you became three. I mixed it with this one and took two lengths, I made 123, okay, look here, you will see that it was done in 123, then when one came, okay, basically this one, it was recalculated from super here and again with this one, next. He will have it at the bar and in this way the whole diamond will remain as it is. Okay, so I think you understand this. Now look here, I was talking about the state transfer, so look at the size, if we are 3 cute, then its How much size was it getting, wherever the person I am talking about, how many characters have I added, then I should go behind him and see that yes, tell him, how much did it take to make that particular thing, okay, so if I talk about this one. If I am doing this then whatever its index will be, I will add it and how its index will be found will depend on what we are looping, so simple here I will write whatever is unknown to unknown, its index Okay, in a way. If I say that it is a fast character, then it will have to be added, then the number, if it is DPFIS, then what is it showing, then tell me in simple words, here we also solve the dot, the P of I, which is basically telling the number of because last. If you are comparing it with K then the form of number is okay, whatever form will be one, it is okay while taking your number of K, which is basically asking you a question, here the form of number will be, all the numbers in this range. If you applied this thing till the index till the possible true date, then the numbers that will be generated are the same as DP off, so if I am writing DP of zero, then basically it is telling that there is zero index. But whatever it is, tell me, okay, how do you have a base, so what we do is zero in the string, okay, then when we will talk in the string, it will be DP of I minus one, when we come in DP, then it will be given. If there is PFI, then you have to pay attention to this thing. Okay, so this logic is completed. With this, let's discuss one more thing which I am seeing in this solution sector. In the solution sector, when I was seeing that people have Do not read from the front. I see in most of the questions at the beginning, I have not understood why it means that it is possible but it is not necessary for the question. I think you should read the top doctor from here or read it from here. There will be a slight change in the logic. Okay, I started reading the string from the right side. Those people I = did not understand. I have made a mistake. When I was doing this, it is possible that a slight error happened. Think, to save it from that or to remove that thing, they have done it in this way. Now I will give you an example like 100. Okay, so when I am talking about let's go to the current index, now I am here and from here. I did that here, then this, first of all this, then this, and then this, okay, so if you find this out, whatever is going on in each part of this lesson, okay, after that you change it. Whatever you are doing along the way, on the basis of it, in the long run, this problem of yours will be sorted which you will not even know that there was a problem in it, but when you do the same thing in this way in which you form the number. Minus zero, if you do this in your own way, what will happen? This is zero in zero plus zero will remain till here, A will still remain zero. If you had taken this value, then when you change it should be 1000. Basically, this is how 1000 cups are compared, but if you went this way, then the value of your name will be one, which is already wrong, compare. Don't do it, whether there is a mistake in it or not, even if there is no mistake in it, then the answer is wrong. Do you understand, basically, there is a mistake in the name value calculation, okay, so if you are going in this way because if you are the last If you come from the previous one then what do you do with the last one, read the last one in this manner and then keep looking at the size in it. Okay, so it does not have these problems but here if there is a problem of this type, then the question will be a little different, so you will have to ask a little bit. Meaning, there will be a slight change in the code if you are correcting it accordingly, so here I will show you how the mistake was made in my test, this one, when it is going wrong, okay, on its value, for your string. To change it, if you were doing it properly in the tree function, basically you are converting it into bricks, then it will happen to you here, if it fails, then you have to do long, okay long, to do it, you have to do something different. He will definitely have to do it, so here is Sarita's method, basically I have done it, okay, you can do it as per your convenience, okay, so now let us discuss on the court, enough sir, doubt that. What I mean is, I observed what happened to me in the solution of people, I have discussed here, now we come to the court, it will be very long to discuss it like this, so see, first of all, let me tell you that it was done in this way. This code of long one is basically fine, this method of Sarita one, I just saw it from Google and did it, I did n't do it much, I don't even care about it at all, this thing is relief, it's fine if you want. You can take help from there, I will read it in more detail, then the number coming here which is your function and here the string and key have been passed to you, then here I have defined seven and n in pay mode and have taken out now see. DP and Plus One's vegetable If we talk, then I - 1 will be the same thing, okay, we talk, then I - 1 will be the same thing, okay, we talk, then I - 1 will be the same thing, okay, I have kept some C out, you can take help of this when you want to see the question, okay, and the maximum value of size will go up to 10, now why did I say this? Given to you because if you look at the value of K, if you convert it into 10.9 rest, value of K, if you convert it into 10.9 rest, value of K, if you convert it into 10.9 rest, then 9 lengths of 10.9 will be nine and then 9 lengths of 10.9 will be nine and then 9 lengths of 10.9 will be nine and plus one which will come to you, the value of K will be more than taking 10, otherwise it is more than that, otherwise we If I made a vesting of length 11 12 and calculated its value, then it would definitely not be in the range of 12. It would obviously not be in the range of 12, so there is definitely no way to calculate it. So what I said was that this string is fine. I have come here recently to be in this index so from here now from here I told all the possibilities so this one will come alone like if one was three then three alone is now let me explain to you what is this basically so the minus size will be plus one okay Now how do you understand now 122 index first size is equal to one then there should be only two counters should be counted then basically what will happen is this I think I wrote wrong ok justice second hand 3 - 1 I wrote wrong ok justice second hand 3 - 1 I wrote wrong ok justice second hand 3 - 1 I - 1 size is done I want one Okay - 1 size is done I want one Okay - 1 size is done I want one Okay - 1 - 1, okay, minus one, because now if you look at it, - 1, okay, minus one, because now if you look at it, - 1, okay, minus one, because now if you look at it becomes 2 - 1, this is one side, it becomes 2 - 1, this is one side, it becomes 2 - 1, this is one side, for this, if you drag it here, then the index will currently move here, which is if you don't want to take me, then plus one, make me these contracts. So basically your I - 1 is your index So basically your I - 1 is your index So basically your I - 1 is your index - size is -1, so if - size is -1, so if - size is -1, so if you look at this, I have to go till I - OnePlus, I have to calculate all these strings, I have to go till I - OnePlus, I have to calculate all these strings, I have to go till I - OnePlus, I have to calculate all these strings, okay, I have to calculate this and let me change it. After changing the number in the number, how should I compare? So I did the same thing, I calculated the substring and because this is the size, it asks for the starting string and I want the size, so I gave it, took out the tempo number, I changed it, keep it long. You should keep this number on the internet otherwise you will fail like I showed you here how is the test ok so like I did the salt calculator after that I checked it now see what it said in the question that your no leading zeros should be there No Leading Zero: leading zeros should be there No Leading Zero: leading zeros should be there No Leading Zero: How to check it? If the first character of the string becomes zero then it will be leading zero. If it is non-zero then leading zero. If it is non-zero then leading zero. If it is non-zero then whatever zero after that or is not non-leading zero will be no, that means non-leading zero will be no, that means non-leading zero will be no, that means non-living zero. That's it, what we have to do is to non-living zero. That's it, what we have to do is to non-living zero. That's it, what we have to do is to check whether the cutting is zero or not, then check whether it is zero or not, if not, then let's move ahead, then let's go back from here, I do n't need to calculate further, let's go after this. I continued in another way, you have checked it. Okay, now I know both the endings, so what I said here is that I will have to add the number of the way in the DP. Yes here, which is your index of this end. Will be the same, I will have to add DP of diet position, then the method will be equal to the bag, Til date position, I will have to add, then DP of I = so much + whatever is your then DP of I = so much + whatever is your then DP of I = so much + whatever is your model now taken, other vice if it is more than k days, then next After adding the character, it will be more again, when the next character is read, it will be more again, so you do not need to calculate further, you have to break out and complete everything again with the new position. Now I have DP off. I returned all the characters of the main string and took the calculation of all the characters that will be formed and this is the question I was asking you, okay it may be difficult to understand but in this way you have to do the breakdown, to understand things one- One thing will be made easily, that is, in half an one- One thing will be made easily, that is, in half an one- One thing will be made easily, that is, in half an hour less time, understand each step in making it, write down what you will get after 15 questions, that which is half an hour, will be converted into 20 minutes, then some more time will be less, but when will the time be less? When you practice more, it will take less time to practice. If you reduce it completely, how much more time will it take, you will not be competitive, you will not be able to solve it even in practice, let's meet.
|
Restore The Array
|
check-if-an-array-is-consecutive
|
A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits `s` and all we know is that all integers in the array were in the range `[1, k]` and there are no leading zeros in the array.
Given the string `s` and the integer `k`, return _the number of the possible arrays that can be printed as_ `s` _using the mentioned program_. Since the answer may be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** s = "1000 ", k = 10000
**Output:** 1
**Explanation:** The only possible array is \[1000\]
**Example 2:**
**Input:** s = "1000 ", k = 10
**Output:** 0
**Explanation:** There cannot be an array that was printed this way and has all integer >= 1 and <= 10.
**Example 3:**
**Input:** s = "1317 ", k = 2000
**Output:** 8
**Explanation:** Possible arrays are \[1317\],\[131,7\],\[13,17\],\[1,317\],\[13,1,7\],\[1,31,7\],\[1,3,17\],\[1,3,1,7\]
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only digits and does not contain leading zeros.
* `1 <= k <= 109`
|
Try sorting nums. If nums is consecutive and sorted in ascending order, then nums[i] + 1 = nums[i + 1] for every i in the range 0 ≤ i < nums.length - 1.
|
Array
|
Easy
|
298,549,1542
|
1,287 |
yeahyeah Hi everyone, I'm a programmer. Today I'm going to introduce to you a problem titled as follows: you a problem titled as follows: you a problem titled as follows: elements appear more than 25 percent in an arranged piece. Arranging the detailed problem as follows gives us a table of integers arranged in ascending order with only one integer in this piece appearing more than 25 percent of the coefficients more than 25 percent or more. about that integer example one in example one We have a person at the beginning of our lesson an integer here has 9 elements and has been sorted in ascending order then as we see in the main section For this element, the element with value 6 is repeated 4 times and 4 times it will account for more than 25 percent of the total number of elements in this table, so we have a bad return value, then the problem is It's quite short and we can easily understand through example one, you can A we will step through the algorithmic thinking part to solve this problem. The algorithm for this problem is also quite simple. Because this is a piece that has been sorted in ascending order, the elements are the same. It will be adjacent to each other, so we just have to have one that has a traversal from the beginning to the end of the table. In each review, we will compare the element at the last position y with the element at the yth position - 1, that is, if the two elements are yth position - 1, that is, if the two elements are yth position - 1, that is, if the two elements are adjacent, if they are the same, we increase the counter variable by one unit. Then we will do that until the counter variable is greater than 25 percent, the length of the array is greater than 25 percent of the length of the piece, then we will return the y value at that position. The location at the location we are browsing is the result of the program. Okay, now we will install this algorithm language using the Vu Lan programming language. First, we will declare a variable. You don't have the result. Then we will return the result variable. Now we will declare another variable called the counter, then our base will start with the value of one then we will give one. object Loc y then this y will run from one i.e. the second element of the array i.e. the second element of the array i.e. the second element of the array to the end of the up piece of rna and y + + Each to the end of the up piece of rna and y + + Each to the end of the up piece of rna and y + + Each time increases by 1 unit Now we will check if a is the position of array A and the position of the 3rd element minus y is equal to the position of the yth element, then we will increase the counter variable by one unit. Conversely, if the element containing Y is different from the yth element, we will try to show that the count is equal to 1. Okay, now after returning the calculation in the counter variable, we have to have a step to check whether this counter piece is greater than 25 percent of the total length of the piece by doing Because 25 percent can be an odd number, we will convert the type of this counter variable into a floating point type, compare it with a floating point type, and multiply the length of these arrays. no dot 25 Yes, if high is the counting variable Ha at the y position is greater than 25 percent of the total length of the piece , then the value at the veterinary position , then the value at the veterinary position , then the value at the veterinary position is the value that we need to return so we assign roses and we exit the program and I will try running this program to see how it goes. You can see that it successfully solves example 1, well there is a hole in This is for position 1 , we o-food out zero. But the , we o-food out zero. But the , we o-food out zero. But the problem requires is 1. Well, when we return zero. Now one, we have to initialize the first value as one. ah Okay So all the values of the Okay So all the values of the Okay So all the values of the beginning of the article have been solved. Now we will go into the complexity of these algorithms, the complexity of this algorithm is very simple. we call N the number of elements of the array. We have a room that is repeated n - 1 times then We have a room that is repeated n - 1 times then We have a room that is repeated n - 1 times then we will have complexity which will be onl the complexity of the storage citizen we don't use anything else Any data structure that is complex for us to store is number 1. Thank you all for watching the video. If you find it interesting, please give me a like and subscribe . If you have any comments or . If you have any comments or . If you have any comments or better solutions, please write them down in the comments section below the video. Thank you all. Goodbye and see you again . . . yeah.
|
Element Appearing More Than 25% In Sorted Array
|
distance-between-bus-stops
|
Given an integer array **sorted** in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.
**Example 1:**
**Input:** arr = \[1,2,2,6,6,6,6,7,10\]
**Output:** 6
**Example 2:**
**Input:** arr = \[1,1\]
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 104`
* `0 <= arr[i] <= 105`
|
Find the distance between the two stops if the bus moved in clockwise or counterclockwise directions.
|
Array
|
Easy
| null |
199 |
hi everyone today we are going to talk with a little question binary tree right side view so you are given root of binary tree imagine your yourself standing on the right side of it Returns the values of the nodes you can see all that from top to bottom so let's see the example so you are given one two three five four and the output is one three four because um one and three and four is located on the right side of each level like this and this so that's why um output is one three four in this case okay so let me explain with this example one two three five four and the two sort of this question I use DQ and initialize a root node so one and then so I Traverse with like a breast fast charge like this so one two three five four and so that the um every time when we finish the looping in each level so last value should be a right side most right side value so let's begin first of all um we use we find one we pop one and then the first level has and there is a one node in the first level so that means this one is the most right value so that's why I put one to result variable and then so but before that um we check the uh its children so one has a left child and the right child and then we have to tell us like from left to right so first of all other two till day two and then after that three then put the one into result variable and then next iterations should be two and three so second level and first of all pop the 2 from day two and then check its children and left side there's no child and the right side and two five there's a five so out of five two thank you and then pop the three from DQ and this is a most right value in the second level so before are the three into result variable take its child so there's no child on the left and there is a child on the right side so other four to thank you and then other three to result variable and the next reiterate through sub level and first of all take five from dayq and there's no child so we don't add anything to thank you and uh pop 4 and then check the its children but there's no children here so we don't add anything but 4 is the most light value on the in the third level so add 4 to result variable then we visit all nodes in the tree so that's why uh output should be a one three four in this case so okay um but somebody wondering how we can find the most right value but I'll show you how to write a code and I'll explain later so that is a basic idea to solve this question so with that being said let's get into the code okay so let's write the code first of all initialize the result variable with empty list and initialize Q equal collections dot DQ and Q dot append and then absolute node and start traversing wire Q and the lights side P colon on and start robusting in each level so four underscore in range length of Q and then pop left most left node from DQ so node equal Q Dot top left and then if uh there's an old in that case are the right side um no update right side with current node um and then add left child to get you node lift and then append node.right so because we have to node.right so because we have to node.right so because we have to Traverse from left to right so left another must be fast and uh so we update right side with current value here because um in the end so this so we pop the node from left to light so last node should be uh most right node so that's why we don't have to check anything just uh if there is a node just a update the right side with current node so that when we finish the this for Loop in certain level we have most left node in right side variable so after that if light side has node in that case that must be a most light node in the current level so after that result are banned right side dot bar and actually that's it after that just return result variable yeah so let me submit it yeah looks good and the time complexity of this solution should be a order of um n uh linear time bit so because we have to visit all nodes in the tree so that's why our linear time order of N and the space complexity is also a single order of n because uh we have to add all nodes into your thank you yeah so let me summarize step by step algorithm this is a step-by-step algorithm this is a step-by-step algorithm this is a step-by-step algorithm of binary tree right side view step one initialize result variable with empty list and thank you with root node step two start traversing with breastfast search from left to right step one initialize the right side variable with no step two if there is a node update right side value with current node and the other left and the right child to date you step 3 if right side variable is not null then add value to result variable that's it I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Binary Tree Right Side View
|
binary-tree-right-side-view
|
Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_.
**Example 1:**
**Input:** root = \[1,2,3,null,5,null,4\]
**Output:** \[1,3,4\]
**Example 2:**
**Input:** root = \[1,null,3\]
**Output:** \[1,3\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
116,545
|
941 |
Hello Everyone, the first number of the code we are going to discuss today is the name of Nine Four One Problem: Lift and Carry. Problem: Lift and Carry. Problem: Lift and Carry. What is there in it is that we have been given an egg and I want to tell you that whether we set the mountain or not, how is this mountain? And then something like this happens to them, okay, so tell us what I understand, first of all, you will be in such a crazy type, then attend a tissue, why will the hair come down in the office, so let us check this and tell. This is the type of mine that will not be used, less want to three, takes increasing traffic point time, if we see want to three is big field work, okay, then we have to check that first of all, this previous should be free, hence it should be decreasing. It must be that he is a young man and you have to pay attention to this, he is a little subscribed, he has melted, he is looting, he has got the forgiveness of readers, remember, if there was delivery of this trick mobile, then the guy would be someone like this, that is, there is no contact, it is okay, he should bring 100, that is why it should be so. The degree should be 409 plus, if they do then what will happen to me? First of all, we will remember that first of all we have to get up in this previous increasing, a German will get the pick Raju, then from there we will write through this letter, so here our Velvet Mountain is theirs. The function is that we told the web that it is mountain that it has looted the ad, what is this, I took the end and finally and see here exactly ₹ 2 was laxed and what are the money doing exactly ₹ 2 was laxed and what are the money doing exactly ₹ 2 was laxed and what are the money doing Ayurvedic districts come that West Village Boys High School Plus it means that if mine is 12321, then I will try to check from here and till where I go, I will stay only here instead of her staying from here to here, she will do it first because I will do Agarwal Secretary, okay if the high will stay only from here to here. Don't rob me of issues and diversity elements, that's why from here till here, what have we seen that if the good limit is if and if it is smaller than this, the soldiers with the IS A plus fast are the big ones ahead of them, by the way, this is the phone if This is a small one, what can you do with it, now let the person come and get it bandaged, go to the e-mail bandaged, go to the e-mail bandaged, go to the e-mail and as soon as this condition is there, Falguni's method will decide here whether this is small of mine, is it the movie next to where? What will this do, this prescription will go and will remain to be collided in this manner, you will see that this one is smaller or if you do not have the one next to you, then you will get more of this. Whenever Bells cigarette will be used, will it take from everyone and one and a half cigarette will come to you which will show it to IS intact and Kirti. Because breakup is the first wind, first we will check that it is small, the turtle had said that this pick of the boys was the biggest, then after that, due to some big reason, Omega got voted in this war like situation, it will come out of the people, now here we have a condition. For farming by taking this which we could write cut like this for pick lecture above b b0ht subscribe yourself and last date could not be seen player president city only acid is 12345 so what is there in it where is the pick value be presented here The speed of liquid values will come. Okay, so the same person is saying speed of liquid values will come. Okay, so the same person is saying speed of liquid values will come. Okay, so the same person is saying that for this case, the key value cannot be started only. The pickers were also told last. Who did the above and return the call to us? This is a closed loop, you are tricked. Tell me where is it and here I will check, then again zero and last cannot take you, what does this mean that the stigma will be in the middle, so what are we doing, especially the form is running from behind and it is watching and where. Used to go just till first we will take here and stand this B and check till the back and bottom and saw that if the layer of I you find this Maruti Chahal-pahal last flat of I you find this Maruti Chahal-pahal last flat of I you find this Maruti Chahal-pahal last flat owner ok what is this small meaning it should be from its dominant - Bante should be from its dominant - Bante should be from its dominant - Bante Yeh - Me, it is small, the party has Yeh - Me, it is small, the party has Yeh - Me, it is small, the party has moved ahead, get up, okay, if the partition is not subscribed in the middle, then return the force, we submit it, ILO, this portion of ours is cleared, if Koirala is there, then comment. Please share in the box, you will get commission on this side so that
|
Valid Mountain Array
|
sort-array-by-parity
|
Given an array of integers `arr`, return _`true` if and only if it is a valid mountain array_.
Recall that arr is a mountain array if and only if:
* `arr.length >= 3`
* There exists some `i` with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
* `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`
**Example 1:**
**Input:** arr = \[2,1\]
**Output:** false
**Example 2:**
**Input:** arr = \[3,5,5\]
**Output:** false
**Example 3:**
**Input:** arr = \[0,3,2,1\]
**Output:** true
**Constraints:**
* `1 <= arr.length <= 104`
* `0 <= arr[i] <= 104`
| null |
Array,Two Pointers,Sorting
|
Easy
|
2283,2327
|
1,359 |
hello everyone welcome back here is Vanessa and today we are diving deep into lead code daily challenge count overall its pickup and delivery option and we are going to explore not one Note 2 but three different methods to solve it so let's dive in all right so the game is S4 uh it's say we have an order and each with a pickup and a delivery and we are going to find all the valid sequence ensuring each delivery for its pickup so sound fun run but first let's also look at constraints so our n can range between 1 and 500. so that's why we need to Output it as modulo 10 to the power of 9 plus 7. so let's look at example when n is 1 this is our base case and if you have just one order you have only one sequence so it's pick up first order and then deliver it and voila so it should output one and when n is 2 now you get a multiple option to arrange the pickup and the delivery so as you can see we can have different approaches so n is two so output is 6 and for example we can have pickup one pick up two delivery one a delivery two so it's one option but we can have also uh mixed so pick up one uh delivery one pick up two and then delivery two so as you can see uh yeah and we can have also four more and total is a sixth arrangement so now when we understand the task let's dive into understanding how we can solve it so we will start with dynamic programming so DP so okay let's dive deep into the first method it's dynamic programming and the first thing we have to do is initialize a variable called count to one but y1 you might ask imagine you have a single order just one so how many sequence can you make out of it the answer is one as an example so you pick up the order and then deliver it so that's your only option so count starts off as one to capture this base case and this is our foundation and the core Stone upon which we will build entire solution so uh let me implement it so we will also have a modular as our helper and then yeah count one and four I in range 2 to n plus one count equal count times two times I minus 1. times I modulo on the law and to return account so really simple implementation uh so let's understand so we got our base case down and what's next iteration so we will iterate from 2 up to n but Y starts at two because we have already got the base case for n equals one covered and let's get into the uh our transition function so for each order I you have two action a pickup and a delivery and in total for I order you have two I actions so we need to figure out where to place this in the sequence so here is the kicker when you add a new pickup for the it order you have 2i minus one places to put it y minus one well you got to save a spot for its corresponding delivery right so for the delivery you have I option because it can go anywhere after its corresponding pickup and the update rule here is our main part so it's count equal count times 2i minus 1 times I and this formula consider all the new possibility including uh by the height order and yeah and so after this we simply return our calculated count variable so now let's test our first implementation it's yeah all good for uh test cases two six so let's submit it for unsynthesis cases to verify it's working so yeah it's working it took uh 44 milliseconds I think I have even faster we can uh yeah rerun it so as you can see now in the second run we have a runtime of 36 milliseconds beating eighty two percent all good so let's go to description uh we can yeah erase it and there we have it dynamic programming elegant python function so now recursion with memorization so uh let's start with also placing our helper and also what we will need is our memo okay so now let's shift to memorization in recursion so first thing first we create a memorization dictionary and this isn't just any dictionary it's our secret vault the store answer to sub problems so we don't have to solve them over and over again so and the base case is like the root of our three so four n equals one so how many sequence can we have just one so pick up and delivery and that's it so we said that uh as our base case so yeah let's do this if n equals one return one yeah and then we have recursive call so now comes the head of our method so recursion but we are doing a recursion with a Twist so before making a recursion call we peek into our memo dictionary and if already has the answer boom we take it so no more calculation so it's quite optimal uh so yeah let's implement it as well so if and self memo and then return memo and now count will be self count order and minus 1 times 2 times n minus 1 times n modulo mode so and of course if the answer isn't in memo we calculate it just like we did in the dynamic programming method so same logic but here is the crucial part we store this newly calculated answer in our memo so for futurists so we are using it yeah so self memo and will be count and final step you can guess this return account okay so this is our implementation uh let's run it to verify it's working for yeah for uh or memorization and yeah and recursion memo so comment orders and it's filled with our answer and for the initial n that we started with memo n we have a final answer so uh let's run it or submit it yeah so as you can see it also past unsynthesis cases 35 milliseconds with runtime and yeah beating 23 with respect to memory so with respect to memory maybe not so fast so let's look at the description so yeah solve memo we pick a account and yeah return count okay all good so let's reset it one more time and yeah so I could uh probably not reset everything so mods okay so this is our uh modular Helper and last but not least mathematical approach so uh math is a secret tunnel that takes your uh directly to the treasure so our final answer so for this method we will use combinatorial math and first we calculate 2N power and also two to the power of n so two and factorial and 2 power F and so let's implement it so two and Factor so factorial 2 times n or low and 2 power n will be power and mod and now the last word so return 2 and factorial times power 2 power n minus one mode so notice we are using the module operation to keep our number from exploding so always a good practice and finally we use this to directly find the number of valid sequences so just yeah Formula 2 and factorial times power of 2 power n minus 1 and model so let's run it and see if it's working yeah so uh all good so we can also yeah submit it just to have a look so it took 40 four milliseconds but I think like test cases sometimes differ yeah as you can see just by re-running it with a bit see just by re-running it with a bit see just by re-running it with a bit even yeah 92 percent with respect to memory but those are not a significant uh changes so yeah our last implementation and so it's power and minus one of model so there you have it we have solve it and with different free approaches uh so free approaches to tackle a single problem so I hope you found this session as through link as I did but wait there is more in the description you can find the source code for all three approaches in different languages like go or asked and much more so check it if python is not your core language and if you like this video smash the like button share it with your friends and don't forget to subscribe for more exciting coding Adventure machine learning tutorials challenges and much more programming and text related and yeah so see you next time keep practicing stay motivated and happy coding
|
Count All Valid Pickup and Delivery Options
|
circular-permutation-in-binary-representation
|
Given `n` orders, each order consist in pickup and delivery services.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
Since the answer may be too large, return it modulo 10^9 + 7.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation:** Unique order (P1, D1), Delivery 1 always is after of Pickup 1.
**Example 2:**
**Input:** n = 2
**Output:** 6
**Explanation:** All possible orders:
(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.
**Example 3:**
**Input:** n = 3
**Output:** 90
**Constraints:**
* `1 <= n <= 500`
Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that : p\[0\] = start, p\[i\] and p\[i+1\] differ by only one bit for all 0 <= i < 2^n - 1.
|
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
|
Math,Backtracking,Bit Manipulation
|
Medium
| null |
1,652 |
Al so this question is fuse the bomb so you are given a circular array and integer K so K can be greater less than or equal so if K is greater you want to add some of the next K numbers if K is less than zero you want to add the previous K number if k equal zero return zero and then you want to return the new array okay so yeah this is somehow challenge for sure so for the positive number that will be straightforward so if we just so I represent the current index J represent the index between one all the way to K right so I + J K right so I + J K right so I + J there will be the next index but at some point over here at some point you want to starting from zero right so you want to say m by what M by earning is the L of the code so this is straightforward right um for the next um I mean a positive k for the uh next K number how about the previous K you want to go left but if you want to go left you want to make sure you don't want to um have a negative value inside it uh in Array right so this is going to be trick so n is what n is the greatest um it didn't actually talk about a logic here but what n is always the largest number uh for Index right and K is always what K is always uh base index one if have k equal to Z you return zero if k equal to one you want to you know add the value I'm sorry not add get the next value on the right by one only and then um and then you want to know like um what is your current position for I now if you want to get a sum for the previous K number you want to keep your spot right here right and you want to add the two previous guy which is going to be 93 so it's going to be I uh sorry m + IUS J is going to be I uh sorry m + IUS J is going to be I uh sorry m + IUS J is going to be starting from1 all the way to K and let's think about this equal to four right 4 plus what current index is actually Zero 4 + uh 0 current index is actually Zero 4 + uh 0 current index is actually Zero 4 + uh 0 = to 4 minus starting from 1 so this = to 4 minus starting from 1 so this = to 4 minus starting from 1 so this represent what this represent three right um yeah 0 1 2 3 yes this is correct and then let's look at this if you have the next one it's going to be -2 right so it's going to be 4 + 0 - 2 -2 right so it's going to be 4 + 0 - 2 -2 right so it's going to be 4 + 0 - 2 going to be 2 so 9 + 3 okay this is going to be 2 so 9 + 3 okay this is going to be 2 so 9 + 3 okay this is correct but what happened if you are at this one yes at this spot so your I is what your I is 0 1 2 3 so your I is three your K starting from one right minus one you're all of bound right 7 - minus one you're all of bound right 7 - minus one you're all of bound right 7 - 6 what do you mean 7 - 6 7 - 6 is out of 6 what do you mean 7 - 6 7 - 6 is out of 6 what do you mean 7 - 6 7 - 6 is out of bound so this is why we always want to M by K uh sorry M and you want to keep your index in boundary so Len you will always forget on the first trial but you want to keep your index in boundary more by always uh always done mass and make sure you know how to uh get the current value IND that's for the negative K so let's see so in result equal to new in how many size to the lens size so if k equal to zero right you want to return result if K is greater than zero first thing you want to Traverse every single element inside the what inside the result index and then you want to make sure you're starting from one and all the way to K right and result a i is plus equal code and then it's going to be I + J code and then it's going to be I + J code and then it's going to be I + J M by uh L which is going to be result L doesn't matter you can say an initial n as well doesn't matter up to you so else is going to be the negative value right and then J is starting from1 J less than equal to K and then j++ j++ j++ so you started from Jal to1 and then you increment your J which mean you want to say1 * say1 * say1 * K so K will be um where is my K oh sorry uh Jal one and you want to Traverse um all the way to negative K right and then we will uh walk backward so this is cod and then this will be minus and then this will be the total length plus I minus J represent this boundary and I mean don't look at this you think about your J is always negative value right I mean negative J right but in the folder you are keep it as positive and this is how you break right and you will return result in this case so yes so time is space is all of n representing the size of code length of code and the time is going to be all of n times all of K so it's going to be n k worst case n k and spaces all of n okay so uh this is a tricky part I mean if you understand uh if you don't understand draw on the paper or you can ask question in a comment I'll try to explain but this is pretty uh pretty neat so you get your current index minus J represent positive but you will Traverse in a negative uh negative value at the end you know you want to break out this guy right and you don't want to modify your K right so this is how we make sure this is a positive triers but we actually minus J minus K all right so um how about we make some break point so let's look at the buer okay let's look at this one and then we'll look at the other one all right so you can look at the windows on the left all right and next one is going be test case this guy start plugging all right you can pause the video doesn't matter all right and the zero I mean we don't need to test a zero is going to be this guy all right so hope you get it and apologize I mean it's going to be hard for me to explain that what is the logic behind this you just have to know it like no one can actually convince you but think about this like what is the negative traversal in this pattern you know the negative traversal you know make sure it's a circular AR Ray right all right so I'll see you next time and good love bye
|
Defuse the Bomb
|
minimum-suffix-flips
|
You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **next** `k` numbers.
* If `k < 0`, replace the `ith` number with the sum of the **previous** `k` numbers.
* If `k == 0`, replace the `ith` number with `0`.
As `code` is circular, the next element of `code[n-1]` is `code[0]`, and the previous element of `code[0]` is `code[n-1]`.
Given the **circular** array `code` and an integer key `k`, return _the decrypted code to defuse the bomb_!
**Example 1:**
**Input:** code = \[5,7,1,4\], k = 3
**Output:** \[12,10,16,13\]
**Explanation:** Each number is replaced by the sum of the next 3 numbers. The decrypted code is \[7+1+4, 1+4+5, 4+5+7, 5+7+1\]. Notice that the numbers wrap around.
**Example 2:**
**Input:** code = \[1,2,3,4\], k = 0
**Output:** \[0,0,0,0\]
**Explanation:** When k is zero, the numbers are replaced by 0.
**Example 3:**
**Input:** code = \[2,4,9,3\], k = -2
**Output:** \[12,5,6,13\]
**Explanation:** The decrypted code is \[3+9, 2+3, 4+2, 9+4\]. Notice that the numbers wrap around again. If k is negative, the sum is of the **previous** numbers.
**Constraints:**
* `n == code.length`
* `1 <= n <= 100`
* `1 <= code[i] <= 100`
* `-(n - 1) <= k <= n - 1`
|
Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left.
|
String,Greedy
|
Medium
| null |
9 |
okay this is leak code 9 in javascript palindrome number so palindrome as they say is something that's the same backwards as forwards so i'll show you a couple of ways to do this uh the way i solve this so first i'm going to start this by setting reversed to this input x and all i'm going to do here is i'm going to convert it to a string then i'm going to split it then i'm going to reverse it and then i'm going to join it so this is going to this is how you uh get a string and you reverse the string so if i console log this give it a second here i want to run code so it's giving me this one two one this is a string you can see this if i do a type of and run this again it's going to tell me that this is a string oh didn't like that well that's because i'm missing the parents here let's run this one more time there we go so it's a string right now so i now need to take this reverse string and compare it to the input x so how i can do that i can simply take extra string and then just compare it see if it's equal to this reversed and if i return that it'll give me a true or false so let's run this and if i hit submit there we go that works so that's way one let's do uh let's do another way i'm just going to comment that out make some more room here let's paste that back in get rid of all this there so another way to do this is to start essentially loop through this input number and then just compare uh the result of that well you want to loop through it and build up a value and then you take uh that value that you've built up and has been that has been reversed and then you compare it so let's i'll show you how to do that or how i did it reversed string okay so we're going to start by declaring an empty string here and then we're going to say x string so the string version of x is equal x to string okay and we're going to do a for loop we're going to let i of this x string so this is now a string version of x of this input a string version of 121 and we're going to loop through the string version of 121 and what we're going to do is we're going to take this reversed uh string that starts out as an empty string here and all we're going to do is take every letter and add on added on to uh the reverse string so if that didn't quite make sense my explanation reversed that didn't quite make sense when you're looping through this uh where is this so let x just ring so right now your x string is equal to one let's do one two three that makes maybe it's makes a little more sense so what this would be on the first pass on pass one uh we're going to take reverse string which is an empty string and we're going to add on i so that would be 1. and then for the second pass we're going to take on uh we're going to take i and then we're going to add on reverse string oh my explanation here was backwards at first so we're actually taking one plus reverse string now we're going to take uh nope i think that was right and then we're going to take two plus one like that remember these are strings they're not actually doing addition so that would actually equal 2 1 and then we're going to take on the last pass we would add three to that this remember this is strings again so now we'd have three two one so might be easier to show that by console logging there we go so one two one oh my input is one two one but you could see that's one two one so this hair is now technically reversed so all we need to do let's go outside the for loop so all we need to do now is just repair uh compare this reverse string to the stringified version of x so compare them and then i'll give a true or false and then we can just return that and success so those are a couple of ways to do that let's see if i can't get clean this up if you want to look at the whole thing there we go so way one at the top way too at the bottom hope you enjoyed appreciate the like and the subs
|
Palindrome Number
|
palindrome-number
|
Given an integer `x`, return `true` _if_ `x` _is a_ _**palindrome**__, and_ `false` _otherwise_.
**Example 1:**
**Input:** x = 121
**Output:** true
**Explanation:** 121 reads as 121 from left to right and from right to left.
**Example 2:**
**Input:** x = -121
**Output:** false
**Explanation:** From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
**Example 3:**
**Input:** x = 10
**Output:** false
**Explanation:** Reads 01 from right to left. Therefore it is not a palindrome.
**Constraints:**
* `-231 <= x <= 231 - 1`
**Follow up:** Could you solve it without converting the integer to a string?
|
Beware of overflow when you reverse the integer.
|
Math
|
Easy
|
234,1375
|
58 |
Hello Everyone Welcome To My Channel It's All The Problem Length of Clans Words For This Is Very Easy Problem And Straightforward Suryavanshi Open Soft And Terrific Subscribe Length Of The Last Word Meaning Word In Root From Left To Right In Distic Last But Not Least 1000 maximum subscribe button the return of the solution class first of all will be split into a string into word subscribe to i anil jandu space character and when will return first vijay keyword length from this zil written word dot live wall - 1the subscribe withdraw from Distic subscribe will remove all subscribe to that and in the east room desh will take a length of this string and attractive from first to last index of speech during middle subscribe disposition and subscribe solution for this problem solving the first of all the best to trim also string so trim setting light bill check second to in this page will continuously co don't know how will the minister will just this district compare the character airtel.co.in minus one is it is spain we can do character airtel.co.in minus one is it is spain we can do character airtel.co.in minus one is it is spain we can do subscribe so let's see that bihar country Spring So Let's Meeting Is ABCD Space And Subscribe The Channel And Subscribe To Subscribe Our Prime Minister Subject Character Nowhere Ball Setting On In Greater - 110 Subscribe And Setting On In Greater - 110 Subscribe And Setting On In Greater - 110 Subscribe And Share It Is This Time Is Not To Speak On this will be continuously updated on - IF One Riddle in Last Date of the - IF One Riddle in Last Date of the - IF One Riddle in Last Date of the Last Character Which is This - The Amazing Place Without Using Any Time and Place in the Third Day 136 Accepted Norms The Time Complexity of Dissolution But in String in Internal Storage Se 0.5 Widow String in Internal Storage Se 0.5 Widow String in Internal Storage Se 0.5 Widow of Spring in Your Language Se subscribe and subscribe the Channel subscribe thanks for watching this
|
Length of Last Word
|
length-of-last-word
|
Given a string `s` consisting of words and spaces, return _the length of the **last** word in the string._
A **word** is a maximal substring consisting of non-space characters only.
**Example 1:**
**Input:** s = "Hello World "
**Output:** 5
**Explanation:** The last word is "World " with length 5.
**Example 2:**
**Input:** s = " fly me to the moon "
**Output:** 4
**Explanation:** The last word is "moon " with length 4.
**Example 3:**
**Input:** s = "luffy is still joyboy "
**Output:** 6
**Explanation:** The last word is "joyboy " with length 6.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of only English letters and spaces `' '`.
* There will be at least one word in `s`.
| null |
String
|
Easy
| null |
162 |
foreign problem and the problem's name is find Peak element in this question we are given an array called nums and we have to find a peak element and return its index and it says it might be possible that there are multiple Peaks inside the array written any one of the Peaks so how do you identify element is a peak and enter not in this example you are given an array one two three one the peak element is 3 because all the elements to the left of this are less than that and all the elements to the right of it are also less than that now let's take a look at this example and see how this question can be solved I've taken the same examples I've given us this is the input array noun and we have to return the index position of the peak element we can solve this question using binary search so this question is very similar to Peak index in a mountain array I've already solved that question please take a look at that tweet I'll leave a link to that video in the description box below or you can also click on the top right corner icard to find that video so similar to that question we can solve this question using binary search so like always in a binary search algorithm we're going to declare two pointers the left pointer will be starting at the beginning and the right pointer is going to start at the end the left pointer is going to start from left to right and the right pointer is going to start from right to left this for Loop will meet until left is always less than right once they meet we can end the iteration so inside this while loop we should always find a mid element mid can be found out with this formula left plus right minus left by 2 left is pointing at zero and right is pointing at 3 minus 0 by 2 3 by 2 is 1.5 which will take 1 so by 2 3 by 2 is 1.5 which will take 1 so by 2 3 by 2 is 1.5 which will take 1 so make this pointing here now we have to check if the element at Mid is less than the element at Mid plus 1 if 2 is less than 3 it means that we have to decrease our search Space by shifting left to Mid plus 1 since this element is greater than 1 we'll never find our answer in this part of the array so we are shifting our search Space by reducing it into this part of the array so left will be moved to Mid plus 1 so left is pointing here and now we have to calculate and mid again so with this 2 let's move Metro 2 so mid is also pointing there now mid is pointing at 2 and we have to check if element at Mid is less than the element at Mid plus 1 3 is greater than 1 so this condition fails so whenever that condition fails we have to reduce our search space we have to assign right to Mid now we cannot move to the next iteration because left should be less than right but here it is equal so once these two pointers meet or these two pointers cross each other we can end the iteration and we return the index of the left pointer is 2 will be returned as output now let's take a look at the code coming to the functions I've given us this is the function name and this is the input array nums and the return type is an integer so you have to return an integer as the output representing the index position of the peak element as I've said let us declare the left index pointing at 0 that is the beginning of the array and the right index will be pointing at the end of the array now we run a while loop until left is less than right once these two pointers meet across each other we end the iteration so the first step is to find the mid is calculated with left plus right minus left by 2 so this is used to avoid overflow condition you can also use left plus right by 2 and now we have to reduce the search space if the element at Mid is less than the element at Mid plus 1 it means that you have to search in the right part of the mid so we increment left to Mid plus 1 and in the else block it means that the element at Mid is greater than the element at Mid plus 1 so else block will be executed meaning we have to search in the left part of mid so we move right to Mid so this will reduce our search space to the left of mid so this will happen until both the pointers meet or cross each other because left is moving from left to right and right is moving from right to left and when you break the loop you return the left pointer that will give you the peak index so the time complexity of this approach is O of log n and the space complexity is constant of 1 because we are not using any extra space to solve this equation that's it guys thank you for watching and I'll see you in the next video thank you
|
Find Peak Element
|
find-peak-element
|
A peak element is an element that is strictly greater than its neighbors.
Given a **0-indexed** integer array `nums`, find a peak element, and return its index. If the array contains multiple peaks, return the index to **any of the peaks**.
You may imagine that `nums[-1] = nums[n] = -∞`. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in `O(log n)` time.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** 2
**Explanation:** 3 is a peak element and your function should return the index number 2.
**Example 2:**
**Input:** nums = \[1,2,1,3,5,6,4\]
**Output:** 5
**Explanation:** Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
**Constraints:**
* `1 <= nums.length <= 1000`
* `-231 <= nums[i] <= 231 - 1`
* `nums[i] != nums[i + 1]` for all valid `i`.
| null |
Array,Binary Search
|
Medium
|
882,2047,2273,2316
|
1,534 |
hi guys so we will do the question count good triplets so this is a easy level question and given an array of integers arr and three integers abc you need to find the number of plates so what is meant by voter plates per triplet a r of i a r of j a r of k is good if the following conditions hold true i and j i j and k are less to the length of the array and the absolute difference of array of i minus array of j is less than equal to a and the absolute difference of the jth and the kth element is less than equal to b and the absolute difference of ith and the kth element is less than equal to c so we need to uh return the number of good triplets right so basically we are given this array and these three integers we need to count the number of triplets are like three elements from the array such that these given conditions hold true so let's look at the constraints first so um what we are given is like a size less greater than equal to 3 and less than equal to 100 complexity so let's look at absolutely foreign equal to um is and right so i hope this is clear to everyone
|
Count Good Triplets
|
minimum-number-of-frogs-croaking
|
Given an array of integers `arr`, and three integers `a`, `b` and `c`. You need to find the number of good triplets.
A triplet `(arr[i], arr[j], arr[k])` is **good** if the following conditions are true:
* `0 <= i < j < k < arr.length`
* `|arr[i] - arr[j]| <= a`
* `|arr[j] - arr[k]| <= b`
* `|arr[i] - arr[k]| <= c`
Where `|x|` denotes the absolute value of `x`.
Return _the number of good triplets_.
**Example 1:**
**Input:** arr = \[3,0,1,1,9,7\], a = 7, b = 2, c = 3
**Output:** 4
**Explanation:** There are 4 good triplets: \[(3,0,1), (3,0,1), (3,1,1), (0,1,1)\].
**Example 2:**
**Input:** arr = \[1,1,2,2,3\], a = 0, b = 0, c = 1
**Output:** 0
**Explanation:** No triplet satisfies all conditions.
**Constraints:**
* `3 <= arr.length <= 100`
* `0 <= arr[i] <= 1000`
* `0 <= a, b, c <= 1000`
|
keep the frequency of all characters from "croak" using a hashmap. For each character in the given string, greedily match it to a possible "croak".
|
String,Counting
|
Medium
| null |
1,312 |
hi guys good morning welcome back to the next video it's a pretty easy problem if you have done the last lectures of our DP or the programs of RDP I just recommend please try this problem by yourself it's actually an easy problem but let's quickly jump to the problem statement itself it says meme session steps to make a string palindrome okay cool we know what's a palindrome we know what's a string uh and all that stuff a string s is given in one step you can insert any character at any index of the string which means insertion operation at an index is allowed to you cool written the minimum number of steps my words minimum number of steps which means minimum number of insertion of characters into that string to make that string S as a palindrome cool uh it just says what's a palindrome we know what's a palindrome where start and end the same which means it reads scene forwards and backwards like this cool uh let's say example pretty quickly we have the string zzaz matched ZZ man last a itself is at the mid okay it's already a palindrome so minimum insertions required are zero because no insertion is required as such to make it a parallel because it's already a palindrome cool let's see the next example which is m b a d m and m matched cool no worries it's gone b and b o b is not there cool I just took it as the consideration B is not there so I need to match B which means I need to add B for sure okay I will add a b I'll add a b uh d o d is not there I added a d cool and a is at the mid cool A is for sure it's of itself for it a parallel so I made it as m d m b d a d b m in which this D and this B I added and for sure it's the minimum I have to add because for this B no pair was there for this D no pair was there so I need to make the add a palindrome let's move on next one a lead code for sure it's a big example but that's it for this L nothing is there so add a l for this E I have a e for this next E I have nothing so let's say for this T I had nothing let's add a t let's put a d here for this C I have nothing so add a c for this oh I had nothing to add a o and for this D in total I have five operations which is o c t e l that's it that is the only thing you have to do if we look at this very carefully then you can easily see what is happening you have m b a d m um first let's have a look what I needed I just went on and see okay M and M itself became palindrome B was not making or was not included in the palindrome so I have to make Okay add another way because B was there I can only insert I cannot delete anything I can only insert so for this B I need to add something so added a B for this D I had to add something so I added a d for this a okay it's in mid so nothing required you saw what happened I just went on and checked okay what is the actual palindrome like in this m b a d m a it was already making a palindrome while the characters B and D were not contributing in the parent room so I just went and asked them okay if you're not contributing what if I just add a duplicate of yours in the respective location because I know I can add it any index I want any index so I can afford this B I can add another B at any index whatsoever is comfortable for this B to make it a parent room and it's the only thing which you have to do which means I just find okay what is the remaining number of pairs which are not contributing in my palindrome and thus I'll just make a pair for them for this B I add another B for this D I add another D because I can add at any index possible and it's the whole thing which I have to do which means I'll just grab the palindrome existing palindrome and then what is whatever is the remaining which means palindrome I have got m a m i have got remaining thing is actually nothing but B and D simple as that remaining thing is B and D so it is what I have to add an extra thing and when I say okay I'll end room as in the problem statement itself it's saying oh I have to do minimum number of steps additions which means I want this part as minimum as possible which means the remaining number of elements which are being added if I have this palindrome M A and M for sure M and M is also a parindrome but still I'll take the longest palindrome because I want the remaining numbers to be inserted as new as possible because it is saying mere number of steps thus I take the longest parent room but as we know okay longest battle but our longest parent room what like longest parent room uh consecutive or we can take anything right anything which means subsequence so I can grab a subsequence of string in this particular string s to make a longest palindrome which means I need to grab the longest palindromic substring I have the string I have the longest palotomic substring which means I have the string m b d m I have the longest paranormal substring which is mam remaining characters are BND for this B and D I need to add B and D because for this B I'll add another B for this d i light another D and it is adding two more in sessions to actually make it a palindrome and that's the answer which means you will find the longest palindromic subsequence you will find okay what's the length of the longest polynomial subsequence it is three what is the length of the string itself it is five so I have two extra tests which are not contributing in the palindrome right now so for these two characters I need to add another two characters because it is right now there but for them I need to add another two to actually make it a palindrome and that's the reason my answer is 2. and now my sub task is to find the longest palindromic subsequence length because it is I can easily find it's a string dot length but it is the main question now so I have reduced my bigger problem to a smaller problem which means finding the longest paranormal subsequence and if you don't know we have discussed the same problem in very detailed we went from recursion to top down to bottom up to bop term optimized code which means space is O of n so I highly recommend it will be down in description cards and Screen everywhere so just go and have a look at this problem and after that we will be able to solve this full problem because the sub problem is actually a new other problem the code is very simple it is the exact same code I discussed in this video it is the most optimized code we discuss every of those approaches so you can just have a look and ultimately I'm just calling s dot length minus my LPS which means longest palindromic string dot like of that particular string s which will give me the LPS length and that's pretty much it time complexity same as that of LPS which means of n for a uh for the whole time and oh sorry o of n Square for the time and O of n for the space and it's the same as the LPS I highly recommend to watch the LPS video after this and rest of the codes for C plus Java and python are down below I hope that you guys will watch LPS and I hope guys that you guys got okay how we think of the bigger problem then we'll drop to a smaller problem and find the solution that's all from me goodbye take care foreign
|
Minimum Insertion Steps to Make a String Palindrome
|
count-artifacts-that-can-be-extracted
|
Given a string `s`. In one step you can insert any character at any index of the string.
Return _the minimum number of steps_ to make `s` palindrome.
A **Palindrome String** is one that reads the same backward as well as forward.
**Example 1:**
**Input:** s = "zzazz "
**Output:** 0
**Explanation:** The string "zzazz " is already palindrome we do not need any insertions.
**Example 2:**
**Input:** s = "mbadm "
**Output:** 2
**Explanation:** String can be "mbdadbm " or "mdbabdm ".
**Example 3:**
**Input:** s = "leetcode "
**Output:** 5
**Explanation:** Inserting 5 characters the string becomes "leetcodocteel ".
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of lowercase English letters.
|
Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array.
|
Array,Hash Table,Simulation
|
Medium
|
221
|
797 |
everyone in this video let's go to question 797 all paths from source to Target only code this is part of our blind 75 list of questions so let's begin in this question we're given a directed acyclic graph dag of endnodes labeled 0 to n minus 1 and you want to find all possible paths from node 0 to node n minus 1 and return them in any order the graph is given as follows where graphite I is a list of all of the nodes you can visit from node I basically there's a directed Edge you can think of this as like an adjacency list right representation okay so before we even start this problem let's take a look at the wording here right like find all possible paths whenever you see something like that right like find all possible or generate all possible combinations all possible permutations Etc when you have an exhaustive search like that it's often good to use recursion but not only that backtracking and we've done this in many of our other problems like subsets permutations combination some Etc but whenever you see like generate all or find all backtracking is a good approach here and I don't want to just like say like all if you see all just generate a do backtracking like think about acquire it makes sense right because this question in itself is actually not that hard if you know like how to work with it so just take a look at the graph that we have over here and I'm actually going to show the paint version that I have okay ignore this like uh ignore this part right here that we have Okay so let's say like we start off at zero right so then what can we do or we can go through Zero's neighbor so we go through one and then we go through three right and then what well once we're at three we have nowhere else to go right so then we go back and then let's say from here like we have nothing so that's why I kind of added in this but let's say from three we go back to one so what are we doing we're backtracking back to one and then we go to four and then we go to three and then we backtrack to four and then again we backtrack to one and then we backtrack to zero and then we go to two and then we go to three and then maybe we backtrack the two maybe there's like another Edge that something like this maybe this is like something like five so we go here obviously these numbers are not correct because um it should be like zero to n minus one but yeah like hopefully you get the idea but notice how like we're going to the final location and then we're backtracking and seeing if there's anything else so that's kind of like why backtracking might make sense here and for all of these questions that we do like we have a general format that we like to follow right so we have a result variable we have our recursive call and then we return a result variable in the very end a result variable will be basically filled with all of the set of paths that we can form in the helper function so let's take a look at how we might want to do this right so the first thing I think we need to do is kind of the case where graph is empty well if graph is empty I don't know if this is like even valid but let's just assume it is then we return empty list right because there's basically no paths to form otherwise well let's just declare some variables here what is n will be the length of the graph right n will be the length of the graph that we have here what else okay so we're given graph in terms of something like this right but this is not really useful for us it'd be better if we can somehow represent this using like adjacency list so in Python it's very easy to create we just create a default dictionary where it's a dictionary that points to a list right so like every key points to a list and then we'll just go through the graph like so and then we'll do adjacency listed I is equal to graphite I so basically all this is going to be doing it will be mapping something like zero two one and two it'll be mapping one to something like three 2 will be mapped to 3 and then three we map to empty like this okay so now let's take a look at like how we might want to code in our helper function because the way you do this is it's just as you expect you would just go through this like one by one so you start off at zero we go to one and then it recurs we'll go to three and then we'll see there's nothing here so we'll backtrack there's nothing else here so we'll backtrack we'll go to two and then we'll go here and nothing more and then end so that's kind of like how we want to do this so let's take a look at like what we might want to pass in so as with like all of the problems our general format stays the same so always want to pass in the graph what else well we need to pass in the result right so this is like what we will add we need something else as well we need curve right we need to keep track of where we are so for example if I'm at zero then I'm at one here and I'm at three when he tracked this path right so that will be stored in Curve will be added to Res what else well we need our Json C list right we need to know like adjacency list what else well we need to know like our base condition is when we reach the final node well we need to know what the final node is so we can pass in something like n to represent our final node right so we have that now what else do we need well I don't know do we really need anything else if you think about it do we really need anything else I don't think we do in this case right because Kerr we can always find like the last element that we've added incur right we can just look at like current like minus one and we can check if that like it's equal to n so I don't really think like we need the like anything else here so maybe let's just go ahead and start with this and see where we can get at so let's take a look Okay so we can check if Kerr at minus one if we've just added in N minus one right like if we added in the N minus first um item if this is the case then we can add this curve to a res so we want to rest out of pen Cur and remember we always add in a copy when we're doing these types of questions and then we can just return and that's all there is to this curve and minus one this is like our last item that we've just added okay what else well if we didn't do that then occur initially it's just like this zero thing zero here right because initially like we always start with the zero so we're passing the zero here so now we need to know look now we need to know like the neighbors that we can visit so I can do four neighbor in adjacency list at correct minus one right so this will be the item I just added so it'll be adjacency list at zero which is just one and two and now this is like where backtracking comes into play so when you're exploring one you'll first add one to our list we add on the neighbor go to our helper function call and then simply we'll pop it just like so this is how we always do our backtracking so why do we pop it because when we are over here like let's say we go to the number three so at this point we have zero one four three well let's say there's another connection here maybe there's something like six right well I don't want to have that three like I don't want it to be zero one or three and then like six and then three right that doesn't make sense well we need to remove this three which is what we do in pop and then we do 0 1 4 6 and then three again so that's like why we pop it just what the subsets question or permutation question to understand why we need to pop it so we have that and then here what do we need to pass in we have graph rest Cur we've already adjusted here adjacency list we don't need to change but n here um again n does not need to change okay and that's actually I think pretty much all we need to do for this question so let's actually pass in what we need the res and the curves like an empty list adjacency list is something like this n we can pass in N here and what is actually n is the length of the graph so let's actually go ahead and try this out to see if we run into any problems okay so list index out of range so I wonder if it's possible oh yeah because I need to include some value here right so I need to include like the first value here so that's why we can refer to the last value so we can do something like this okay it passes so now let's go ahead and click submit and it also passes so perfect so again just to kind of explain like why we need to append and then pop it's because if we have something like our path is let's say 0 1 4 and then three right when we are at three and then we are like out of the loop essentially or not out of the loop we're basically done the function so we go back to this one well when we're over here we still have three as part of the list right simply because of how lists work in Python they persist even if you go back a recursive stack so here if we were to then go to six then we would have something like this which is not what we want we need to remove this three which is why we do the pop and then this is how we come by this Final Answer here so that's exactly what we're doing here and so this is how we do this question as for a time and space it's often like actually pretty hard to tell for these types of questions because when you generate like all types of paths you have to know like what are like the total number of paths you can generate in like an arbitrary type of graph so it's a little bit difficult to check here you can check in discuss if you want to learn more um but yeah as for time and space just check and discuss and that should be good okay thanks for watching
|
All Paths From Source to Target
|
rabbits-in-forest
|
Given a directed acyclic graph (**DAG**) of `n` nodes labeled from `0` to `n - 1`, find all possible paths from node `0` to node `n - 1` and return them in **any order**.
The graph is given as follows: `graph[i]` is a list of all nodes you can visit from node `i` (i.e., there is a directed edge from node `i` to node `graph[i][j]`).
**Example 1:**
**Input:** graph = \[\[1,2\],\[3\],\[3\],\[\]\]
**Output:** \[\[0,1,3\],\[0,2,3\]\]
**Explanation:** There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
**Example 2:**
**Input:** graph = \[\[4,3,1\],\[3,2,4\],\[3\],\[4\],\[\]\]
**Output:** \[\[0,4\],\[0,3,4\],\[0,1,3,4\],\[0,1,2,3,4\],\[0,1,4\]\]
**Constraints:**
* `n == graph.length`
* `2 <= n <= 15`
* `0 <= graph[i][j] < n`
* `graph[i][j] != i` (i.e., there will be no self-loops).
* All the elements of `graph[i]` are **unique**.
* The input graph is **guaranteed** to be a **DAG**.
| null |
Array,Hash Table,Math,Greedy
|
Medium
| null |
491 |
to day 28th of Jan lead Cod Challenge I hope all of you are in a great spirit and by the way this painting is made by me so I'll be sh I have created a new wall I've got my paintings framed and there is a very good surprise for all of you so stay tuned I'll be showing you something really interesting now let's focus back onto the problem the question that we have in today is non decreasing subsequences and the question says you are given an array of integers what do you need to identify the number of unique non decreasing subsequences that exist in this entire array with size greater than or equal to two so do you remember anything after reading this question the question itself gives you the hint when you have to count all possibilities we will go by the approach of backtracking and whenever I hear the word backtracking I get a big smile on my face because backtracking is something that we are masters of so the CES of coding decoded we know that we have a template that we use in all the backtracking questions and if you are new then this playlist is for you go through the first video backtracking template I have clearly explained how backtracking template actually works and we apply the same template to each and every question that has been listed over here and today as well we will apply the same concept of backtracking so I would urge you guys to try this question first this template first and then walk through today's question followed by if you need more practice then the ENT ire list is for you uh start walking through the video that I'm attaching in the description below and this is the backtracking template uh we will use this template again onto solving today's question it is nothing extraordinary it's a very simple concept and those who have mastered it in the past really stay happy with all the backtracking questions for those who are new let me just briefly explain how backtracking actually works backtracking is nothing fancy and extraordinary it's nothing but recursion with a tweak and The Tweak is the important concept of backtracking so let's walk through the solution and then we will try to map it to the example in the first go we have created a set and why set although the return type is a list because set will help us remove and handle duplica so we have created list a set of list of integers and when we'll be returning our answer we will return new AR list and this answer will be passed over there it will take care of casting this set into a list so remember AR list supports a method wherein you pass in a set to it and it will cast it into an array list now let's proceed ahead in the at the first statement I have initialized it to a new hash set and why hash set because we have set over here then we have written the DFS or the recursion method and this recursion method accepts three parameters the first one is your input array the second one is a the starting point where you are starting the input progression and the third one is the current state of your list so what is the current state of the list as we are processing the r we are adding elements onto it we are deleting elements onto it and this current list will actually take care of it so as remember only those list that are increasing or and non decreasing in nature rather non decreasing in nature will be added onto current list and how is this being taken care of I'll talk about it in the lat section but as soon as you find that the current RLS size happens to be greater than two that means we have found one subsequence what are we going to do in those cases we'll be adding those the moving ahead I have created a for Loop which is the basic practice of every backtracking problem we start it from the current index which is being passed over here we go up till the end of the array and what do we check whether the last element added into the list is less than or equal to the current element under consideration at the ith index if this condition is met that means we are forming a non-decreasing pattern as a result of non-decreasing pattern as a result of non-decreasing pattern as a result of which we are happy to add the current element under consideration which is nums of I into our current list we go ahead and add it over there so this step is of addition of a new element we recurse it over using the recursion tree using the same help method what do we pass in nums since we have already added nums at the is Index this time we'll be starting from i+ 1 and we time we'll be starting from i+ 1 and we time we'll be starting from i+ 1 and we pass in the same current list array list that we have been tracking so far onto this recursion helper method once we are done with it what do we simply remove the last element that was added in the previous step from the current list and this is it so once the recursion tree completes it will give you the answer think of it as you're basically creating pairs when you see six is greater than four that means you will be creating four and six as an entity and progressing ahead towards next elements and when you are recursing back you will be deleting six from it and thinking of more possibilities in and in those cases you will be clubbing four and seven together so if you are not able to understand don't worry walk through these templates and everything will be crystal clear to you over to you guys the effort is all yours I can only be the Catalyst and I'll see you tomorrow with another fresh question but till then goodbye take care have a great day head
|
Non-decreasing Subsequences
|
increasing-subsequences
|
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[4,6,7,7\]
**Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]\]
**Example 2:**
**Input:** nums = \[4,4,3,2,1\]
**Output:** \[\[4,4\]\]
**Constraints:**
* `1 <= nums.length <= 15`
* `-100 <= nums[i] <= 100`
| null |
Array,Hash Table,Backtracking,Bit Manipulation
|
Medium
|
646
|
1,993 |
welcome back guys so now let's see the third question it's basically we have to design our data structures which supports the following operations like we can lock when a particular node is not already locked and then we can lock it for a given user and unlock we can only unlock when the given user tries to then the user who has logged it tries to unlock it otherwise we cannot unlock it okay and also the lock should exist then only we can unlock it and there is one more feature which is upgrade from this what we can do is we can lock the current node which would be given to us and unlock all its descendants and when we would do this when all the three conditions given should be satisfied like the like it's sure it's and sister should not have any longer nodes logged log nodes and at least one log descendant should be there and the current node on which we are applying upgrade option should be unlocked okay so this is how we have to implement this data structure on the implement this tree okay so certain operations would be given to us and we have to return like whether true false something like that so if lock is successful true we have to return if unlock is successful we have to return true if upgrade is successful we have to return to otherwise we have to written false so yeah this was the question so let's see how i approach the problem like it's basically implementation based so i will directly explain through the code so yeah what i did i made a vector for parent like here also the parent was given as input so i made a global like global vector so why i made this so that i can access it in other functions as well so and also i made the n size of that array and also i made a map mp mp1 which i have used mp i haven't used so i'm deleting it so yeah now let's see for lock and for unlock because they are easy so like i would show them to you like in lock whether it was all if or and also yeah when i need when the locking tree function was called like when the constructor was called what basically i did was like i initialized the global vector which was there not global we can say like which is available to all the functions of this class and i also initialized the size of that vector and equal to parentheses and similarly i cleared all like i also constructed adjacency matrix which i cleared and also i think mp1 what mp1 is storing is like whether the current node is locked or not so mp1 of zero denotes that the lo that the lock that the node is not locked okay then what i did was i inserted the i completed my joint matrix okay like a joint of parent of i who is the parent of i um that should go to i like that i is the child of that period so yeah this is how we insert this is how i made the adjacency matrix and now let's see about the log function if already it is not logged mp of 1 is not equal to 0 then if it's already locked sorry i will repeat if already it's locked then what would be our state mp of num mp1 of num would not be 0 so then i would return simply false because the lock is that log which the user is trying to lock like the node that the user is trying to lock is already locked we cannot lock it so i will return false otherwise i would give that node the username they their lock of this user okay similarly for unlock if the lock is not of the given user who is trying to unlock and i would return false otherwise i would unlock the lock and lock the node sorry i will unlock the node then i will return true okay see that when i have returned true so okay now let's see the upgrade function okay so like independently equal to like which like what i have done here is in while loop i have checked whether any of its uh any of its ancestor contains any lock or not they should not contain any lock so i am checking that condition i am checking it i am going to the parent of each and every like i am traversing up the tree like what i am doing is i am first checking this then i am checking the parent of this then i am taking the parent of this is how i am moving see you can see like while num is not equal to minus 1 which means parent of 0 is minus 1 so that's why i am moving in such a way because when parent like when zero comes then no other ancestor is above it so that's why we would end the while loop so here i'm checking that whether is there any lock or not in the ancestors if there is a lock then i would return false so if we come here which means there is no lock until now so one condition we have checked and also i have run a dfs which condition i check through this is like whether it's descendant any of its genders contain at least one lock so for that i have run a dfs and what i have done is like i have gone to each and every child and checked whether that child has a lock or not if yes then i would return true and then i would to take the or of all such childs and if the answer is true then we would if any one of the node contains one like if any one of the node contains log then it would return true so this is how i have implemented the dfs function okay so and if answer is for like no none of its descendants contain a lock then i would return simply false because the three conditions should be satisfied and if we come here which means all the conditions satisfy so now what i have to do i have to set that log to the current user and also i have to unlock all its descendants log so what i would do is i would unlock them by another dfs like bfs one and i will simply unlock all of them so yeah if and i will i have returned true so yeah this is how i implemented this whole question so yeah thank you very much guys
|
Operations on Tree
|
sum-of-all-subset-xor-totals
|
You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.
The data structure should support the following functions:
* **Lock:** **Locks** the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.
* **Unlock: Unlocks** the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.
* **Upgrade****: Locks** the given node for the given user and **unlocks** all of its descendants **regardless** of who locked it. You may only upgrade a node if **all** 3 conditions are true:
* The node is unlocked,
* It has at least one locked descendant (by **any** user), and
* It does not have any locked ancestors.
Implement the `LockingTree` class:
* `LockingTree(int[] parent)` initializes the data structure with the parent array.
* `lock(int num, int user)` returns `true` if it is possible for the user with id `user` to lock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **locked** by the user with id `user`.
* `unlock(int num, int user)` returns `true` if it is possible for the user with id `user` to unlock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **unlocked**.
* `upgrade(int num, int user)` returns `true` if it is possible for the user with id `user` to upgrade the node `num`, or `false` otherwise. If it is possible, the node `num` will be **upgraded**.
**Example 1:**
**Input**
\[ "LockingTree ", "lock ", "unlock ", "unlock ", "lock ", "upgrade ", "lock "\]
\[\[\[-1, 0, 0, 1, 1, 2, 2\]\], \[2, 2\], \[2, 3\], \[2, 2\], \[4, 5\], \[0, 1\], \[0, 1\]\]
**Output**
\[null, true, false, true, true, true, false\]
**Explanation**
LockingTree lockingTree = new LockingTree(\[-1, 0, 0, 1, 1, 2, 2\]);
lockingTree.lock(2, 2); // return true because node 2 is unlocked.
// Node 2 will now be locked by user 2.
lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.
lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.
// Node 2 will now be unlocked.
lockingTree.lock(4, 5); // return true because node 4 is unlocked.
// Node 4 will now be locked by user 5.
lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).
// Node 0 will now be locked by user 1 and node 4 will now be unlocked.
lockingTree.lock(0, 1); // return false because node 0 is already locked.
**Constraints:**
* `n == parent.length`
* `2 <= n <= 2000`
* `0 <= parent[i] <= n - 1` for `i != 0`
* `parent[0] == -1`
* `0 <= num <= n - 1`
* `1 <= user <= 104`
* `parent` represents a valid tree.
* At most `2000` calls **in total** will be made to `lock`, `unlock`, and `upgrade`.
|
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
|
Array,Math,Backtracking,Bit Manipulation,Combinatorics
|
Easy
| null |
389 |
hello so these questions find the difference so you're giving too soon s and t and basically that sntr exactly almost the same so there's only one character difference so you just have to return a later levels add to the string T so uh and this is simple so here we go so here's it so you have ABCD right and then in the student T you have extra character which is e right and in this one you just have to return e same thing again so if s is empty and T is y then you return y so how do you actually solve this question is pretty straightforward so I'm giving to a solution so the first one is going to use the content array so uh the container from size A to Z right so it's going to be 26 right and then you can use in to sort it right and then uh two in for uh for this question one inch array for S and the other one four can you put every single I mean you increment the frequency into the content array and then at the end then you just compare if they are the same if they are then you skip if yeah then you return the current character so this will be and another one is using the actual notation so uh if a X or a right this is going to be uh this is going to cancel all right so it's gonna be uh it's gonna be nothing and if a X or something like zero something like this right and this is a right so just imagine one if so one One X so zero XO one zero XO zero right this is going to be what zero one zero right so using the same idea so let's just start putting the uh the most easy one so using a computer right so I'm going to say count C uh sorry come as new in 26. the other one this one become key new in 26 right and I just have to try first the content I mean the screen character and then just basically just increment C minus a and then you increment because there's only 26 space in the array and then if there are uh just look at the ASCII table the values are definitely greater than uh 26 because you're starting from a lowercase a right and you just have to subtract by the location to starting from 0 and then this is going to be exactly the same thing but slightly different because you have traversing another three right CNT C minus a can I use increment so now we have both frequency array we just have to compare right so it's going to be about four points I equal to 0 I less than what 26. and I plus so if uh CNT Sai the sign equal to C and t a i right they are different which is the uh which is the character you add right so you just have to return Char right and then this is uh like this is the index so since we minus a right we have to plus a bank right and then at the end you just have to return the empty sorry so this is going to be pretty much like a Simple Solution so it's pretty straightforward so let's talk about the timing space so in this one this is a space all of 26 so this is pretty much it right so this is uh full of time this is all of s this is all of T this is all of 26 right so for the worst time complexity I'm going to take the maximum uh between s and t so T is always a maximum length right so it's going to be all of t and the space is all 26. so here is a quick note right time and space complexes complexity for this solution so another one this is going to be exactly the same simple using a bit operation so I'm just copy and paste uh just quickly uh guy over so I'm going to Traverse the screen array s and then I use an Excel notation right and traversing the string t uh a string T and then using excellent location as well so if there is a single character which is the only one remain and then you have to return so let me run a code so submit so this is going to be pretty much a solution so for this there's no space uh space complexity this is constant this is time right so the worst one is going to be all of T so uh this is a solution so if you have any question leave a comment below subscribe if you want it and I'll see you next time bye
|
Find the Difference
|
find-the-difference
|
You are given two strings `s` and `t`.
String `t` is generated by random shuffling string `s` and then add one more letter at a random position.
Return the letter that was added to `t`.
**Example 1:**
**Input:** s = "abcd ", t = "abcde "
**Output:** "e "
**Explanation:** 'e' is the letter that was added.
**Example 2:**
**Input:** s = " ", t = "y "
**Output:** "y "
**Constraints:**
* `0 <= s.length <= 1000`
* `t.length == s.length + 1`
* `s` and `t` consist of lowercase English letters.
| null |
Hash Table,String,Bit Manipulation,Sorting
|
Easy
|
136
|
1,675 |
hey everyone welcome to Tech quiet in this video we are going to solve problem number 1675 minimize deviation in Array first we will see the problem statement then the logic and finally the code now let's dive into the solution so here I've taken the first example from the leeco website so here we are given positive n integers in our array as nums and we need to find the minimum deviation between any two elements in the array right and then we need to perform two operations so in our input array when we have odd element we need to multiply it by 2 and when you have even number then we need to divide that element by 2. right and the deviation is nothing but the difference between the maximum element in my input array and the minimum element in my input this will be my deviation right so we need to find the minimum deviation after performing the deviation calculation between any two elements from my input array then I am going to create a list named as maxif here so at first I'm not going to perform the device operation it means when I see a even number in my input array I will just add directly to my Mac ship list and when I see odd number I am going to multiply it by 2. I will show you guys why we are doing like that now we will start so here we are picking one first since it's an odd number I'm going to multiply it by 2 so I'm going to get 2 and I will add that 2 in my Max heat list then I am having 2 I will just add directly to my list then next it is 3 I will multiply it by 2 then I'm going to get 6 I will add that in my Max zip list then 4 it's an even number I will add directly right then I'm going to have a loop I will run the loop until the length of my Max Heap list and the length of my input array are same so I will run the loop until there is a balance between length of mine both of my arrays right so initially I'm going to have three variables one is minimum deviation which will be assigned as an Infinity at the start so then the Min value is nothing but the minimum value from my sleep list so in this case the minimum value in the max C plus is 2 so I'm going to initially assign it as 2. then I'm going to have a current variable so this will be the maximum value from my seat list which is nothing but 6 in this case which means I will pop it from my maxi now I am going to update the minimum deviation variable so I am going to update it by taking the minimum between minimum deviation itself and the difference so this difference is nothing but the difference between Min value and the current value so basically this is the maximum value in my Max sleep list and this is my minimum value in my Max heat list so we are going to take a difference between them so I am going to get 4 so minimum deviation was initially it was Infinity so I'm going to take the minimum between these two and I'm going to update that in my minimum deviation so now minimum deviation is 4 right so after updating my minimum deviation now I need to update my minimum value so I will update it by if my current value is an even number then I will update my minimum value since we have 6 in this case so I will update it by taking the minimum between the current minimum value and since we have the current variable as even number so we are only updating the minimum value when you have an even current number since we have a even number I am going to divide that by 2 so I'm going to get 3 in this case right I am going to take the minimum between these two so mean value previously it was 2 here it is 2 right so minimum value is not going to change in this case and since my current value is an even number I will divide this by 2 and I will add that value to my Max sleep list so in this case we have an even number I'm going to divide it by 2 and I'm going to add 3 to my Max shape list now I need to pop the maximum element from the backseat list which is nothing but 4 in this case and I will assign it to my current value then I will update my minimum deviation by the minimum deviation itself that is 4 is the value here then I'm going to take the difference between my minimum value and the current value and I'm going to get 2. and I need to update my minimum deviation by taking the minimum between my 4 and 2 then I will update that in my minimum deviation since we have 2 in this case I am going to update with 2. then I need to check whether my current value is in E1 number yes it is an even number then I'm going to divide my current value by 2 and I'm going to take the minimum between The Divided value and the minimum value and I'm going to update this in my minimum value so in this case there is no change we can just move on since my current value is an even number I need to divide by 2 again and I need to append that to my Max C plus so basically I'm going to append to in my axi first so we are iterating since my balance is maintained here between the length of my input array and the max interest both have equal size so I am just iterating if it is not equal I will just break out of the loop right so again I'm going to pop the maximum element from my maxi list so which is nothing but 3 in this case I'm going to assign it to the current value then I am going to update the minimum deviation which is nothing but the current minimum deviation value that is 2 and the difference between the minimum value and the current value which is nothing what I'm going to get one year one right so I'm going to update that in my minimum deviation then I need to check whether my current value is an even number if it is an even number I will update my minimum value and push that divided current value to my maxi but in this case we have an odd number as the current value is 3 now so I'm not going to do any operation I will just break out of the rule which means I have found the minimum deviation so I'm not going to push the divided value to my maxi and if I don't push that is going to be a imbalance in my input array and the max Heap list so I'm going to break out of the loop and finally I will return the minimum deviation value which is nothing but 1 in this case now we will see the code before we code and 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 first I'm going to create the max Heap list then I'm going to iterate to the input array and if the number is a even number then I'm going to add directly to my maxi list so here I'm just making the number as negative since I am using python I'm using negative signs if you are using different language you would be having Max it directly so if the numbers are I'm going to make the current value multiplied by 2. right so here I'm going to add the current value to my maxi right then I'm going to initialize variables here I have the minimum deviation which is basically it's going to be Infinity at the start then I'm going to have the minimum value I'm picking the minimum value from a Max then I am going to write the while loop so I will run the while loop until the length of my input array and the length of my Max Heap list on eco then I'm going to take the current value I will pop the maximum value from my Max sleep list sequenced then I'm going to update my minimum deviation by taking the minimum between the minimum deviation itself then the difference between my current value and the minimum value then I will check whether my current value is even or not if it is even I will be updating my minimum value by taking the minimum between the minimum value itself then the current value divided by 2. then I will add the current value divided by 2 to my maxi right for this art I'm going to break out of the loop then finally I will return the minimum deviation value I think it's fine let's run the code so the time complexity is order of n log n and the space complexity is order of n happy learning keep supporting cheers guys
|
Minimize Deviation in Array
|
magnetic-force-between-two-balls
|
You are given an array `nums` of `n` positive integers.
You can perform two types of operations on any element of the array any number of times:
* If the element is **even**, **divide** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].`
* If the element is **odd**, **multiply** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].`
The **deviation** of the array is the **maximum difference** between any two elements in the array.
Return _the **minimum deviation** the array can have after performing some number of operations._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 1
**Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1.
**Example 2:**
**Input:** nums = \[4,1,5,20,3\]
**Output:** 3
**Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3.
**Example 3:**
**Input:** nums = \[2,10,8\]
**Output:** 3
**Constraints:**
* `n == nums.length`
* `2 <= n <= 5 * 104`
* `1 <= nums[i] <= 109`
|
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
|
Array,Binary Search,Sorting
|
Medium
|
2188
|
70 |
in this problem we have to count the number of ways of reaching from bottom of a stair to top of a stair and there are different steps in the stair and in each step you can either climb by one or two so you have to just return in how many ways you can do that so let's look at an example so this is a pretty simple problem so if you have or done fibonacci uh sequence then this should be very similar to that so let's take a stare of just four steps and let's level them one two three four and we have to reach from here till top so what we can do one would be to take one step at a time so go one two three four that is you jump to first step then second then third then fourth this is the first way next uh we can reach the last step from three as well as two so three by taking one step two by taking two steps there is no other way and let's say you came to two following one step each so what is this one from 0 we went to 1 from 1 we went to 2 and from 2 we went to 4 this is another way next we would be to take the first step 2 step so here in both these methods we are going from 0 to 1 but we can go to directly 2 also so we jump to 2 and from here there are more choices we either go to 3 then 4 so let's do that first three then four so this green will correspond to first we go to two then three then four next what else we can do uh we can go to one then three so come to one then three then four so this is also valid uh how we are solving this so let us say we are solving for some general stair so in this case we are solving for four we always start from bottom so let us say we are solving for 10 so the 10th we can reach the 10th stair let's say 10th stair is somewhere here there are some more steps this is the 10th step so either we would come from this ninth one or we can come from this eighth one these are the only two values allowed you can take either one step or two step so if you know how many ways to reach from 0 to 8 then you can just take one step and reach temp so this is same as count 8 plus and you also know how many ways are there to reach step 9 from 0 then you can take one step to reach 10 so if you add these two you will get the solution so this is very similar to fibonacci nth number is fibonacci of n minus 1 if you take it as a function plus f of n minus 2 so here also we are same this if the this is n minus 2 this is n minus 1 but if we do it recursively like this then let's see the recursion tree for 10 we need 9 and 8. so we will solve for 10 9 and 8. for 9 we will need to solve for 8 and seven here we will solve for seven and six then we will solve for seven and six and five six five four and it will keep growing so first level 1 next level 2 4 8 16 so in general 2 raised to the power level number k where k starts from 0. so it's exponential and if you are solving it again and again even for moderate values like 20 30 this will become very slow and it may stop working and the other thing is that you are resolving it for example 7 and everything below it you have already solved here similarly 8 and everything below it you are solving it again here so we are resolving this problem again and again similarly 6 and below here also 6 is there so once you have solved it no need to solve again and again so this falls under the category of dynamic programming that is overlapping solutions here and optimal substructure that is in order to solve if you solve the smaller problem in optimal way then you will solve the bigger problem so n we broke into n minus 1 and n minus 2 so if you find the optimal solution of n minus 1 and n minus 2 which are less than n then you will get the optimal solution of n simply by adding them so what we will do here we will start from the base case if n is one then there is just one way you have one stair and you have to reach from here to here you will take one step if we have two steps then you can go one at a time or you can directly go here there are only two ways and from three onwards what we will do we already know one and two so we can keep two values x equal to one y equal to two and if n is less than equal to two and n is guaranteed to be at least 1 this is not 0 or negative it's mentioned so if n is less than equal to 2 you return n and if n is more than 2 you return the previous two values so for 2 it will be 1 plus 2 that is 3 for 4 it will be the solution for 3 and 2 that is 5. so here we had missed one solution there would be one more solution here you can try out that for four it should be five for five it will be the solution for four and three that is eight for six it will be 13 so these are in fact the fibonacci numbers themselves and we only need to keep track of previous two values so we can start from this and when we calculate 4 x becomes uh this corresponding to 3 and y becomes 5 the latest one then we are solving for 5 we will simply add them so we get 8 and we update them so y takes the latest value that is 8 and x takes the value of whatever y was taking so we are in kind of also doing sliding window so we are keeping track of these two to solve this one when we have solved this one we slide this window to here so the first one is x second one is y so when we slide here this becomes x this becomes y again we will move it here and this will become x this will become y and so on so let's write the code for this and we are starting from 3 since if it's less than 2 or 2 we will return it from here itself so y will become y plus x so x plus y is the next solution so next solution we keep in y so that's why we stored y here since y is updated and x will take the value of previous y that is tmp and finally we can return so if we are doing less than n then we will return x plus y if you are doing till equal to n then you will just return y both are valid and the solution is accepted and what will be the time complexity it will be o of n since we are just iterating from uh you can say from 0 to n so there are n iterations or n minus two iterations so often in space we are having a few variables so of one so we can write the same logic in java and the solution is accepted finally we will write it in python or we can write x y equal to x takes the value of previous y and y takes the value of x plus y and the python solution is also accepted
|
Climbing Stairs
|
climbing-stairs
|
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**Constraints:**
* `1 <= n <= 45`
|
To reach nth step, what could have been your previous steps? (Think about the step sizes)
|
Math,Dynamic Programming,Memoization
|
Easy
|
747,1013,1236
|
1,668 |
welcome to my uh legal summit section or 1668 uh maximum repeated substring before i start uh please subscribe to my channel okay uh for string uh sequence uh string word case k a string word is k repeating if a word is containing k times the string of subsequence of sequence right otherwise maximum k between values highest value where the words is k repeating in the sequence right so basically you guys have a sequence right let's say abc and you have word and then you see that uh another answer will reprint two because you can only return a b is a subsequent a b right but you can go twice a b right but you cannot go triple right a b so there is a is nine sequence so the answer is that somebody give the promise that somebody give you a sequence in words and you need to write return a maximum k repeating value the word in the sequence right so somebody give you a sequence and it works okay so for example ba right there's a small b a here but there's no second b right so one right and ac right the problem is there is no easy okay so the python is very uh very easy that you can just use word in the sequence so check that whether uh such word is uh indeed a subsequence of c of uh original sequence so the let's assume the answer is zero right answer zero that i one okay so why because the i also shouldn't have start from one okay and then you keep repeating what that wordy defined i times word right so i times word means that you repeating i times so you first check that the quota so the algorithm is that you first check the whether word is a subset is a subsequence and if a b if word is a subsequence then you times two right check that the whatever sequence can uh government is twice worth if you can how many twice then the you check that when you get incoming uh triple right you keep going until you find that some you'll find that the statistical cannot absolute board okay so worthy defined to ionize word and worthy if word is not in sequence that means you fail right so for example if i if the original is one then you fail that means there's no there's the word is not subsequent so you don't output zero so that means origin generally you need to return i minus one because uh you didn't pass the ice test otherwise that you just check the next ie plus or equals to one right so this is a very simple algorithm so you just check one by one right i don't hear you fail okay so let's solve the problem okay i'll see you guys in the next video uh be sure to subscribe to my channel thanks
|
Maximum Repeating Substring
|
find-longest-awesome-substring
|
For a string `sequence`, a string `word` is **`k`\-repeating** if `word` concatenated `k` times is a substring of `sequence`. The `word`'s **maximum `k`\-repeating value** is the highest value `k` where `word` is `k`\-repeating in `sequence`. If `word` is not a substring of `sequence`, `word`'s maximum `k`\-repeating value is `0`.
Given strings `sequence` and `word`, return _the **maximum `k`\-repeating value** of `word` in `sequence`_.
**Example 1:**
**Input:** sequence = "ababc ", word = "ab "
**Output:** 2
**Explanation: ** "abab " is a substring in "ababc ".
**Example 2:**
**Input:** sequence = "ababc ", word = "ba "
**Output:** 1
**Explanation: ** "ba " is a substring in "ababc ". "baba " is not a substring in "ababc ".
**Example 3:**
**Input:** sequence = "ababc ", word = "ac "
**Output:** 0
**Explanation: ** "ac " is not a substring in "ababc ".
**Constraints:**
* `1 <= sequence.length <= 100`
* `1 <= word.length <= 100`
* `sequence` and `word` contains only lowercase English letters.
|
Given the character counts, under what conditions can a palindrome be formed ? From left to right, use bitwise xor-operation to compute for any prefix the number of times modulo 2 of each digit. (mask ^= (1<<(s[i]-'0')). Expected complexity is O(n*A) where A is the alphabet (10).
|
Hash Table,String,Bit Manipulation
|
Hard
| null |
1,200 |
hello everyone welcome or welcome back to my channel today we are going to discuss another problem is minimum absolute difference so in this problem we are given an area of distinct integers find all pair of elements with the minimum absolute difference of any two elements what does this mean that we need to return all the pairs such that the pair has minimum absolute difference now what is minimum absolute difference so see if this is a pair a comma b then a comma b r from array a should be less than b and b minus a equals the minimum absolute difference of any two element scenario let's see a test case and understand so we have this array and if you see the minimum difference between any two elements in this array is one see two minus one is one right so there is nothing less no difference less than one so we need to in the output there should be all pairs whose uh like whose difference is one so if you see one comma two has difference one two comma three has difference one and c comma four has difference one so minimum absolute difference is one for all these pairs hence the output is this uh and similarly for this test case also if you see the minimum difference is two and there is only one pair which has minimum absolute difference two which is one comma three so that's in the output let's see for this test case and let's see how we can approach the problem see we need to return all the pairs right all the pairs which have the difference minimum which have a difference minimum that is if a comma b is a pair then the difference between b minus a should be the minimum difference right so first off first of all we need to know what is the minimum absolute difference if we know the minimum absolute difference then only we can find the pairs now so if we know the minimum absolute difference then we can find the pairs so let's say we know the minimum absolute difference so over here if you will see the smallest uh difference which we can get will be 4 that is if you subtract 8 from 4 you will let me just check once okay so like if you see uh this is minus 4 let's say 27 minus 23 so if you do 27 minus 23 it will come out to be 4 and there is no difference less than 4 so 4 is the minimum absolute difference me 4 is the minimum absolute difference now how will we calculate pairs let's so for now let's suppose we know what is minimum absolute difference we have calculated it somehow now we need to know uh all the pairs which have this difference no so one way of calculating all the pairs finding out all the pairs is like running two loops nested loops one is the outer loop and then the inner loop j1 and similarly we can have two nested loops so that will be o of n square and this will give us tle why because if you see the constraints in the constraints the maximum array length could be 10 raised to power 5 that means our n could be maximum 10 raised to power 5 so according to that this will be 10 raised to the power 5 square which will come out to be 10 is to per 10 so this will give us tlu so in order to calculate pairs this approach is not correct we should not use nested loop otherwise we'll get tle so what other thing we can do see whenever we have to calculate pairs now and we cannot use the nested approach nested loop approach then what we can do is we can use sorting how sorting will help let's see that so if we sort this array let's sort it first of all it will be minus 14 minus 10 minus 4 3 8 and then it will be 19 23 and 27 so this is 1 2 three four five six seven eight one two three four seven eight okay so now see we need to calculate first of all we need to know what is the minimum absolute difference so what we can how we can find the minimum absolute difference we can compare these two elements every time so obviously since they are in sorted order the minimum the difference will be because these are inserted so we can find out the minimum absolute difference so let's take a different variable minimum absolute difference and we can just compare the adjacent elements so minus 10 minus 14 this will give us minus 10 plus 14 which is 4 hence as of now the minimum absolute difference initially will take us in take it infinity so now it is 4 the minimum difference now we will compare minus 4 and minus 10 so minus 4 minus 10 so this will come out to be 6 so 6 is not less than 4 is already there so in this way we can find out the minimum absolute difference we compare both the elements till the end so now we have found the minimum absolute difference so see sorting one benefit of doing sorting was we can easily find the minimum absolute difference now secondly we need to find the pairs so we have to choose all those pairs whose difference is this for now so same thing we can do what we can do is we can uh what we can do we can just simply compare these two elements every time so if this give us the difference 4 then that those elements are our answer so if you see minus 10 minus 14 if you do this like this is your a sorry this is your b and this is your a so b minus a it will give us 4 so since minimum absolute difference is 4 and this pair is also giving us 4 so this pair will be included in our answer so minus 40 minus 10 comma minus 14 comma minus 10 will be our answer one of the answer it will be one of our answer similarly when you will compare 19 when you do 19 minus 23 19 sorry 23 minus 19 over here 23 minus 19 then you will get 4 so 4 is equal to minimum absolute difference which we calculated so this pair will also come in an answer nineteen comma twenty so same approach what you are doing we are just comparing the adjacent elements every time and if they if the difference of those are equal to the minimum absolute difference we add them to the output so i hope you understood the approach uh at the dry iron let's see the code now code will be very easy see so first of all we have sorted the area in the sending order and then what we are doing is we have taken this a vector we have taken this answer vector so since we are returning a 2d array so we have taken it vector because at h index there will be a further vector if you see this is at each index there is an array right so then what we are doing this loop is for calculating the minimum absolute difference so we are comparing the adjacent elements and if the difference is less than the minimum difference we are like choosing minimum of these two and after that we are running another loop and we are comparing the adjacent elements and if the adjacent elements difference is minimum difference just add it add that pair to our answer and at last we returning the answer so if we submit this it will be it is accepted and the time complexity since we are doing sorting is o of n log n since we are doing sorting and for the space complexity it will be off if we like add max whatever the uh like you can say at max we can have a around n in our n let's say if the length of the output is x then our this is x space complexity is of x you can say so i hope you understood the problem and the iron approach if you like the video please like it share with your friends subscribe to my channel i'll see in the next video thank you
|
Minimum Absolute Difference
|
remove-interval
|
Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows
* `a, b` are from `arr`
* `a < b`
* `b - a` equals to the minimum absolute difference of any two elements in `arr`
**Example 1:**
**Input:** arr = \[4,2,1,3\]
**Output:** \[\[1,2\],\[2,3\],\[3,4\]\]
**Explanation:** The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.
**Example 2:**
**Input:** arr = \[1,3,6,10,15\]
**Output:** \[\[1,3\]\]
**Example 3:**
**Input:** arr = \[3,8,-10,23,19,-4,-14,27\]
**Output:** \[\[-14,-10\],\[19,23\],\[23,27\]\]
**Constraints:**
* `2 <= arr.length <= 105`
* `-106 <= arr[i] <= 106`
|
Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals.
|
Array
|
Medium
| null |
83 |
foreign problem and the problem's name is remove duplicates from sorted list so in this question we're given the head office Hotel linked list we need to delete all the duplicates such that each element appears only once and we need to return the linked list in sorted order as well so let's take a look at this example and see how this question can be solved I've taken the same example they gave us let's take a look at the first example so the head is pointing at the first node and the last node is pointing to null so our task is to remove duplicate elements so it means that if there are duplicates both of them will be adjacent to each other like in this case these two are duplicates so we have to remove one of them for that let's start off by creating a current node which will be pointing at the head of the linked list and this current null will iterate till current is not equal to null it means that we reach the end of the linked list so until current and also we have to check if current dot next is not equal to null because we are going to compare the current node with the next node so we are going to access a node which is ahead of current so we also have to check if current dot next is not equal to null until then we run a while loop so now we check if current.val if it is so now we check if current.val if it is so now we check if current.val if it is equal to current dot next dot val that is also equal to 1 if that is the case we take current dot next and point it to current.next.next and we remove the current.next.next and we remove the current.next.next and we remove the connections in between so current is now here now we check if current is not equal to null no current is not equal to null but current dot next is equal to null so we end the iteration and now we can return the head of the linked list so our output will look like this and therefore we can return the head of the linked list so this will be our output now let's take a look at the second example so we start off by creating a current node which is pointing to the head of the link list and we run a while loop until current and current dot next is not equal to null meaning we reach the end of the linked list now we have to check if current dot val which is equal to 1 is equal to current dot next 12 wire that is also equal to 1 so we make current dot next point to current dot next and this connections will be removed and now current is pointing here now current is not equal to and also current dot next is also not equal to null so we can proceed now we check if current dot val is equal to 2 if it is equal to current dot next door 12 now it is not equal to 3 so we simply move the current pointer to the next node so current will now point to current dot next so current is now pointing here now again current is not equal to null and also current dot next is also not equal to null so we can proceed now current dot 12 is equal to 3 and current dot next dot val is also equal to 3 so you point current dot next to current dot next so current dot next is here it will point to current dot next and current will move to that node now current is pointing to null so you can end the iteration and finally we can return the head of the linked list so our output will look like this and you return the head of the linked list so this will be our output now let's take a look at the Java code coming to the functions have given us this is the function name and this is the head of the linked list called head and we need to return the head of the linked list after performing the operation so the return type is also list node as I've said let us create a current node and point it to head now we have to iterate until current is not equal to null and also current dot next is also not equal to none now inside this while loop we have to check if two adjacent nodes are having the same value so if current dot val is equal to current.next.12 so if current and current dot next are the same value we have to point current dot next to current dot next so here in this case current was here and current dot next is here both are having the same value so current dot next will point at current dot next and in the else block it means that two adjacent nodes are not having the same value that is the opposite of this statement else block will be executed so if current is here and current.next so if current is here and current.next so if current is here and current.next is here 2 and 3 are not equal so you just move the current point of one step to the right so current will point to current dot next and you come out of the while loop so this process will happen for all the elements and you get the sorted array and now you return the head of the linked list so the head of the linked list will contain the new connections and the duplicates will be removed now let's try to run the code the test cases are running successfully let's submit the code there you have it our solution has been accepted so the time complexity of this approach is of M where n stands for the number of nodes in the input linked list and the space complexity is constant o of 1 because we are not declaring a new linked list or not building a new link we are just changing the connections between the nodes that's it guys thank you for watching and I'll see you in the next video foreign
|
Remove Duplicates from Sorted List
|
remove-duplicates-from-sorted-list
|
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_.
**Example 1:**
**Input:** head = \[1,1,2\]
**Output:** \[1,2\]
**Example 2:**
**Input:** head = \[1,1,2,3,3\]
**Output:** \[1,2,3\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 300]`.
* `-100 <= Node.val <= 100`
* The list is guaranteed to be **sorted** in ascending order.
| null |
Linked List
|
Easy
|
82,1982
|
465 |
hello friends today lists of optimum of a counterbalancing province we are given transactions and a transaction will be given as at a pole X Y Z that means X give Y Z dollars so for this example that means zero gave one $10 to get zero that means zero gave one $10 to get zero that means zero gave one $10 to get zero five dollars and our task is to see how many intersections we need to make so that all the people are settled up that's right of the graph that means zero give one $10 to give their $5 so in zero give one $10 to give their $5 so in zero give one $10 to give their $5 so in third hole zero should give out $5 and third hole zero should give out $5 and third hole zero should give out $5 and he should be paid $5 to be set up for he should be paid $5 to be set up for he should be paid $5 to be set up for the one he was given ten dollars so she should've but he should have paid $10 to should've but he should have paid $10 to should've but he should have paid $10 to be a hub and folder to he were or he gave out her $5 so he should be paid $5 gave out her $5 so he should be paid $5 gave out her $5 so he should be paid $5 to be set up so you will find that all the to be paid if we sum up it should be the sum of all the numbers you don't pay 5 plus 5 equal to 10 so how do how can we make the transaction okay let's won't pay five to zero and one pay five to shoot right like this sort of result should be two transactions that's the another example zero paid one $10 and a 1 peter Yarrow $1 and the one $10 and a 1 peter Yarrow $1 and the one $10 and a 1 peter Yarrow $1 and the one paid it to $5 paid it to $5 paid it to $5 - p20 $5 as before we should turn some - p20 $5 as before we should turn some - p20 $5 as before we should turn some of older we should have calculate its balance for the zero in turtle he paid ten dollars and he received the six dollars so actually the just equals he paid four dollars so in order to be settled up he should be paid four dollars in the same way we calculate that one should pay four dollars because you received four dollars more in the for the truth he words receipt he received a $5 and he paid five dollars received a $5 and he paid five dollars received a $5 and he paid five dollars so in turtle he already set up so we do not need to do any transactions for this person in the end we just needed led to one pay zero four dollars and all the people I said up so the reader is just one we only needed to do one transaction so you will see how do we get the number of the transactions first we will calculate the balance of each account right in the transaction actually a two-way relationship two-way relationship two-way relationship what does that mean when we calculated the top whole zero paid one $10 that the top whole zero paid one $10 that the top whole zero paid one $10 that means zero should be paid $10 to be means zero should be paid $10 to be means zero should be paid $10 to be settled up and the for one he should pay others $10 to be set up so one others $10 to be set up so one others $10 to be set up so one transaction actually means two changes for both the you know the first people understand people so in this way when we iterate to all the transactions we can get the balance for each account you know red coat of the balance for each account we can use a hash table right the key just means account the balance means it's balanced you know the value makes that balance right and there was the next after you see in this example this qu is already settled so we do know me that you count it in the next steps so we only need that you get all the values in the hash table that is not equal to zero and we can use at least that you said all the parents that have known zero okay how about next let us see this example and then we use the same methods before we can calculate their a zero should be paid two dollars to be set up and one should be paid two dollars to be set up and choose the pace three dollars to be set up so actually we can use a negative three to represent because when it'll should be paid that means she told balance should have this you know should be added you know when it should pay others the dollars actually his total balance should be - right should be managed and should be - right should be managed and should be - right should be managed and the legacy alternative way to settle all the people up as three should pay others to dollars so he can pay $1 to four to dollars so he can pay $1 to four to dollars so he can pay $1 to four to let fall be settle up and he left him one dollar and he can pay that to one and then choose you the pays $3 each and then choose you the pays $3 each and then choose you the pays $3 each others so he can pay the one to the one tolerant you want to led2 won't be centered and he left a $2 he campaigned centered and he left a $2 he campaigned centered and he left a $2 he campaigned back to zero so all the people are said her dad but you will see in turtle is fortune sections this non-optimal you see this is optimal non-optimal you see this is optimal non-optimal you see this is optimal right you can Det 3 pay $2 to one right you can Det 3 pay $2 to one right you can Det 3 pay $2 to one because you have $2 a 3 have $2 in one hell should I be paid a $2 so actually hell should I be paid a $2 so actually hell should I be paid a $2 so actually we can let us repay his $2 to one so it we can let us repay his $2 to one so it we can let us repay his $2 to one so it is just a one transaction and for the two he can pay $2 to zero and he can pay two he can pay $2 to zero and he can pay two he can pay $2 to zero and he can pay another $1 to four so all the people a another $1 to four so all the people a another $1 to four so all the people a set order and in turtle there are only three transactions this is optimal so you will find that we will try to let this transaction happen that means one person like his balance is negative and then that person his balance is positive and if their balance sum up equal to zero it shouldn't be an optimal method right this is the scene you should notice so let's see actually the elgar is just we start from the first value actually you recall that we have at least said all the values that are not equal to zero right now we try to set up with the rest of values in a week compare all possible assignment like this is a possible assignment this is another possible assignment and again at global minimum number of the transactions this is a truly once the current balance plus the next balance equal to zero it should be an optimal assignment so we can end early what does that mean and just like here this is negative two and this is party to so we can assign this true it should be the optimal if we split this tree up right we assign this one to four in the one dollar to one it should not be optimal this is you should notice and only when the current balance times the next balance is less than zero we could have set up what does that mean like zero should be paid to and wants to be paid acute they are all positive so if we let zero give money to one that means it will just add more transactions because zero should the people at you know you let 0k to two dollars to one that just added the motion sections because zero should be paid up four dollars and they already cost one dollar a one transaction to pay two dollars to one so only when the you know this balance times this balance are less than zero we can use a transaction to try to make them set up this is the same okay wrap up we first do some pre-processing wrap up we first do some pre-processing wrap up we first do some pre-processing to get the balance of each account and then we will do the backtracking to get to the global minimum number of the transactions and just as something you need that you notice that owning the crap okay the current balance times next balance less than zero we can perform one show section and we can always and early if a current balance plus the next balance you go to zero it is the optimal assignment okay you can send that so now let's write the code first that's saying first so we need a hash table the key and value shoot oh be the integer a new hash map and then we iterate the transactions and we could kill zero right and the map get or default there will be t 0 and if we have the city before the should be 0 and as you see zero paid $10 to one so and as you see zero paid $10 to one so and as you see zero paid $10 to one so to piss a lab he should be paid $10 so to piss a lab he should be paid $10 so to piss a lab he should be paid $10 so she should ask add that is he cute to be settled so it could q1 and never get all default I repeat he 1 0 - ooh what a default I repeat he 1 0 - ooh what a default I repeat he 1 0 - ooh what a dummy that means 1 he received $10 and dummy that means 1 he received $10 and dummy that means 1 he received $10 and to be settled up he should pay other people $10 so we should have - this people $10 so we should have - this people $10 so we should have - this number teacher and now we will try to get to the values that are not equal to 0 so here's a list and then we will see for all the value in the mapped on values if B not equal to 0 at least will at least V okay now we get all the values then we will call it def search we will know the first you know the current index is 0 and we will also pass at least and now let's write and this DFS function this is a cake mix the index in the list okay this is a list let's see the base case once the k equal to the list dot size we do not need any transactions mob so we return 0 and now we can get a current balance there will be listed get ok the same thing if this curve equal to 0 that means we can just skip current you know skip a current value so there will be k plus 1 list we do not need to add another transaction otherwise we can try to get the global minima so initially we can learn you caught you integer max value in the folder you know I start from k plus 1 I less than least all slice I plus look at the next balance should be at least yet I right and I said below and I said before only when the current balance comes next balance less than zero we can make a transaction in the minimum we try to get the minimum to be a minimum of the minimum and if we do transaction actually we add a one transaction then we try to do the next you know try to set happen next out so there should be K trust what mix but do not forget you update to this value so least at this I will be curbed last next and if we undo this I will reset it to the I there will be next then we can and early if this curve class next equal to zero we can just break this is already optimal finally we will return this minimum okay thank you for watching see you next time
|
Optimal Account Balancing
|
optimal-account-balancing
|
You are given an array of transactions `transactions` where `transactions[i] = [fromi, toi, amounti]` indicates that the person with `ID = fromi` gave `amounti $` to the person with `ID = toi`.
Return _the minimum number of transactions required to settle the debt_.
**Example 1:**
**Input:** transactions = \[\[0,1,10\],\[2,0,5\]\]
**Output:** 2
**Explanation:**
Person #0 gave person #1 $10.
Person #2 gave person #0 $5.
Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.
**Example 2:**
**Input:** transactions = \[\[0,1,10\],\[1,0,1\],\[1,2,5\],\[2,0,5\]\]
**Output:** 1
**Explanation:**
Person #0 gave person #1 $10.
Person #1 gave person #0 $1.
Person #1 gave person #2 $5.
Person #2 gave person #0 $5.
Therefore, person #1 only need to give person #0 $4, and all debt is settled.
**Constraints:**
* `1 <= transactions.length <= 8`
* `transactions[i].length == 3`
* `0 <= fromi, toi < 12`
* `fromi != toi`
* `1 <= amounti <= 100`
| null |
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
|
Hard
| null |
368 |
hello everyone this is sham soari and I welcome you again in the next video of our YouTube channel in today's video we are discussing this problem which came on 9th of February so the problem is largest divisible subset so they have given a set of distinct positive integers nums and we need to return the largest subset answer such that every pair answer I and answer J of elements and this subset satisfies answer I modul answer Jal Z or answer J modul answer IAL to0 so if there are multiple Solutions we will return any of them so here nums it is 1 2 3 output is 1 2 because 1 and 3 is also accept accepted so here they have given a set of distinct positive integers and we need to return the largest subset answer such that every pair answer I and answer z of elements in this subset satisfies this condition uh which is answer of I modu answers of J equal to 0 or answer of G Modo answer of I equals to Z so 1 2 is the pairer which satisfies this condition in the 1 2 3 so we will return that and here 1 2 48 uh it is satisfying so we will return 1 12 48 so how to solve this type of problem let's discuss what is the approach here so first of all we will sort the input ARR nums after that we will initialize a dynamic programming array DP of size n because it is a dynamic programming solution we will create a dynamic array of size d n where DP of I represents the size of the largest divisible subset ending at I so our DP of current I will represent the size of the largest divisible subset ending at index I and we will iterate each pair of elements uh nums of I and nums of J where uh J and I should be greater than equal to zero and I greater than J and if nums of I is divisible by nums of J we will update DP of I to be the maximum between its current value and DP of J + between its current value and DP of J + between its current value and DP of J + one so after that we will keep track of the maximum value of Maxi in DP we will also track the maximum value here and we will Traverse DP from end to start so for each index I if DP of I equals Maxi and the current number nums of I is divisible by the previous selected number num we will add nums of I to the result vector v and decrement Maxi and at last we will return the result vector v which will be the output so let's code for this solution before that if you are new to the channel hit the like button and subscribe for more content so first of all we will store size of nums in an num. size then we will create a Max C variable and assign it one and a num variable which will which we will assign minus one then we will create a vector of n v then we will sort nums or begin nums do end we will sort the nums array first and then we will initialize a de Vector of size n and one is the value of each element so now we will iterate through this Vector in I = 1 i l than n and I this Vector in I = 1 i l than n and I this Vector in I = 1 i l than n and I ++ and again we will use a nested for ++ and again we will use a nested for ++ and again we will use a nested for loop forting from j = 0 J less than I loop forting from j = 0 J less than I loop forting from j = 0 J less than I and J ++ here we will check a condition ++ here we will check a condition ++ here we will check a condition that if nums of I and modulo nums of J is not present means it is false and thep of I less than DP of J + 1 we will check these two of J + 1 we will check these two of J + 1 we will check these two conditions if this two conditions satisfied then we will proceed further with DP of I = to DP with DP of I = to DP with DP of I = to DP of J + of J + of J + 1 and if Maxi is less than DP of I then we will update the Maxi as DP of I and after this for Loop we will again initialize a for we will again Implement a for Loop which we will start from nus1 and up to 0 i- will decrement 0 i- will decrement 0 i- will decrement I then we will check for the solu uh if we will check some conditions here if Maxi is equal to DP of I and num = 2 and num = 2 and num = 2 -1 or not of num modulo nums of like this LS of I so these are the two conditions if we will check Maxi equals DP of I and nums of nums = minus1 or nums mod nums of I of nums = minus1 or nums mod nums of I of nums = minus1 or nums mod nums of I which is it is not true if this conditions satisfies then we will push nums of I and we will decrement my C after that we will update nums equals to nums of R and at last we will return v is the final solution so let's check for this solution yeah the solution ran successfully check for the hidden test cases hiden test cases also so overall the solution is right so here talking about the time complexity we are sorting array for that we will the time complexity will be big off and Logan and we are using this nested for Loops for insert for Loop so for this it will be of n Square so overall time complexity will be B of n² + log n which we will get as big of n + log n which we will get as big of n + log n which we will get as big of n Square which we can take it as a big of n square and the space complexity will be big of n because we are creating these vectors a vector of size n so that's it if you are new to the if you enjoyed the video hit the like button and subscribe for more content and stay tuned for upcoming lead code problem onday videos and exciting month stack web development projects happy coding and let's make this year a fantastic one together thank you
|
Largest Divisible Subset
|
largest-divisible-subset
|
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies:
* `answer[i] % answer[j] == 0`, or
* `answer[j] % answer[i] == 0`
If there are multiple solutions, return any of them.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[1,2\]
**Explanation:** \[1,3\] is also accepted.
**Example 2:**
**Input:** nums = \[1,2,4,8\]
**Output:** \[1,2,4,8\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 2 * 109`
* All the integers in `nums` are **unique**.
| null |
Array,Math,Dynamic Programming,Sorting
|
Medium
| null |
698 |
hello everyone welcome to coderscamp we are at last day of september eco challenge and the problem we are going to cover in this video is partition to k equals some subsets so the input given here is an integer array num and an integer value k and we have to return true or false if it is possible to divide the given array into k equal parts whose sum are all equal let's consider the first example if you see we have to divide the array into four equal parts so if we divide 5 1 comma 4 2 comma 3 and 2 comma 3 all the sums are equal and we have divided it into four equal sums so we are going to return true so let's see how we're going to approach this problem so here is a given example in the problem statement so we have to divide this array into four equal parts of equal sums so to divide the array into equal parts we first know what would be the each subset sum then only we can put the elements accordingly into the bracket so now before getting to find what is the sum of each subset we have to find whether we can divide them into equal four parts or not so here the total sum of the array is 20 so we have to divide the whole array into four equal parts so 20 reminder 4 if the 20 reminder 4 is equal to 0 then it is possible to divide the array into 4 equal parts or k equal parts if not we can directly return false because we cannot divide the array to equal paths so here 20 by 4 is giving you reminder 0 so it is possible to divide the array into four equal parts so now by guessing this you can easily find what would be the subsets sum so 20 by 4 would be 5 so 5 would be each subsets sum so now our job is simple we have to put the elements equally that sums up to 5. so now starting with the first element 4 we have to explore with the rest of the array what would be its pair to make the sum up to 5 so now we are going to check which pair would actually make it to 5 so now 4 is it first we are going to explore 3 2 3 5 2 and 1 so now starting with 3 if you add 4 with 3 then the sum would be 7 which is greater than 5 so you cannot pair it with 3 then goes to 4 plus 2 this is also greater than 5 then goes 4 plus 3 which is again 7 then 4 plus 5 which is 9 4 plus 2 which is again more than 5 so finally 4 plus 1 is 5 so this makes one pair that sums up to 5 so we found our first subset out of 4 so now what we do our k is equal to 3 because we found one so k minus is three we need to find three more subsets and we are going to set the first pair to true that is visited so we don't have to include these two elements again in the next subset the first subset is four comma one so there comes our next element three we have to check which one would pair with three to make it to five so fix the next element three plus two is five so we found our next pair so we are going to add that to our subset and we are going to set the places to true and we still have two mores observed to find so there comes our next element which is 3 adding 3 plus 5 will not give you 5 so 3 plus 2 is 5 so we found our next subset which is 3 comma 2 and we have one more subset to find now and we set this to true so if you check we have only one more element left of sum five so that is going to be our next subset and we found our subsets four subsets and we divided the array into four we don't have any more elements left because all the cells are updated to true so we are going to return true as our output so clearly we here did a backtracking dfs where we took one element and explored every other element to match whether it paired with the element to make the sum to 5 or not so we are going to explore each and every path and update our k accordingly once our k becomes 0 then we finished our array and we have to return true so this is going to be a simple dfs code let's explore the code more while we are coding it and hope you are understanding this concept let's go to the code now so we are going to use a recursive dfs let's initialize the basic variables so first let's calculate the sum and find the target and whether it is possible to divide the array or not so we directly written false if the remainder is not equal to 0 or the maximum number in the array is greater than the subset sum we found if not if it is true then we are going to call a helper method which is nothing but our tfs which is gonna explore every number to find its pair and this new boolean array to mark the whether the cells are visited or not now let's spend some time in writing our helper method so now we are getting the target sum that is sum by k of each subset and a visited array to keep track of what are the elements we have already used in our array and index is to start from the zeroth index and travel till the last index so first we are going to check the base condition that if our k becomes 0 then we found our subsets then we are going to return true if any point k cannot be 0 or less than 0 then we did not found our subsets but that can be a case because we are negotiating if it is false already so now there comes our calculation of sound that current sum is going to keep track of the sum till it reaches the target sum once it reached the target sum it is going to calculate the new subset so if we reached current sum as the target sum that is that means we have found our new subset so we are going to call recursively the same function to find the rest of the subsets so we found one subset then our k is gonna uh decrement one target sum is going to be same and current sum is reset to zero because we found one and we are going to initialize it back to zero to form the next one so we are going to iterate the given array and every time we are going to consider each element if it is not already visited if it is already listed we are simply going to iterate to the next element and which means we are visiting that element and gonna find its pair so we first set visitor to true and then we are going to add the sound to the current sum if that works then we are going to return true if not we are going to reset it back to false because if this sum can be considered and that is within range and if we explore the path and that can be part of that subset then it is going to be true if not we are going to reset it back to false so here is where we do the backtracking and finally if it doesn't reach 0 and return true then it has to be false we cannot find then we finally going to return false yes this is it let's run and try yes so let's submit yes the solution is accepted and runs in one millisecond so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
|
Partition to K Equal Sum Subsets
|
partition-to-k-equal-sum-subsets
|
Given an integer array `nums` and an integer `k`, return `true` if it is possible to divide this array into `k` non-empty subsets whose sums are all equal.
**Example 1:**
**Input:** nums = \[4,3,2,3,5,2,1\], k = 4
**Output:** true
**Explanation:** It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
**Example 2:**
**Input:** nums = \[1,2,3,4\], k = 3
**Output:** false
**Constraints:**
* `1 <= k <= nums.length <= 16`
* `1 <= nums[i] <= 104`
* The frequency of each element is in the range `[1, 4]`.
|
We can figure out what target each subset must sum to. Then, let's recursively search, where at each call to our function, we choose which of k subsets the next value will join.
|
Array,Dynamic Programming,Backtracking,Bit Manipulation,Memoization,Bitmask
|
Medium
|
416,2135
|
84 |
so in the previous approach we implicated this formula in order to find out the rectangular area and we did this for every a of i for every a phi we did this and this was a two pass solution where we had to figure out the left smaller as well as the right smaller how to convert this to pass into a one pass solution now if you remember while finding out the left pass we implemented a stack which was containing everything in the linearly increasing fashion we're gonna use that let's see how now imagine i give you something like an histogram i give you some an histogram which states uh this is a block two this is a block uh let's assume this is a block three this is a block two okay and this is a higher block of block n and this index is zero one two this is again a block of 11 size okay and this is having a block of size 5 which is at index 4 and at index 5 again you have something as a block 10 and over here you have a block six okay at index and right at index seven you have a block three assume this is the histogram that we consider now if you remember the previous process of finding the left smaller the moment you come to this element i'll just talk about this element and after that i'll do one complete try the moment you come to this index 7 can i ask you what will be there on the stack if like the stack which contains index will contain everything in the linearly fashion when you come to the 7 what will it have it will have this guy and it will have this guy you can definitely do a dry run and you'll see that the stack will contain the index 1 the index 4 the index 6 and the index 6 is having 6 the index four is having five the index one is having two this is what the stack will contain the moment you reach a of seven equal to three correct you can do a dragon for finding the left smaller and you'll find that whenever you add a of you will contain this only i'm talking about the intuition now can i say instead of finding for a of i instead of finding for every a of i you will try to find the rectangular area for these guys six four one indexes now you'll be like how will this work this will work i'll tell you how will this work see the moment you are at six let's consider this as the height what will be its right smaller and what will be its left smaller let's think about that can i say the right smaller will be nothing but for the six if you're comparing this with three that's gonna be a right smaller this is what is going to be your right smaller indeed before six the index that you have in your stack because this is a linearly increasing order before 6 you have a 4 so can i say this guy will become my left smaller for this index this height 6 indeed so without actually doing a couple of passes for six i could figure out the right smaller is this guy the left smaller is this guy and that is that makes sense i could so that was for six correct let's do it for the next one now what do you do in the next step you compare three with six now once you've got for six you remove six right that is what you did in stack because it was greater next you compare three with four now when you are at the fourth index this is the fourth index for this guy since you're comparing with three can i again say that this guy will become mine right smaller again make sense if you look at around the right this three is indeed your right smaller correct for this five can i say the left smaller is right before this element right before this index one again this will become your left smaller so as you can see i have the left smaller index one the right smaller index seven so can i say the width can i see the width for this guy will be from here to here can i say that will be my width yes again i figured out the left smaller right smaller in one step let's do it for the next what did you do with this three you compared four and you removed so as of now you have a one and you compare that with three so this is the moment you can say key this one is no more comparable with three because it is smaller so you'll not do anything and you'll pick this three and you'll put it over here all right so every element in the stack can actually tell you which is your left smaller which is your right smaller now this is where your iteration will be over and you'll reach an index eight you will reach an index eight so the moment you reach an index eight you still have one three but the histogram is over doesn't matter even if your histogram is over you are at a of eight can i say for this three the right on right you don't have any one all right you don't have any one so can i say for those three right smaller will be eight that's your right smaller because you don't have any one and crazy left smaller will be this guy again i have figured out for this three also yes you need to do is i trade till eight so you can easily figure out for three remove three next you can figure this for this one also for this one there is no one on the right so eighth index will be this and there is no one on the bottom of one so the left index will be this zero so that's what my thought process will be in order to solve this problem i hope you have understood the thought process now we'll do a simple run so that we can quickly wrap up this problem so i hope you have understood my thought process like how do i plan to get the right smaller and left swallow in a single pass that's trying to do a dry run so that you get a much more clarity about this so what we will do is we will keep the max area as zero okay we've kept the max area as zero and now we will start off with the zeroth index so we have a three over here so the stack is already empty so there is no one on the stack for which we can find the right smaller as well as these left small so i'll take the zeroth index and i'll store it onto the stack okay done next we'll come to this index one when you come to this index 1 that's the value array of 1 which is 1 so you compare this with this array of 0 that is 3 so you find this out key this guy is greater than this hence for this guy the right smaller is this guy with an index one the right smaller is that index one right and this guy is removed right smaller you have figured out and you will remove this guy okay so you know the height as of now is three the height is three for this guy zero you figure out the right smaller is this who will be the left smaller do you have anything before that if you do not have before that you know the stack was an increasing order can i say there is no one before that so can i say the starting index will indeed become your left smaller which can be treated as zero so in such cases you can say whatever is your right smaller the total will become your width hence i can say the width is one hence the maximum area for this three comes out to be three so i can update our maximum area so once you have done this take this index one put it into your stack put it into your step next you will come to this index two okay now add this index to your five you compare this index one value which is one so you don't find it greater so what you'll do is just take this index two and you'll put it over here whenever there is nothing as great as take it and put it over here next you come to index three what's the value that you have that's the value of six so what you'll do is again you compare that's not greater so you take this index three and you'll put it over here try to create the linear increasing fashion okay next you'll come to this food now at this four you see that we have a two which is smaller than the top of this and that is the case if that is the case you'll take this guy three which is this six you'll take this three which is having a block size of six you're having a block size of six and you will say this guy your right smaller is this index four right and your left smaller is nothing but this because for this guy the previous increasing the previous is to so you're left smaller is this so can i say the width is 4 minus 2 minus 1 that's 1 hence for a block of 6 the width becomes 1 very simple whatever right smaller you find it over here whatever left smaller you find it over here just do a minus 1 because this is left smaller correct so some across so let's do a minus 1 4 minus 2 minus 1 will be 1 so for the 6 again for this 3 you've figured out for the 6 i figured out that's 6 so that is done so once you have done for six make sure you remove this okay removed what is the next criteria you compare these two with this five again five is greater if it is greater i'll consider this block five okay and that block five is at index two for this index two can i say this index four becomes my right smaller indeed that becomes my right small can i say my lip smaller will be someone before that index one yes so can i say this is my width indeed 4 minus 1 is 3 so this is the width can i say for five i'll have four minus one three minus one that is two width so i'll get five into two i'll get a max area of ten okay so first i got three then i got a six then i got a ten so you can keep on updating so i'm getting all the max areas again the block 5 has also been computed next you just remove this two and next you will compare this 2 with this one again that is not greater so i'll just take this index 4 and i'll put this 2. try to maintain the linearly increasing order so this 4 is also done next move to this index 5 the moment you move to index 5 you have array of 5 as 3 so the value 2 is not greater than 3 so again you maintain the linearly increasing fashion so that's the index 5 containing a value three just try to maintain the linearly increasing fashion nothing else so i've maintained it but still this block has not been considered into the area so what you'll do is you just do one more iteration for this block six okay like there are indexes these are the indexes correct it starts from zero one two three four five will go until six will go on till one more so we will move to six now as you can see you've just done for the histogram of height three five six still left off with one two and three and these are present in your stack so we're gonna use them so what we will do is we'll do one more iteration if the indexes are till five you're going to do one more iteration till the index six okay now what you'll do is since this is the last index you don't need to do anything you just pick up the fifth index guy you picked up the fifth index guy which is a block of size three for this index can i see the right smaller is definitely this because beyond this i don't have any one so the right smaller becomes six can i say for this the left smaller will be this index 4 yes because that's before that correct so can i say the width will become 6 minus 4 that is 2 minus 1 that's 1 again make sense because 1 is the width for three one is the width so three crossed one becomes three next you will come to this fourth index so when you come to this fourth index you have a block size of two correct take this off since you've come across to this take this off now can i say for this guy the right smaller will be six itself and can i say for this the left smaller whatever is before that's one again makes sense if you look at this two the right left small is this so you'll come across over here and the right small is no one so can i say the difference is six minus one that's five and the width length becomes four so two cross of four is eight so this is also done so again you can erase this next we'll come to this one so that one will be also taken out so you have a block uh height of one at index one will be the right will definitely be uh something as six that's your right smaller what will be left smaller the left smaller will be nothing but zero so can i say six zero can i say the width length is one two three four five six so in cases where your left smaller becomes zero you can take this right smaller whichever is it as your complete width because it's gonna maintain the complete one two three four five six so you're gonna say one that's this block multiplied with six then six so as you can see i've actually covered up every block and out of this the maximum is 10 did i do double passes no i just did a single pass just i made sure i just increased the pass from zero to six instead of zero to five and i was able to do it so i hope the entire intuition is clear what are the time complexity is big o of n for traversing a b go of and throughout for maintaining the stack i might argue why not n square because yeah hal bar every time you're not removing every element from the stack hence it's a n plus n what about the space complexity is just a big o of n solution so that's the time complexity this is as good as a b often and it's far better than the previous solution now generally if this question is asked in an interview i'll suggest you to stop at the previous solution unless and until the interview says you to please optimize this also then only you should go otherwise this solution you should not tell him because this requires some skill to explain otherwise it's going to be an entire mess the interview is going to be an entire mess so make sure you only tell the solution if he asks you to optimize the previous one okay so now it's our time to discuss the code so let's understand the c plus code again the java code link will be given in the description it's extremely identical because we're just using for loops and stacks so that is also present in java so both the codes are extremely identical so what you can do is you can open the java code link in some other tab and you can follow my explanation you'll understand the java code as well so what we are given is an array of histograms heights right after that i declared i get the size of that array and i declare a stack and a maximum area after that you know we have to iterate from 0 to n lesser than equal to n because as you remember at the end if there is something left in the stacks we need to compute for those guys as well the in the example that we took now the first step that we always check is the stack non-empty right that is the first trick non-empty right that is the first trick non-empty right that is the first trick we always do right after that either it's the last index so if it is the last index everything that is left in the stack has to be computed or else you just operate like you just operate by removing the greater than element just remove the greater elements so for a greater element that's the height histo of st.top because the indexing is histo of st.top because the indexing is histo of st.top because the indexing is stored over here so once you get the height can i say you can pop it out so currently we have the height of the history for that for which we are looking to compute the width so can i see the width will be i what does that mean if the stack is empty that means for the current stack element it has a above guy which is definitely smaller the right one we have got right smaller we have got correct but does it have a left smaller the stack becomes empty beneath the stack there is no one so can i say the width will become the entire eye or the wherever the right smaller guy stands till the 0th index that will be the entire width and if the stack is non-empty stack is non-empty stack is non-empty then i'll say the width will be whatever is at bottom like right after that element in the stack right after that whatever is on the stack i'll take that and i'll compute the width once i've computed the weight i can do a width into height and i'll get an easy maximum area and once all of these things are done i can take the current element and i can just push it just in case the element was smaller just in case the element that we got was greater than the stack so what we'll simply push that will not go into the while loop so with the help of the stack we can maintain the linearly increasing order and whenever we get elements that are greater we can just compute the maximum area for that so just in single pass you can find the maximum area and you can return it so instead of doing multiple passes that we did in the previous code over here we are doing single passes so guys this will be it for the c plus code i know you might still find it confusing the best way to understand this code is probably take some other examples and try to draw a dry run on this code so the more you do a dry run the more clear it will get to you so just try doing it so once you have done it i think that should be clear so guys i hope you have understood the entire explanation as well as this wonderful short code just in case you did please make sure you like this video and if you're new to our channel do consider subscribing for this let's wrap up this video bye take whenever your heart is
|
Largest Rectangle in Histogram
|
largest-rectangle-in-histogram
|
Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_.
**Example 1:**
**Input:** heights = \[2,1,5,6,2,3\]
**Output:** 10
**Explanation:** The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
**Example 2:**
**Input:** heights = \[2,4\]
**Output:** 4
**Constraints:**
* `1 <= heights.length <= 105`
* `0 <= heights[i] <= 104`
| null |
Array,Stack,Monotonic Stack
|
Hard
|
85,1918
|
56 |
in this problem we have a list of intervals and an interval is a tuple it has two points start of the time and end of the time so this is one interval and we have many such intervals and it's not sorted in any order so you have to merge these intervals so if we have intervals like this so you can represent intervals by straight line two points start and end start has to be less than end and then we have another interval let's say this one then we have another interval like this and then some interval like this and then we have this so let's say we have these five intervals so you see that this is separate i1 this i2 i3 and i4 has some overlap between them like i2 has not yet ended but i3 has started similarly i4 is completely included in i3 so these all three are overlapping so we merge them so this is new i2 and this is separate so we will call it i3 so these five intervals are returned as three intervals so let's take a concrete example so we have this 1 3 2 6 8 10 15 18 and the result is this the merged one so we see that 1 3 so it starts here at 1 ends at 3 this 2 6 it starts before this here and ends at six so you see that these are overlapping so we merge them so minimum among these is one and maximum here is six so this is one common interval one two six then eight to ten so eight is completely outside this six even if one point is overlapping that is in place of 8 it would have been 6 then we would have merged it so this is a closed interval so we include both start and end 8 10 is separate then 15 18 is also separate so we have these three merged intervals and these may not be sorted in this case it was sorted but it can be in any order and in this problem you can assume that this intervals list is non-empty so you don't need to worry non-empty so you don't need to worry non-empty so you don't need to worry about base cases of empty so what approach we can take is that it is very convenient if the intervals are sorted in ascending order of their start time because it makes the processing very natural like we as a human being how did we process it we saw one three then we saw next interval means this interval starts after this and then next one starts after this so if it's in sorted order of their start time we can easily compare with the previous one and we will get to know whether there is overlap or not so what we will do first we will sort intervals based on start time so what time it will take n log n time any standard comparison based sorting algorithm where n is the number of intervals in this case we have four so this is first step now we have to iterate through this intervals list now it's sorted based on start time so what we can check is that let's say we have we are iterating through all the intervals i n in this intervals so this is again two components start and end that is 0 and 1. so if in0 is more than the previous end so let's take two more variables start equal to this take the first interval sort in the sorted so interval 0 and end is interval 0 1 so if the current intervals start time is more than whatever was the end running end then this is a distinct interval a new interval we have found so what we will do whatever we have been saving the start and end time we will insert into our result so result dot push back or insert or add whatever is the data structure you are using this result start and end this denotes one interval and so we inserted it into the result only when we found a new interval so we have been merging it by updating start and end in fact start we were not updating only end and then we reset start now we have inserted till here so start is now pointing here end is pointing here so set the start and end here else if this is not the case that is the start of current interval is less than or equal to the previous end that is there is overlap so either it's like this form where start of current interval is less than previous end or it can be of this form also so let's say end was here next interval is here it starts before it but also ends before it so we will pick just update end here and equal to max of end and current intervals 1 and finally we will return the result also in the end we will insert push back the last interval because we will never get a chance to insert the last one so in the end we will write result dot insert whatever is the running start and end these variables so let's write the code for this and we will write it in java c plus and python so first let's write in c plus so first step is sort and by default it will take the first element which is start so we will not use any custom comparator here so this i is the interval i 0 means start of the interval is more than whatever was the end till now that is before this interval so this is the case where we have to insert it into the results so this means separate interval not overlapping no overlap then we will insert it into the result and then reset start and end so else case means overlap so we will not insert into the result just update the end max of end and i 1 so maybe the end was already more in this case this new interval i is completely enclosed in the previous interval then this will not be updated it will remain the previous end and finally in the end for the last interval uh if it's not discrete we will not get a chance to insert it so let's say last interval is discrete then also we will insert the previous interval update the start and end but we will never insert that so that's why but start and end are correctly updated so we just need to insert it even if it's overlapping we are updating the end so no matter what for the last interval we have the correct value of start and end whether it overlaps or not so we are just inserting it and return result and this is as expected so let's submit and the solution is accepted and if you see we are right here around 72 percent of the submissions in terms of time and memory also we are around 91 so that's good so what was the time complexity we sorted it so n log in and then we iterated it just one loop so this is o of n this is n log n so overall n log n and space we are using just this space whatever we have to return the result so this is mandatory space you cannot avoid it so it's often but if you ignore it's off1 now let's write the same thing in java and then we will write in python so we will give a comparator a b are intervals and these values within them are integer so we can use compare inbuilt in integer and what we will compare a0 b0 that is based on start times of a and b and br intervals and then the result should be this two dimensional integer array but we don't know the size beforehand how many intervals we will make so what we will do we will have list and then we will have int array and finally we can easily convert error list to array in the end so we will return using that and this part should remain same so this is a list of integer array so new int and we initialize with these two values and this is fine here it will be math.max math.max math.max and again new int and it's a list and we have to return convert it to array and its size should be resultant dot size and the second dimension is 2. and this solution is also looking correct and it's accepted and it takes five milliseconds so it's even better it's around 95 percent of the submissions finally we will do it in python 3. so simply call intervals dot sort and it will sort on the basis of first element so and the python solution is also accepted
|
Merge Intervals
|
merge-intervals
|
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\]
**Output:** \[\[1,6\],\[8,10\],\[15,18\]\]
**Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\].
**Example 2:**
**Input:** intervals = \[\[1,4\],\[4,5\]\]
**Output:** \[\[1,5\]\]
**Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping.
**Constraints:**
* `1 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 104`
| null |
Array,Sorting
|
Medium
|
57,252,253,495,616,715,761,768,1028,2297,2319
|
199 |
hey everyone welcome back and let's write some more neat code today so today let's solve binary tree right side view the problem is pretty self-explanatory we're given a binary self-explanatory we're given a binary self-explanatory we're given a binary tree and basically imagine you're standing on the right side of it so this is the tree imagine we have a person standing over here right you can see from the right side you can see everything on the right side and so what nodes can this person see well they can see the root node right there's nothing blocking that they can see this node can they see two well you can't really see two because it's behind this node right it's basically blocking it's blocking this node right and the same thing with these two nodes right we can see four because it's the right most right like imagine the person sees this but you can't really see that because it's being blocked by the four so that so when you just look at this example this problem seems really easy right so your first thought might just be okay start at the root and keep going to the right just keep going down and we'll get the right side view right every node on the right side but we can make a counter example pretty easily to show that actually won't always work imagine this node 5 had a left child right like let's say it has 7 over here now you can see that our result is going to be one three four we can't include these nodes because they're being blocked but there's nothing over here right the seven is not being blocked so if this was our input tree then our output would be one three four and we'd have to add a seven to that because look at our person they can technically see down here so basically what this means is we can't only look at the right children right so you can actually solve this problem with a breadth first search i know most tree problems you can just do depth first search but this problem can actually be solved with breadth first search there actually is a depth first search solution but i'm going to explain the breadth first search solution to you because in some ways it's easier and you might know brett's first search in a tree is also known as level order traversal so it's also known as level order traversal which you're gonna see why it's called that just about now so instead of saying that there's a person over here that can see only the right side of the tree another way of framing this problem is saying okay for each level right each level of the tree we want the right most node so the first level it's pretty easy because there's only one node so we'll just take the one from that what about this level right we look at the nodes together for this level we want the right most so we get the three next we want the third level and what's the right most value it's gonna be the four right and lastly we take the last level and there's only one node it's seven so we're going to get d7 so with a picture this is pretty obvious right it's really easy to know what we're doing with a picture but actually writing the code for level order traversal is a little bit tricky and i'm gonna show you how to do that basically how we're gonna implement this is with a q data structure so initially what we're gonna do is add the root node to our queue so we're gonna add one to our queue and we're also going to have a result array so now what we're going to do is take a look at our rightmost value in the queue it's 1 so we're going to add 1 to our result next now we're no longer looking at this node we are looking at its children basically the next level so we can get that by taking the left and right child and adding them to our q and removing the leftmost value from our q so we add the two and the three to the q and it's important that we do it in order right the left and right the left has to be added first and then the right because we always want to get the right most value when we you know add to our result so now this is the second level of our uh tree right so what are we going to do again we're just going to take the rightmost value in this case it's 3 add it to our result and next what we're going to do is we're going to look at the leftmost value pop it right but before we pop it we want to take its children notice it doesn't have a left child right that's null and the right child is 5. so we're going to take its children and add them to the queue so now we're adding 5 to the q so we're done with 2. next we have to remove 3 from our cube because we're done with this level we want to look at the next level so we remove three but before we remove three we have to add its left and right child notice it doesn't have a left child but it has a right child four so we're going to add four to our q so now look at our cube we have two elements and these two elements represent the third level so what we're going to do now is take the rightmost value once again in our queue and add it to our result because that's the rightmost value in this level of the tree and now we're going to repeat that process so for five we're done looking at five but we have to look at its left and right child it has one child seven so we remove five and we add seven to our q and we also look at four so we're done looking at 4 right so we pop it but before we pop it we want to look at its children notice both of the children are null so basically we've reached our base case we don't end up adding more elements to the q in this case and now there's only a single element remaining in our queue and that element represents the fourth level of our tree and the rightmost node in that level is seven so we can add seven to our result and we know we still have to remove seven now right so remove seven from our q notice it didn't have any children right both of the children were null so we've reached our base case we cannot add any more elements to the queue therefore the queue is now empty so now we can stop running our algorithm we know that our result is complete we have no more nodes left to traverse so now let's translate this into code so i'm going to initialize a empty result i'm also going to have a q so in python we can do that like this it's called a dec and i'm going to initialize it just like i did in the picture with a single element and that's going to be root now it's possible that root could be null so technically it's possible that our q could have null values and i'm going to show you how i'm going to handle that so while the queue is non-empty that so while the queue is non-empty that so while the queue is non-empty that means we can pop elements from the queue so i'm going to get the right side element from this current level i'm initially going to set it to null and i'm going to get the current queue length right the current length of the queue so right now imagine it's just a single level right our q at any given point contains one level at a time so for this level i'm gonna get the length and then what i'm gonna do is go through every element in this level so for only q length right the initial length because we know this q is going to continuously be updated so i'm going to go through every element and i'm going to pop it so q pop left right we know we're popping elements from the left and we're adding elements to the right now we know the node actually could be null so what i'm going to check is if node is not null if it is null then we can just go to the next iteration of the loop so if it's not null what i'm going to do is update our right side to that node so you can see that after this entire loop is done executing what right side is going to have is the last node that was in this current level of the queue and since this node is not null i'm just going to take its children so node.left and i'm going to append so node.left and i'm going to append so node.left and i'm going to append that to our queue and also i'm going to take node.right and also i'm going to take node.right and also i'm going to take node.right and append it to the queue now it's technically possible that these children could be null but we know that if they are in the next iteration of the while loop we'll come back here and we'll verify that the nodes are non-null that the nodes are non-null that the nodes are non-null before we you know update our right side and it's also important that you add the left node before you add the right node and after this for loop is done executing what we have done is taken every node in the current level popped it right that's what the pop is doing and taking all the children of that level and added them to the queue so basically what we've done is removed the elements from the previous level and added the elements from the next level so that's good and the other thing that we did is we took the right side the right most node in that level and had it stored in the right side variable so now we can take to our result we can take that right side variable and append it to the result but not just uh right side we actually want right side dot value because we're trying to append the values and it's actually technically possible initially right side was null in one of the base cases you know the right side could actually be null once we've reached the last level so we're going to verify that right side is non-null so once we've right side is non-null so once we've right side is non-null so once we've done that and once this cue is empty meaning we've gone through every single level of the tree then all we have to do is return our result so there it is it's a pretty efficient solution even though this percentage doesn't indicate that so i hope this was helpful if you enjoyed like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
|
Binary Tree Right Side View
|
binary-tree-right-side-view
|
Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_.
**Example 1:**
**Input:** root = \[1,2,3,null,5,null,4\]
**Output:** \[1,3,4\]
**Example 2:**
**Input:** root = \[1,null,3\]
**Output:** \[1,3\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
116,545
|
657 |
Scientist Hi how are you I hope all doing good welcome to the land so english playlist wear completed a notification and update you are all right you all engineering display list of trains from bulk shiv watching this video please like subscribe and comment shravan ko messages robot Return to Origin Ten Little Bit Long But This Note Subscription Bill-2008 And To Play The Subscription Bill-2008 And To Play The Subscription Bill-2008 And To Play The Robot Can Know Right Left Returns The Video then subscribe to the Page 90 Jo Hai Saurav Official Ko Aap In This Will Come Down Ho Edit Welcome 800th Urs Effigy Points this point from this point zinc dros left soe hua hai return to it's original position not difficult for that in this big and right the little one down that down on one message all this thing you this is update serial updates loot or Good luck in this case against and right day that down who has just returned to it's ur alone but in this case I will go now to Vrindavan in this case where now and they definitely have any questions what will you not be able to Be Amazed The Country Which Is The Con Is The What Is The Meaning Of This Traveler Mu That If I Rise Up Down That's Going On In The Elections Which Toe Giffin Download That Definition Are Coming Be Coming Back Pune Into R Food Addiction Is Ad Akram Do n't See If You Can Assume You Said Again Came To Its Original Creation Means When - 111 Face Original Creation Means When - 111 Face Original Creation Means When - 111 Face I Is Left Misbehaving Listen From The Left Side Understand You Can See What's Amazing Just Return To 100 But Another Wise Left Is For Us So Let's A Mistake What is This Some Mistake Like My Ya Masjid Road Show This is the Moon White Think Mu and Sorry Please This is All Mahmood 101 But Now Too Variable IS Jain Vijay IS Quite Frequently Fashion More Creating a Great Swaraj Ko Decisions in Creating a Growing Up Understanding Check Out Means The White Quantity Increasing spider-man The White Quantity Increasing spider-man The White Quantity Increasing spider-man Adventure Park and Notice Decreasing Net Means Assigned to J2 Senior Research Okay So Its Practice IS Not Move On Or So K 128 Mixture Soft You Have Understood This Vegetable Sanauli Road Website Is Swaha Payment In The Women Turned Into A River Ganges So Difficult Must Try All Returns Through Others This Request Is Ultimate Return For Us So Ayo Gas Have All Of You Have Understood The
|
Robot Return to Origin
|
robot-return-to-origin
|
There is a robot starting at the position `(0, 0)`, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot **ends up at** `(0, 0)` after it completes its moves.
You are given a string `moves` that represents the move sequence of the robot where `moves[i]` represents its `ith` move. Valid moves are `'R'` (right), `'L'` (left), `'U'` (up), and `'D'` (down).
Return `true` _if the robot returns to the origin after it finishes all of its moves, or_ `false` _otherwise_.
**Note**: The way that the robot is "facing " is irrelevant. `'R'` will always make the robot move to the right once, `'L'` will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.
**Example 1:**
**Input:** moves = "UD "
**Output:** true
**Explanation**: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
**Example 2:**
**Input:** moves = "LL "
**Output:** false
**Explanation**: The robot moves left twice. It ends up two "moves " to the left of the origin. We return false because it is not at the origin at the end of its moves.
**Constraints:**
* `1 <= moves.length <= 2 * 104`
* `moves` only contains the characters `'U'`, `'D'`, `'L'` and `'R'`.
| null |
String,Simulation
|
Easy
|
547,2239
|
173 |
hey guys how's everything going this is Jay sir who's not good algorithms today let's get a look at one seven three binary search tree iterator we're implementing an interpreter over a binary search tree Ari reader must be utilized with the root node of a BST for what is BSD means smaller nodes so left and bigger nodes to right calling you next we'll return the next smallest number in a BST like this for this tree we create a iterator and next we'll return three next with seven as next of course true next night well of course so I think it's just uh first let's forget about next and hastag thing what's the order so how could we represent this binary tree in a sarnie order well of course it's in order traversal right if we're doing it in a inorder traversal we could store the nodes in you know the formal form in an array right if you got this array we can just keep internal index what which we means current index and then next has next will just be some basic operations on our array Wow right well and everything could be just be done so let's start so how could we do the indoor traversal Wow of course we walk right if we want to if we'd like to if we like to use recursion well it's simple I try to let's try to do that first use recursion well we first we walk to the root and then what we should what should we do and the result right the result is like this and then for one tree they were the only one array so weekly we don't need to create a new array and we are going to use in order traversal so we need first if food has left we walk on that root node left right and if there is no left and then it should be itself right so this is the how to say this is the array they are push node and then if node right we walk node right so for seven we walk three there's no left so we push it there is no right and then we return right so we got seven and we push it so this is it well it's done so let's say this in order would be walk routes empty so this is the another one and this index I'll say current minus 1 right so now we get next which is simple for next one we will move the cursor to the next one right so this current plus equals one and then we return this in order this current Wow this is done and this is the current X so if this current is equal to you may assume next call I was always valid that is there will be at least next smaller number ABS when X is cost so there's no overflow check if this equals to this in order dr. Nance -1 equals to this in order dr. Nance -1 equals to this in order dr. Nance -1 return false return true well this is done surely it's not cannot really push up on define oh my bad do this in order undefined ah oh my bad I forgot to return my input is why there are strings next has next ah this is the input right oh okay this is the input this is thing but what ah we just push my push note Wow should I kept a note or value I think no DS okay that's a return this one Yoder and The Vow hmm cool let's submit if it is a empty wow man okay what happens when this is empty if no net left no itself is empty okay I'd add this still not okay ah god no my bad if node and if node equals new I just say return empty not to return empty but return they are ah no check cool so I think there's nothing too special about this one so our in here I hope it helps see you next time bye
|
Binary Search Tree Iterator
|
binary-search-tree-iterator
|
Implement the `BSTIterator` class that represents an iterator over the **[in-order traversal](https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR))** of a binary search tree (BST):
* `BSTIterator(TreeNode root)` Initializes an object of the `BSTIterator` class. The `root` of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
* `boolean hasNext()` Returns `true` if there exists a number in the traversal to the right of the pointer, otherwise returns `false`.
* `int next()` Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to `next()` will return the smallest element in the BST.
You may assume that `next()` calls will always be valid. That is, there will be at least a next number in the in-order traversal when `next()` is called.
**Example 1:**
**Input**
\[ "BSTIterator ", "next ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext "\]
\[\[\[7, 3, 15, null, null, 9, 20\]\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 3, 7, true, 9, true, 15, true, 20, false\]
**Explanation**
BSTIterator bSTIterator = new BSTIterator(\[7, 3, 15, null, null, 9, 20\]);
bSTIterator.next(); // return 3
bSTIterator.next(); // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 20
bSTIterator.hasNext(); // return False
**Constraints:**
* The number of nodes in the tree is in the range `[1, 105]`.
* `0 <= Node.val <= 106`
* At most `105` calls will be made to `hasNext`, and `next`.
**Follow up:**
* Could you implement `next()` and `hasNext()` to run in average `O(1)` time and use `O(h)` memory, where `h` is the height of the tree?
| null |
Stack,Tree,Design,Binary Search Tree,Binary Tree,Iterator
|
Medium
|
94,251,281,284,285,1729
|
91 |
And listen guys Mukesh and you're looking at tempered and as always we're going to go ahead our line is 7500 decode base that you question sample is medium type and saying that the decoding methods are actually our A to Z 1234 like this And the food is Sector-26, this is our dip, so I am Sector-26, this is our dip, so I am Sector-26, this is our dip, so I am asking about the way to decode, okay, I will give you an example, how can you write 12, either you can write it as 12 or you can write 12 together. If we accept it completely, then there is a lock, when the tube is made like this, it comes and goes only once, so these are the only two ways, is n't there any other way? Look at the next example, like it is 226, how come there are three ways of this, 12226. Take away the hands of this benefit, then what should I do? Take away the voltage, fat too, by doing 226, or what should I do? Run 26, take care of today's date of birth and other things. We have to take care of any such thing which is In this case, we can say that what would have happened if we were together here, it was not possible that I could press it properly, I am giving you a note book because of this, so what is there in it that they have given more on a small exam. One thing that bothers the eyes here is that we know that either it will be a one digit number or it will be DIG or it will be a two digit number. After that it is clear that this is our domain and it is fine. Either one will be how to use tow, if something else happens then it will be from train to 9, two digit number here, it is up to 2726, if we have it in condition, then we will shoot one, what 127 one is related and here Say a different thing 2106 It is not possible, there is something, see, if you read carefully, then everything is there in reality, how will we do the painting here, value 1210 66 Now if it will be according to the parents here, then the cost and what can we do, this is also Let's accept this also, then this also happens to be this one, now you say, if you accept this then the geographical is valid, no, it is printed before zero, no, 98100 single events have not been done or are these we have you We have to accept this as tan only, this is our matter, isn't it, we fix the relationship quickly on time, okay, so only one has become for you, the interest is worn that it is ours, whose second can it be that in 106 we will meet both of them In this case, both of them will remain as friends no matter what happens and if we believe in six then this explanation will be given: this explanation will be given: this explanation will be given: Yes, that is right, you are a monkey, 1110 is 6, I can tell you in these two ways, so I will be inside it. Let us give another small example, this is a good question, meaning this small example of 121, it tells us that if we want to reach 121, then we have two ways in the beginning, but even get wealth, if we start from here in this position. Washed with you can celebrate one including India now we know that one after the other two can come in I can by a young man or 21 can become this cent tell this Dev understand the thing if there was 127 here then it is 2071 because Our 2016 is over, so there is one, so either two will come after one or 21 will come, ok, what will become the reason after tu, so this is possible, ok, second possibility is this, after 12, one will come, this is the third possibility. So there are three possibilities, the team of Titans will come up with the answer that TK Chhota Sa mine, which question has to be recorded in 'A', which question has to be recorded in 'A', which question has to be recorded in 'A', okay, there are ways to decode, we have sent the records, now there is a way to do this, which is your brute force, which means no victory. Like, whatever will be the number of lines of the word, it will be ₹ 2 on the decision, okay if it will be ₹ 2 on the decision, okay if it will be ₹ 2 on the decision, okay if we can do it in the fridge, yes, by updating it in the face, this is what I am going to tell you tomorrow morning, I have found the solution here and the pattern. I have written it in and as we have said that I have understood that the length of office and one means whatever length will be there in the starting and what to do after that. I have put this friend's function to show you that actually our With what is happening in our country, the answer is to return money, you are walking from behind, okay, walk from behind, what is the reason, see, now you understand how we are, I am updating you that from this article if I run this chord, I have taken a value, now I will show it to you, now this is life in the question, okay, the answer is 12122, which is what we want. 121 person understood that the one who sells three, then I will explain its code, because of this you will understand the whole exact thing, so in this way, our juice is of the palace due to which the output is coming three, it is okay and we will do more puja, that will be the return. 108 zero-valued in time, you are that will be the return. 108 zero-valued in time, you are that will be the return. 108 zero-valued in time, you are looking here 0338, how is it happening right now, I am going to this thing, okay then see our ghagra is initially length office 12303, so I had told 3 people, not he is saying why write like this That is - Ki to why write like this That is - Ki to why write like this That is - Ki to eni hota, that means from zero to end minus one, it is one step back, neither is written like this in the pattern, when we go back, we have to say - and if the go back, we have to say - and if the go back, we have to say - and if the last date of the lens remains then we have to Do you know how much would be 123? If it ranges from zero to 200, then ask the apps which are there, our string is the limit, if it is zero, then it is okay, otherwise go like this, it is not like that, brother, because Once is the last element, should I make it and show it to you? Yes, I will tease you a little in this matter. If this person has understood it, brother, they are good people and it is a good thing, only for those who have not understood it will be of some help that this Our second place is fine now we are checking here and saying is this school so a little late small disavar chart that let's go so fine, it should be easy to do magic, just keep in mind, see if it is like this here, if there is zero. So, we reduced the HI to zero, there is nothing like this which is ours, okay now we are going from the back, let me make you traction position on the tablecloth position and this is at zero position, so ours is like this Nisha ji. What else is ₹ 1000, what will we do by finding HIV in it, ₹ 1000, what will we do by finding HIV in it, ₹ 1000, what will we do by finding HIV in it means that I, now our kitna hai tu hai, then h2 that Ajay two, we made h's i plus one dead three, in addition to this, it became 121, so I did like this It was appointed from which here I have got it in print in the first, it has been said that this pipeline dynasty length I kitne hamara abhi tu hai this aayi hai keep in mind I have come my to my play number and urban hota hai tu plus 134 If you are not from the test team, then leave this condition, it is always a no, let's take a step back because our people are going in the opposite direction, so where did our point go, it has come here, okay, it is here, keep in mind, brother, it is like this below me. This is the value, this is ok, so now we where the powder came, one step back, so now it has become, now the first condition is asking, what is it otherwise, this is ok, let us now reverse the 1251 apk file, so Close it, okay, so this is what happened in this condition that when will one come on third, no, the right thing is now asking that i plus boon length is like this, yes now it is okay brother, whatever happens if two is shorter than that, then this Two, how should I say, our forest is going on right now, okay baby, I told you one person, how much is tomorrow's day, Mr. Ghrishneshwar, so this thing is fine, see my association of writing this condition that I was understanding that if there is a forest, then I understood you if If that is then it is possible 0 All possible All these will be found Ghr So we have to keep in mind that if our Ghaghra should be in the middle only If there is such a condition then there is such a condition Brother if there are two and what is the one in front of two then 21 is that. Allowed means we have to do the decoding, it was done in the way, so it means inch plus one side, which is this responsibility and plus 2 inch plus two 13 2011 and to add, this is 102 and this is what happened that I have cut end of two here. Come back to the point, medicine is our enemy, but it's okay at zero, I am writing slowly or said in some such language, at that time I neither subscribed 101 nor from 2016, so I will do it at its speed. We will make it 2017 latest and it has been deleted. Okay, brother, I am saying that copy its value below, let's do this, he is asking, see, all these hours are being centered, right, it is small and one too. If it is not there, then everything is on condition, then what will we do, HIV plus seat is 126 202, what is the percentage, so much God has entered in two backs, then put one more, then this is what happened because I am one plus, you and I are free. I have gone, okay, so because it is free, look here, the total food is zero, initially the position is required, now all this is over, the look that our one who - one who loves me - our one who - one who loves me - our one who - one who loves me - 60 is over and like people are over and 1000 Tell us for free, how did you like this method, how did you like it, I have subscribed this method and like it to support India, otherwise subscribe the channel.
|
Decode Ways
|
decode-ways
|
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping:
'A' -> "1 "
'B' -> "2 "
...
'Z' -> "26 "
To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into:
* `"AAJF "` with the grouping `(1 1 10 6)`
* `"KJF "` with the grouping `(11 10 6)`
Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`.
Given a string `s` containing only digits, return _the **number** of ways to **decode** it_.
The test cases are generated so that the answer fits in a **32-bit** integer.
**Example 1:**
**Input:** s = "12 "
**Output:** 2
**Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12).
**Example 2:**
**Input:** s = "226 "
**Output:** 3
**Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6).
**Example 3:**
**Input:** s = "06 "
**Output:** 0
**Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 ").
**Constraints:**
* `1 <= s.length <= 100`
* `s` contains only digits and may contain leading zero(s).
| null |
String,Dynamic Programming
|
Medium
|
639,2091
|
421 |
Hello hello friends why are we going to discuss today liquid problem photo space maxims of two numbers is there a problem on these can you also use the channel subscribe button subscribe and share and subscribe their video like share and if you like this subscribe It's okay, what will you get after the shark office in the laptop, you will get the time limit exceeded, okay, so that vehicle and we are thinking of some optimized version, we will have to think of something new, see what are the questions to listen to him, he has the credit first. Try to take the trend. What are the properties of life? What is youth? Zero is fine. 70 is what is 0 but what is 180. One means. Whenever 220 means 220 will be different then this of their youth is done by both the feet. If the piece is one or both of them, then I tell you in the rear, if both are different, then you will lose the result, then consider it as number one side, this is 1010, what does this mean, if you get your stay written, then if you No. 21 A, you have to do it once, the truth is that brother, whatever result you get, I am a traveler, what should I do, the results should be maximum, so what would you like, if there is a promise, how should the medicine be, a stranger, a problem, son, Sameer, if that is Bieber. Only then you will have to stay and someone else will have to stay at 150 ki mentioned in the tags, only then you will have that when you do Karishma Liquid Cup often, then it will be emphasized due to the rudeness of the camera. What would we like that if you always have zero at some rectangle position in the app, then it is okay for you. What should happen is that it should be closed, we should try our best so that only then what happens to you is that what you will get, maximum is necessary, see 1.00 tax sonic and if you do this then see 1.00 tax sonic and if you do this then see 1.00 tax sonic and if you do this then you will get admission on camera maximum retail, so keep this thing in mind. But we will support our group, we will metro it on all power, then we could not find out, but if you see the dress, try to pay attention to one thing, tell us if there is any problem number one and you will try to see once that your active time is 231. Okay, whatever you mean, it can neither be related 31dec, so I will see this number is active, how many total 32bit specific tumors in it, you can represent any, how will we be episode 232, like so plane, you have any number one. You can sleep 32bit on it, from here you try to think, then you have to focus in the middle, how will you use fiction in it and if there is anything else in it, then I have got such a number from the films in which it was meant that Karishma has done the best. I am one of this number or if you assemble in a one by one place meeting in India, you will take zero track and attention of me at the work place, the most significant will be as big as the alarm of butt if your partner is more benefit to the tawa, great chilli if everything is one to it What is 1010 and he distributed the laptop, brother, I understand that your life is incomplete and your dose, I assume, is 1000, so how is your festival at this time, sir's is 000 180 or career 000, if you do it. So we're going to focus on the jet Georgette with contact with AP's one on what's 540 Okay if you're exposed with often on what I'll get you'll get a zero you'll get one and one you'll get this if you over here if You get something pressed in this way, here you say that here, whatever you cut, I give you 1513 only 20, okay, so how do you try to focus, that's okay, but what do we have to do with all this, we should always focus on the most requested. It should be okay, like if you try to write here Morsi has tweeted that in the beginning there was a relationship between the two but after that it is liquid, that is, right in the middle of the night, you are going towards it, okay? This compound here, we will fry it on taking this white, okay because of this, on the left, where we will get strength, we are going to benefit, okay, so keep these things in mind that our solar 32nd conscious has information with the beat, so Here from the data that would give you a lot of benefit if you have to focus on this total soil like for example if you have this 1010 don't scare you if you have you mean you have done this left to right a great thing then what should you focus on you should focus on this Half an inch of the back side, first, what will you get, then you are surprised, second, thank you sir, if you find anything strange, then you should remember that you are in the forest, so in Andhra Pradesh, no matter how much price you will get, you will be asked, I am coming till now. This is the first erase zero if you want this if you first collided with the other in some districts Rajju bhaiya with some stuff then felt that you did not increase yours for most tweeted so keep quiet what to do all his Kanhaiya Mishra It's Allied State Karate Kid Difficult point for them to do, how will they spend the money, a very good data success, subscribe data success, what will we do with it, we will start transactions on it, number subscribe retention, okay, they will benefit from it, luck is an example and the game that will benefit us on this is 310 phases. You can print any number from the number while allowing it, you know that for you so my if you want this total from how many numbers is it right from the number and what are you doing a for a particular number you right from a means complete. You are operating an electrolyte, but if you subscribe to Twitter of a metal, please subscribe to this channel, it works, it gives you a lot of benefit now, that is, in a short time. Okay, so D. If you have read till now, then it is a very good thing. So, I am writing in the description box that you have the opportunity to read today and put it here so that if it ever happens to you in the future, it is better than yesterday, then you can confirm that Radhe-Radhe, you have then you can confirm that Radhe-Radhe, you have then you can confirm that Radhe-Radhe, you have come to read those particular topics, if you click on something. So, has it ever been shallow, it is a question of all the topics, so think that I have studied till now, but if you increase it by adding two spoons of salt, then I will give you a try. What happens in such cases, if I have used any particular or any reaction data subject? How is very easy but actually you should have conscious knowledge from that data then you must go to the description box in Titans VS Patna, you will tell me what we will do, here we will one by one, how to install sodium in all of us, what are the stupid question marks. If there is a group study room, then we say that if there are children, but we can be of off-butt rally, if we did but we can be of off-butt rally, if we did but we can be of off-butt rally, if we did chilli, then bread benefits in the hands of the districts, then raised the mixer, then others also got notifications 10 2018 Well, someone from God. Someone to fear will definitely make Grover Chetan in the children's hands and how many 302002 symbols are there but if we have to focus on cash withdrawal then 0001 then this was yours, this was done by going to the lecture and presentation on whose idea is the right repetitions Arvind Last who fitted the glass I am 31204 author plus is so what do we do here we 0123 then we will start 14% to the court 0123 then we will start 14% to the court 0123 then we will start 14% to the court all of them on 28th that number four can submit according to the former many a beta carotene thiamine were representation and when in our last There we have salt, before that we have salt here, ₹ 3000 village and before that we have salt here, ₹ 3000 village and before that we have salt here, ₹ 3000 village and crotch number, we have breads on 1010 capital, 2010, you have 10 top quality that your channel is going to sink till 2030, so you have made up your mind that its 010 means what is this 0 ok She also has children, CID, Abhijit makes Arvind Asha her hero, what is this token number, what is the lock step, the help of which method or factory at rival test and she has an affair etc. Tune this plate. This zero you have, this quarter story of zero, which unites on 10, has a hero, its hideout, you need a forest, quickly cover you here, Ghr 2011 90 So you see, description of your form, description Children of limit to otherwise you will have to put this hole in this hole, what will we do, one capsule, then what will be double, then also its symbol which is one, okay, this is closed to you, then one more 1600, so you clicked from 100 to 300, we have done this in the manner of 0018 East. You have supported so much and what was the difficulty in going ahead, friends, you should do 2000 times, then how come you have 00010, if you have 10 already, then what do you do, rather play it with you, if you provide the page directly, what would you do if you tear it apart? Others are ready to collect, either it has become and this verification has been started here Delhi's Rakhni Tu Tattoo Rakh Youth due to which the tourism department here has given Amit and from inside you the system 1000 so that Taj Loot Kabir The problem had gone away on its own. Aamir Khan created 328. If this is a rule then we will earn our money. You will have to implement it. I will not disturb you because what have we done. Have we made two children of every vote or your son? Which is before us what all the telescope monks in their atrium school absolutely versus last month in us every form is every 5 minutes so now I play you ko try 1ghz will have an affair with 1008 actress because ghee got So all of you, by doing youth puja, you will be deprived of 11100 such patients, then your spies have children, look at this, it is a very good thing, then after that, if you ever have any question mark here, then this is your bandan wise symbol again, then you If this is what you want, then the making of the symbol of the forest has started on 152 CDs. Of course, I will definitely tell you to stay connected because you are right, that is, what are we doing? You become the one who subscribes, my sweet, to everyone on the world's most significant media. Meaning Tejaswita got strength that you are informed about the time to choose the second password, right here I have told you in the report that life is going to be almost magnetic for you, if it is made zero then you will find it strange for Gujjars, how much will this night cost in most of the districts, then you will get it. In fact, if we get time, it is zero, now we have Iraq, so we definitely need you next, but I will not take anything further, there is confusion on Jio channel, so I am in front, so you will see some lucky number, this one was your number here. Till number so 336 and you got help number I got Australian most appropriate most remarkable you had difficulty keep a little patience I am one more 11100 your face will be shared if you do so sir what is this repeat na care 11401 speedy double and Again I have kept it at 0.5 inches. 11401 speedy double and Again I have kept it at 0.5 inches. 11401 speedy double and Again I have kept it at 0.5 inches. Okay, so here I have subscribed to Van Adhikar, so for this you need 500. What will you get in the most appropriate way for the tank? For Play Store, these plates are 520 profit. If you can get half the laptop done, then you can do this. All the things are in this and here you get here 10 16 subscribe we have appointment 101 of Jhala June it will be to your skin most nut partner if you that particular might have been subjected to remove v0 opposite what if home Ghee made of So who is there now, do you have an oven, this cash deposit, you get the platform and write this application again, got the cover, you are professional, it is very good that you have been in a little zero since childhood, but what happened and This must cover conversation Always someone You must go here Jewelery You must always combine this here So see now you also see the files Satya Prakash Overall, see this on the front side What is the result you are going to get Continue if you do We were able to get the most favorite size then Thandi and if there is no other then you will get the result either valve way here see that part plus 800 what is Frontier so here you get the regular tractor you have got the ticket to the camera from our richest people Now what else is needed, for whom will we find military grade three layer create companions near to front that according to Ramesh, salt elastic, if we will do everything, then try boxer, but I will get the maximum loan waiver according to us. We must be having a headache, so you will waste your time talking here. First, what is your first attempt, what justice did you do to it with the number and to set a number, subscribe, do not forget to subscribe to the video channel, then do it accordingly. घर If you subscribe 560, two duties are effective for you, then first of all you are getting zero. On Tuesday, again in the roots, you have this festival children, but if you have a sprinkle requirement, then you need the answer to this thing, if you once, then this is from the state. Despite this, children, but play that you have this chair, Raghavan, if you are more interested, you should dip this, apart from this, here in India, you will have to keep a knife in this part, you will not have to do 5ghz, if you have a request, then you will have to go with five. Task four is to ask what is nod32, this is the first task, then the second step is okay, the number is finally updated, so how many green numbers do I need for that and can I present it for admission in 32 days. Again like the earth and vitamins. Through one or the other, you can do this through the benefits places and your admission is done, use ours, this is done, set the time, we are in the ISKCON court case, we have to wish ourselves a birthday, then this is our code here before doing it. Community leadership has become meaningful, it has been divided into 11 class time, 10 minutes of notification has been passed because your behavior will be 101 square kilometer area, how will it fix it, 920 for your 0, that entry will be charged for both of you will also need it daily. According to the note, for a quick start, we have tried it by appointing a teacher in the subscribe school on Thursday. Thank you liked The Video then subscribe. While subscribing, do not forget to subscribe. 123 Do whatever it is, one left. All one life events have an appointed time and it is half an hour after checking. So if you do what you want with it then you will get it. So click on the subscribe button on this side and subscribe to my channel and if you have subscribed to my channel here. If you are angry with me then you must definitely store it on June 20, Tinder was there or not, otherwise I must keep it, then I have kept you hair, then I have made my life happy, but next time and I have made you one's channel zero, then my lamp today, girl. Do not change your Jio chiller, dip it in water, if you Chakra is a pure Chakra that when the government has not made that commission, they will make it for you and whatever you are in the last line, what will you do there, from the above we have mentioned here. Also, as soon as your last notice is definitely the role of the place, okay, you will do 3102, if you can, young man, what will you do with this jio4gvoice, help him, hand him the piece of Ayodhya verification, set salt in the lump and will harass him, for that he will roast most of the optimizer friends. Any festival function or theorem. Okay, your Tubelight is a person, so we made a temple run here, that small good song that what we did is our I tweet0. Now we will make this if you diet, whatever happened, if you do the video, along with the oven to tell your One in life - Will check the beans, tell your One in life - Will check the beans, tell your One in life - Will check the beans, if there is constipation, I made his partner sit here, one is for you, we are there, if you are children, then you subscribe 1000 500 600, subscribe 2010, if you want, I have made two here Meera Kumar Management You will have to do it quickly by pressing this button, whatever you have to like on your channel, like this pure here, 1000000, so if you click here, then you click on continue and subscribe to my channel, what will we do now? It is distributable that along with the color of good time will be from his village and the maximum answer is that the route executive rooted in coming to visit if we talk about the time here maritime what is going to happen to us additional medical is happening that and Subscribe to talk to them through any number of phase numbers and share the hatred in your mind with your friends. Do subscribe the channel.
|
Maximum XOR of Two Numbers in an Array
|
maximum-xor-of-two-numbers-in-an-array
|
Given an integer array `nums`, return _the maximum result of_ `nums[i] XOR nums[j]`, where `0 <= i <= j < n`.
**Example 1:**
**Input:** nums = \[3,10,5,25,2,8\]
**Output:** 28
**Explanation:** The maximum result is 5 XOR 25 = 28.
**Example 2:**
**Input:** nums = \[14,70,53,83,49,91,36,80,92,51,66,70\]
**Output:** 127
**Constraints:**
* `1 <= nums.length <= 2 * 105`
* `0 <= nums[i] <= 231 - 1`
| null |
Array,Hash Table,Bit Manipulation,Trie
|
Medium
|
1826
|
137 |
hello everyone let's talk about a new problem today that is single number two what does this problem exactly say is that you will be given an array of integers and in this particular array every element is going to appear thrice except for one element which is going to appear only once and your task is to find that particular element which does not appear thrice I hope the question is clear let's look at a some example now to understand it better right the first array contains all these elements right and in this array you will see that there is only one element that is four that is appearing only once in this particular array so for this array for this first example input the output is going to be four now for the second example you will see here that in the given array there is only one element that is appearing once and that element is one and this element needs to be returned so for this particular question the output is going to be one now let's try to make some observation to see how we will solve this question right now here let us look at every bit position here you will see that every number that appears thrice with either contribute to three ones or three zeros to that particular position right also the number that appears once let's say that number is X will contribute exactly 1 0 or 1 to that particular position depending on whether it has 0 or 1 in that position right so let's take an example to understand this let's say the array elements are 4 and right so if I write the bit values of these numbers I will get this right so here you will see that since 4 is occurring thrice it is contributing to 3 once at this particular bit position and since 2 is occurring once so it is only contributing 1 0 to this position similarly for this next bit position as well 3 zeros are being contributed whereas only 1 is being contributed and here 3 zeros are being contributed from d3 force and 1 0 is being contributed from the number 2 so you will see that every at every bit position we will have either 3x plus 1 zeros right or we will have 3x plus 1 once depending on the bit values of the number X right so this these 3 X right since every number is appearing in a multiple of 3 so this X could be any common number right the basically will depend on the number of will be depending on the numbers which are occurring thrice and this will be the factor multiplied because each number is a great price right so we will have these this factor 3 x factor because every number is occurring thrice for the bit positions and this one factor will come because of a number which is uniquely occurring in the I right so using this observation we will solve our question right so let's take this example only and continue forward right the elements are 4 & 2 right so when I the elements are 4 & 2 right so when I the elements are 4 & 2 right so when I write these again right what I can just simply do is I can take the sum of the bit values at every position right I can just take the sum of the bit values at every position when I do this here I get 3 as my son right I get 3 as my son and when I take its mod by 3 only I will redo I will reduce or I will say get away from all the elements which are occurring twice right I will get away from all these bits value so when I take the mod with three of three I get a zero here right similarly the process is followed here I get when I take the sum I get one I take a mod with three I get one so this bit right this bit which is here is presenting the bit which is actually left out right because when I take the mod with three all the bits which are occurring thrice in a multiples of three are being canceled out and the only left bit here is one right and here also when I take the sum I get zero and when I take the mod with three I get zero early right and when you get and whatever sum or whatever let's say the number you get in the end is actually the number which is occurring once right here I get when I take the sum of all the bit positions and then take a mod by three and the end which is not the number which is being formed is here too and I can simply say that this is the number which is occurring once now what will be the time complexity you will see here that since we are let's say we are taking n bit numbers right we are taking n bit numbers and we are going over each bit and calculating its sum so the time complexity here is going to be order of M right and what about this space complexity you will see here that let's say we are taking the only numbers or numbers up to 32 bits so I can basically take an array of size 32 and store the bits or the sum of the bits after taking the mod at every is index only and since I am taking constant space of size 32 I can say that my space complexity is order of 32 which is equal in to order of 1 only so I am taking a constant space here to solve this question and a time complexity of order of n now I hope this question is clear to you thank you
|
Single Number II
|
single-number-ii
|
Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. _Find the single element and return it_.
You must implement a solution with a linear runtime complexity and use only constant extra space.
**Example 1:**
**Input:** nums = \[2,2,3,2\]
**Output:** 3
**Example 2:**
**Input:** nums = \[0,1,0,1,0,1,99\]
**Output:** 99
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-231 <= nums[i] <= 231 - 1`
* Each element in `nums` appears exactly **three times** except for one element which appears **once**.
| null |
Array,Bit Manipulation
|
Medium
|
136,260
|
210 |
hey guys welcome back to another video and today we're going to be solving the lead code question course schedule 2. all right so let's just go over the question real quick all right so we have a total of n courses you have to take label from zero to n minus one so some of these courses have pre requisites so let's say you have zero comma one what that means is in order to take course zero you have to first take course one all right so then we're given the total number of courses and the list of prerequisite pairs so then we need to return the order of courses we need to take them as okay so there may be multiple correct orders you just need to return one of them and there are a few cases where it is impossible to finish all courses and in those cases we just return an empty array let's quickly look at an example to understand what this actually means so over here we're given four courses so four is the number of courses and these are the pairs of prerequisites all right so what is our output gonna look like so let's just look at class three so to have class three you must have finished class one and class 2. so now let's look at class 1 and 2. so to finish either class 1 or class 2 you must have to finish class 0. so obviously our first class is going to be 0 and then we can do either 1 or two it doesn't matter but we need to finish both of them and only once we finish one and two we can go on to doing class number three all right so now we're gonna first go over the theory behind solving this question and then i'm gonna use python in order to implement a solution to this in order to solve this question we're going to be implementing something called a topological sort algorithm so what this does is it takes a directed graph like for example this one which we have over here and we're going to return an array of the nodes where each node appears before the node it points to so what does that actually mean so over here so we have this graph and says and this is one of its topologically sorted order and this is actually an accepted one so what does that mean so let's say we look at the node a and we have a over here so we need to look at what is pointing to a so only b is pointing to a and what that means is b has to appear before a and it does so that's fine so similarly let's look at c so we have c over here and what's pointing to c b is pointing to c and so is a so b and a have to be before c and they are b is over here c is or a is over here and they're both before c so let's just go to eve so we have e and for e we have a and f pointing to it so in this case a and half have to appear before e so we have a over here and then f over here so similarly let's just assume that each of these alphabets represents a class one of the classes and we can implement the same logic to solve this so let's see how we can actually form a topologically sorted order from scratch so in order to do this we're going to be implementing a queue and we're going to start off by looking for the nodes or the edges which have not no arrows pointing to it so we have b now we're going to add that to our q so we're going to add b and what else do we have we're nothing so and then we also have d so there's no arrows pointing to d so we're going to add that to our q now what we're going to do is we're going to pop out the first element so we're going to pop out b and then we're going to add that to our topologically sorted order so we're going to have b over here now that b is on in our topologically sorted order we're just going to cross out b over here and we're also going to cross out all the arrows going out from b so we're going to cross this out and we're also going to cross this out now that we crossed out all the arrows pointing from b we're gonna look for other nodes which are freed up so in the sense that we need to look for nodes which now have nothing pointing to it so do we have anything like that so let's look at c so there's something still pointing to c so let's just leave that but if you look at a now that we cross this arrow out there's nothing pointing towards a so now we're going to add a to our q so now we have a and similarly so then again once we added a now we're going to pop out whatever we have in the queue again so we're going to pop out d and we're going to add that to our topologically sorted order and similarly we're going to cross out d and the arrows going out from d and now we just see if anything has been freed up but there is nothing which is freed up because of this so what we're going to do is we're going to pop out the other element inside of our queue all right so now we have a and we're going to cross this one out and we're going to add that to our answer over here and similarly what we're going to do is we're going to cross out a and all the arrows coming out of it so we have this one over here this arrow here and also this one so that should free up quite a lot of stuff so let's look at e well there's still an arrow pointing to e so we can ignore that but we have f over here so there's nothing pointing to f so we can add that to our q and similarly there's nothing pointing to c so we can also add c so we're now we're gonna pop out this element we're going to pop out f add that to our topologically sorted order and repeat the same step so we cross out f and we cross out the arrows from it and so now we have e and we have g freed up so i'm going to add that to our q as well so we're going to add e and we're also going to add g now again pop out c over here add that to our answer so we have c uh cross it out there's no arrows coming out from that so we're fine uh so i don't have space i'm just going to continue it from here okay now we have e there's nothing there so just pop it out and then add that to our topologically sorted order then we have g same thing pop it out and then just add that to our topologically sorted order so the order we got finally is b d a f c e g so let's just quickly check if this is valid or not so let's just look at g for example so f is pointing to g and f is before g so now let's just look at f so a is pointing to f and it's before f so that's fine similarly let's just say e so uh a is pointing to e and so is uh and so is f pointing to e so they both a and f need a b before e and they are a is here f is here let's just look at one last example let's say c so b is pointing to c and a is pointing to c so b is before c and so is a so this is an accepted answer and this is a correct way to do it so now what we're going to do is we're going to take our question so in our question we have a list of lists and we're going to convert that to a graph similar to this one and then what we're going to do we're going to apply the same algorithm on that graph and then we're going to get a topologically sorted order like this which is going to be our answer so let's see how we can do that using python code before i start explaining the code i just want to explain this one term called in degree in the explanation i just gave i kept referring to the number of arrows pointing towards a node and that is nothing else but the in degree so there's two arrows pointing towards the node it has an in degree of two and if it has zero or arrows pointing towards it has an indegree of zero okay so now that we understand that we can start with um solving this problem so first what we're going to do is we're going to import some stuff so from collections we're going to import a queue and we're also going to import a default dictionary so you might be asking why we're using a default dictionary instead of a dictionary like the inbuilt one in python and that's because the main difference is basically in a default dictionary when you try to access or change a key that's actually not there in that case the default value will automatically be given to that key so we're just going to create our graph which is just going to be an object of the default dictionary so default text and then list okay so now that we have this we need to have some sort of way to calculate the in degree of a node so to do that what we're going to do is we're going to create a list with zeros and it's going to have the same length as the number of our courses so num courses so if our num the number of courses we have is 2 the list of our in degree is gonna be a length of two so two zeros now we're gonna set up our graph so we're gonna do is four so pre is gonna be the prerequisite classes and then i'm just going to call final as being our the main class so for that in our prerequisites over here and we're going to iterate through all of them and to our graph we're going to add final as a key and we're going to append the pre-value we're going to append the pre-value we're going to append the pre-value okay and similarly and one more thing we're going to do is we're going to increase its in-degree value by one increase its in-degree value by one increase its in-degree value by one so in degree of our prerequisite class plus one so we're gonna increase that by one so now we're gonna prepare our q which has zero in degrees so our q is gonna equal to dq and x for x in range and then courses and then we are also going to put a if condition so if in degree x is equal to zero only if that node has an in-degree value of 0 we're going to add in-degree value of 0 we're going to add in-degree value of 0 we're going to add it to our q we're also going to initialize our topological sorted order so this is going to be our final answer and it's going to just be an empty list in the beginning so now we're going to put this inside of a while loop so while length of q is not equal to 0 we're going to keep going inside of our loop now what we're going to do is we're going to pop out whatever element we have inside of our queue so we're going to call that the node and q dot pop left yeah and then after we do that we need to append our node to the topological sorted order so it's the same steps as we did before so we're going to append it to our topological sorted order and we're appending the node okay so what we're going to do after that is we're going to iterate for the neighbors inside of graph node so the neighbors of that node and what we're going to do is we're going to reduce the in degree by 1 for all of its neighbors so in degree of the neighbor and we're going to decrease it by one and one more thing is if the in degree of the neighbor is equal to zero then in that case we're going to add that to our q so q dot append and we're going to add the neighbor all right and finally we're going to return this so this is going to keep going until our queue is empty so we're going to return our topological sorted order over here and one more thing is we're only going to return it if the length of our topic topological sorted order is the same as the number of courses and if that's not the case we're just going to return an empty list all right so let's submit this all right and as you can see our submission did get accepted and finally do let me know if you have a better solution to this and do let me know what you thought about this video and finally don't forget to like and subscribe thank you
|
Course Schedule II
|
course-schedule-ii
|
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return _the ordering of courses you should take to finish all courses_. If there are many valid answers, return **any** of them. If it is impossible to finish all courses, return **an empty array**.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** \[0,1\]
**Explanation:** There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is \[0,1\].
**Example 2:**
**Input:** numCourses = 4, prerequisites = \[\[1,0\],\[2,0\],\[3,1\],\[3,2\]\]
**Output:** \[0,2,1,3\]
**Explanation:** There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is \[0,1,2,3\]. Another correct ordering is \[0,2,1,3\].
**Example 3:**
**Input:** numCourses = 1, prerequisites = \[\]
**Output:** \[0\]
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= numCourses * (numCourses - 1)`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* `ai != bi`
* All the pairs `[ai, bi]` are **distinct**.
|
This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
207,269,310,444,630,1101,2220
|
1,997 |
Hello Everyone Means Sandeep And This Video Is Showing You How To Solve There Problem Zoom Is From 1974 Contest Came Out The Problems Like This Is The Android Platform 020 subscribe to the Page if you liked The Video then subscribe to Main Net Means The Number of Times They Do I Involved in Activities More Liquid Arun Ko 210 Tools Final Equals Protein Vitamin D No. 102 subscribe and subscribe the Channel Please [ Please [ Please subscribe and subscribe the Subscribe 98100 Id Room No. 201 The Students Should Not So S Rule Number One Contest Thursday 56001 Ko 251 Welcome To Sunao Counted As Soon As Way Go To Chief Ne Bigg Boss 2012 Sonu Nigam's Discount Now This Point Note Is The Vriddhi Room At Least One White Sesame Number So That's Why Answers Which Today Sets No Example Of The subject in urdu hindi shabdkosh-2 shabdkosh-2 shabdkosh-2 veerva 200ns Video then subscribe to subscribe our that now in this country comes forward this award winning numbers with us on his twitter 10400 ok and let's move on eggs four minutes till medium 10th ok what 100 state Congress And turn to the person himself more 087 subscribe to that it's ok so this account welcome to 98100 room number 66 Thursday subscribe thank you all subscribe my channel subscribe must subscribe to question exam date all 10 runs from CO2 in his presence not Have invented and number of times Leadership Summit held on a flat An account example and production spread It's a Veervikram Four numbers have come and the number has come from the website Special for Kabir and Vikas The Mid Point That Fans Former That Translation for Wife in All Rooms Behind Its Promise You To Ghaghare Number To Subscribe Don't Forget To Subscribe Section Subscribe Is Deep Next Visit My Request To Withdraw 0202 Click to Mode To Go For 021 Similarly Video then subscribe to subscribe Roll Number 21 Subscribe 1020 12345 number okay so let's you Dr. Tandeshwari spoon number seven now school that by you dish next number 151 the0 subscribe and subscribe the Channel subscribe plus two or today Shanidev to go to in one list mobile don't know what To do number 201 next and 151 subscribe number 212 subscribe number to cash withdrawal is on or dhal officer condition number to let mobile a that hina go to the number 3 ok nayak next step 2020 subscribe not subscribed till 2030 12 Number 2 and 100 are many and number officer ki end to veervar number to the number at number 233 destination subscribe now to receive so please ushe patal ball 10 hai vansh parichay do nitish translation vacancies of Uttar Pradesh India in this that some very dysplasias room and Is stable and number accounts and basic academic so finally I met that they number platform number 2 and now he can directly move to the number three languages one month in western plus one languages one month in western plus one languages one month in western plus one select rich so subscribe to I one translation to go to Twitter - I one translation to go to Twitter - I one translation to go to Twitter - 151 Subscribe The Latest Updates How to go afrog is coming in the next visit - coming in the next visit - coming in the next visit - 125 - One 125 - One 125 - One that will destroy you How to calculate this The best and from India and abroad Notice Patience should be needed to receive new updates 2002 Nothing but this sight Contents Number 10 2012 Contact Number 200 Subscribe To Get Rid Of Two - 20 The Witches Two - 20 The Witches Two - 20 The Witches Nothing But For Which Is The Forces To Move From 2002 Number Two That Is The Information But Will Need A Plus Form That I - One Is That I - One Is That I - One Is A Minus B Pl Hai Next Visit After - Waqt Hua Tha - Waqt Hua Tha Member Se Number Update Notice Needed To Move From Two Three Click OnePlus One Two Plus Subscribe Number Two 200 In Total Stands In Need To Move From Number 3 To Zor Thursday Subscribe To a s they have a b p five em nothing but a number of west indies live video - no video - no video - no a plus continuous formula which is nothing but two plus divine minus one a minus b p l hai next visit hak ki i - 4a ki i - 4a ki i - 4a a fixed Deposit Superintendent of Police Hotspots Problem Attack in this function inch plus b whole rooms and fixed width him a parameter this function subscribe and subscribe the Channel Please subscribe and subscribe the Channel and subscribe the wherever it does - existing models - existing models - existing models property dispute over a minus b model and Mode On Zameen Se Minus B Plus Modify Mod Student Joint Trade Deficit Reduction In Modern Family 2 Yeh To Deepti Mishra On To You For This Problem Solve This Problem So Let's Celebrate Ko Subscribe And Liquid A Number Of Rooms Sim Reap Sense Objects And Rooms At Room Setting Stop This Is A So Time Complexity And Space Complexity Of Us Assigned To Registration Issue Midwing Please Leave A Comment And Then This Video Channel And Operated By
|
First Day Where You Have Been in All the Rooms
|
next-palindrome-using-same-digits
|
There are `n` rooms you need to visit, labeled from `0` to `n - 1`. Each day is labeled, starting from `0`. You will go in and visit one room a day.
Initially on day `0`, you visit room `0`. The **order** you visit the rooms for the coming days is determined by the following **rules** and a given **0-indexed** array `nextVisit` of length `n`:
* Assuming that on a day, you visit room `i`,
* if you have been in room `i` an **odd** number of times (**including** the current visit), on the **next** day you will visit a room with a **lower or equal room number** specified by `nextVisit[i]` where `0 <= nextVisit[i] <= i`;
* if you have been in room `i` an **even** number of times (**including** the current visit), on the **next** day you will visit room `(i + 1) mod n`.
Return _the label of the **first** day where you have been in **all** the rooms_. It can be shown that such a day exists. Since the answer may be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nextVisit = \[0,0\]
**Output:** 2
**Explanation:**
- On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd.
On the next day you will visit room nextVisit\[0\] = 0
- On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even.
On the next day you will visit room (0 + 1) mod 2 = 1
- On day 2, you visit room 1. This is the first day where you have been in all the rooms.
**Example 2:**
**Input:** nextVisit = \[0,0,2\]
**Output:** 6
**Explanation:**
Your room visiting order for each day is: \[0,0,1,0,0,1,2,...\].
Day 6 is the first day where you have been in all the rooms.
**Example 3:**
**Input:** nextVisit = \[0,1,2,0\]
**Output:** 6
**Explanation:**
Your room visiting order for each day is: \[0,0,1,1,2,2,3,...\].
Day 6 is the first day where you have been in all the rooms.
**Constraints:**
* `n == nextVisit.length`
* `2 <= n <= 105`
* `0 <= nextVisit[i] <= i`
|
Is it possible to swap one character in the first half of the palindrome to make the next one? Are there different cases for when the length is odd and even?
|
Two Pointers,String
|
Hard
|
556,564
|
778 |
Hello Hi Friends Welcome Back Today We Are Going To Solid Problem Se Valid Swim In Rising Water Before We Go Through The Problem Description And Examples And Solution Is Just Want To Mention That My Channel Is Dedicated To Help People Who Are Preparing For Java Coding Interviews And Job Interviews And All My Channel More Than 210 During Exam Pulse Of Which Were Taken From Previously That According To Meanwhile Tech Companies Like Amazon Apple One Facebook Google Microsoft Yahoo And Manya Rates And That Of Problems Were Selected To Cover Important Work Hard Reset Dynamic Programming Languages Questions If You Are Related Coding Questions Binary Search Tree Binary Officer Related Coding Questions Edifice Matrix Related Coding Interview Questions Sophie A Ring for Java Coding Interview and Java Telephonic Interview Please subscribe this Channel Nav This Channel Can Definitely Help You in Your Job Interview Preparation and learning different concepts of java please subscribe and so let's go through the swimming rising water problem description you are ever in the interior matrix grade where is well being read it represents celebration at point is the rate and start form time teacher's day off Water Everywhere Is Team You Can Win From One Square To Another For Directions And Sons Where Field Only Give The Elevation Of Both Squares Individually R8 Most TV Shows This Is Very Important Solve This Problem So Which Means Data For Example From Individual Example1 If You Want To go from 0215 days You can only give 120 is equal to one given time both will have same elevation level Trailer 34 Radhe-Radhe same elevation level Trailer 34 Radhe-Radhe same elevation level Trailer 34 Radhe-Radhe statement is very important in this problem You can swim in final distances in real time of course you must win Boundaries of Greed Will Come Once You Have Love You Can Swim in Final Distance in Zero Time 100 Grams Return Last Time Until You Can Reach Bottom Right Square in - You Can Reach Bottom Right Square in - You Can Reach Bottom Right Square in - 110 - Work in Few Start Laptop 110 - Work in Few Start Laptop 110 - Work in Few Start Laptop and Planets Website Top-10 Well- Top-10 Well- Top-10 Well- Organized Two Examples Will Go through the examples and understand how they can solve this problem Problem First Let's look into this example IF YOU WANT TO START 2012 TO THE LOCATION HE CAN ONLY GIVE ONE THE LIKE TOWARDS JOYAL SALES LIKE SHARE AND YOU HAVE EQUIVALENT 12TH Example2 And Share And Subscribe Interview Problem Hai 200 Gram Palvindra When Time Frequent Tootie Retire The Rain Will Start Pouring Right One Time Is Equal To Zero Late Than Extra 120 34 Grease Also 125 1208 Solve What Is Equal To One Differences Over 100 To Go From This Point To The Self That they can see from this point to the self in this channel is water will reach wash basically 80 one time basic entries water clear basically right side time when someone from this point to this cream and after two seconds that labels of birth prevents you from one To three basically its total exit access one waiting time right to go from this point to this and distance two seconds of waiting time to go from distant to retail shop total waiting time hui head 13 to 18 basically so I can reach from this Tel 302 third Basically write a short 30 answers such lively explanation is ready also saying date and time 0 in left location right left most aspirants from where to place where you can go anywhere else development should be done directionally Addison has given bills have high value rights or you can not leave one Time basically a recent times does not reach increase filter is than they can swim in where inside the breed basically Dhairya Singh slept two basically it means reduced back pain and the rain will start point so after 3 seconds basically but after 3 seconds values Will Change It's Official Everywhere It Will Welcome Free Of Per Second 108 The Time Which Can Go From This A Tourist In Basically 5000 That Is Only Possible Wealth Of Which Can Swim Life Into Both Of His Festival Give Na Share To Sirf And Jason Trawick Direction And Sanskar And only the elevation of bones paste individually and most difficult for the celebration will win for three in this case after thirty one to three died after 30 days celebration will reach woman everywhere and time question sequence from this point to see aam aadmi to aam that is Listen the first example let's take another this app with example and they will discuss how they are going to solve this problem 100 wishes in priority queue and different priority queue handsfree is booth and solve this problem 100 BF viewers now Yuvraj in this case will give priority Q Because 512 Only Take The Smallest Cell Value Right From The First Judgment Element 16 201 Let's Make It Sure Priority Accurate So Common Way Can Go Through This Example And How Can Explain You So You It's A First Year And Celebrate 100 Decawar Targets And Decawar Satta Disawar Targets and Disawar Source Paint Shirt will start with 0n tweet0 Interwar Priority This side is absolutely 2012 Priority queue facility and in private U a Sadhu was not robbed at all Well mango checking till the priority because at least 300 happened but polling Elements from priority queue right from zero to right and will change for directionally addition element most loud 34 directions of not valid bigg boss 11 outside of the boundary but this direction is valid suvidha and one year and in this direction also that jewelery shop merger 2014 2800 flat se a hai to aap par text koi bhi lage na priority kyun hui will define true that and they the smallest element will speak in the top right so whenever vipul next time element from priority q you will always get the smallest element this is the Very Important Idea How To Solve This Problem Of What Are So Aam Sun Next Time When You Hear Calling 10 Massage Elements These Honest Souls Will Come Out Of Primitive Tribes And You Will Against Issue Of Private You Again Will Check Fold Direction Which Are Not Withdraw enmity outside of boundary 1000 related issues will not visit to-unique delight to appear for doing good to-unique delight to appear for doing good to-unique delight to appear for doing good care in priority Q 123 will also put country also will put bank details for directional adjustment points 223 loot fear into five arrested from next time When you will fall again for the smallest element from priority the thing to right to is the smallest element is clear subscribe Hrithik you will always keep the element solid by value subsidy the civil servants in sir 2324 will go now after twenty three weeks in this House Property Will Give Priority Q Will Give The Valley Always Solid Saddest Most Value Will Be On The Top Say Again They Are Doing So They Can Visit Free Life And In Which Can Visit Twenty-20 Will Visit Three Here To Your Twenty-20 Will Visit Three Here To Your Twenty-20 Will Visit Three Here To Your Health Care And It Well And so add these are the times when writing gets here Vikas your life you don't have special guest Clear Shot 120 B 420 34 This software is called Vishudh Tracks and next time 15.38 So this work has its own of three will be 15.38 So this work has its own of three will be 15.38 So this work has its own of three will be positive for the four wheel fold day 5.5 In After Five The Reserve Price Of 5.5 In After Five The Reserve Price Of 5.5 In After Five The Reserve Price Of Calling Next Small As Well As The Next Month When You Will Be 6 Fit Vikas Chaudhary Values After Hours 116 Shift 6 Basically Benefit Co Like This Chaudhary Values After Hours 116 Shift 6 Basically Benefit Co Like This 1541 Like This Right Thirteen This Is True Lines 3211 087 797 Tourist 600 Objectives pressure traversal of the great will work basically and this thing can tell stories from start to and height and width of what is the maximum value have seen in this point pure maximum value has seen in this thing from it to have to return during Saraswati Siddha 16th relief but they have seen that you can see you returning this 6 quarter answer right and yes papa this old song year and the receiver is with the help of benefits and priority queue will define in secretary withdrawal witch to the smallest value inside Top Adult To Hai Play List Look into the implementation details for this problem Our source created on small class products Nodi will hold the island jeet coordinator of the matrix only and will hold the value of the sellout fennel example year for 1000 and enjoy value are also From Se Za Roop Malaika 2010 1634 One And Heroism For The Person This Is The Not Class And They Have Created On Hunger Strike Ka Director Because For Directions For The Time For Every Location That Sophia Sending Her One Location You Can Go Now You Can Go Down Hurt you can go on right a to improve for a descendant of sexual do se locations where they can visit right the white tiger alive for directions are clear today they are and is - 1090 are clear today they are and is - 1090 are clear today they are and is - 1090 complete will and values into power current complete will and values into power current complete will and values into power current center so it's look at The Swimming Water Method Which Software Is Water In Which Gives Its Length Is Good To LinkedIn Is Created On Priority Cue Of Notes Write And Witty Sach Develop - B.Com Feet Means That And Witty Sach Develop - B.Com Feet Means That And Witty Sach Develop - B.Com Feet Means That Is It Will Always Have The Smallest Value Within Top Health Is The Lambs Expression that to user defined the positive and will start first Vinod to you want to start the or location rate shooting location and value of 0 will put into priority queue dare spegel this and after death will just creative world pimple twelfth maximum velvet result exactly maximum Value Always Like Sixteen For Example In This Case Hull Should Create A Twisted Ends Here To Keep Track Of The Self Date Were Visiting Grade B To Switch On To Day Visit To Sale Of The Matrix Hui Actually Side For Example To Elastic Out This Coloring White Reduce But Ajay Ko that super example IF you agree visiting zero not so they can visit sure again play war visiting 120 b id so they can only visit 223 basically don't like subscribe and wide it's not a wide variety of you have some elements in the giving Benefits basically benefit servi should not from which check the results will keep updating result volume maximum person don't drink and painting gift for every places like you have reduced in action motor english word this last salute software checking share if you have reached the users breakup do Aspect Otherwise Will Go In All This For Directions At All This For Directions And Dimension Now Down Right And Left His Knowledge Will Get All Discovered In It's From Our Back Wilfred Direction Fighting For Current Position Here And Want To First One 's Whole Amar Giving Out Of The Boundary 's Whole Amar Giving Out Of The Boundary 's Whole Amar Giving Out Of The Boundary Like Loot Person Center For Example One Tweet One Cigarette Daily 120 Axis Bank In Back Greater Daily 120 And Wife So Bright Days It Is Valid Self Vikas Roy With This All Can Go Outside Of The Founder Of The Matrix Also How To Check This And That Is Not Already Visit And Write Your Data Is The Case That Will Offer The New Sale New Comedy Nights And You Value To The Priority Why Hair And Villagers Market Se Tabs It's Own This Royal Look Till 2030 The Standard Implementation Of Different Great for research and will try to find out maximum value Always keep track of maximum ventilatory is the end of this target and fraternity liquid research and development will return result S8 Maximum value will remain due 100 list time until you can reach bottom right square Sudhir Chaudhary Certificate Night So Let's Check Deposit Example Over Here And Unjust Mixture Into Works On So It's K Winger Stree To It's Ki Himmat Kavita Answer So Let's Check The Another Example Dabi Gathan Hui Have Destroyed So This Is The Big Example That You Just Might Be Smacks And Videos 16s The Maximum Value Lite Band Aapt So Let's Take This One 84 You Can See It's That Bigg Boss Correct Answer Reference Giving Us Aa To Will Just Go Ahead And You Already Have Accepted Buddha Test Cases Yudh Submit Power Solution Name Is The Power Solution God Accept Belt Do It Is Pet 6 Per Cent After Another Submission And It One Per Cent After On Memory Usage Of This Very Good 100 This Is The Way We Can Solve Rising Water Problem With The Help Of Deficit And Priority Cue Shoulder Priority Cue Like This Very Important Fear Because They All Want To Get The Smallest Valid For Example Between 2nd And 23rd Seed Always Selectors Massage Value Dual Tenu Suit Select Read And Issue The Left Or Right Vikas Molested Select All Weather Updates Logic To Solve This Problem Common Queue Already Check The Play List All My Channel Find Favorites Delete Playlist Code and Solutions and Leaders Over 200 Years Different Varieties of Problems Sach Dynamic Programming Problems Binary Search Tree Problems Apni Research Related Interview Questions for Face Matrix Related Questions Tablet Screen Liquid Cooling Interview Questions Well and Aspirations For Taken From Mother Were Previously Was Coding Questions By Tech Companies Like Amazon Apple Facebook Microsoft Yahoo And Near Dasha Please Go Through It For Preparing For Recording Interview Definitely And Food Fuel And Various Other Playlist College Jaun Interviews And Acted To Frequently S Telephonic Java Interview Questions and how to answer them so if you are preparing for any job interviews in this channel will be definitely helpful to you if you like this solution if you like how does explain with example in java code please like and subscribe and your subscription is really Important to speak on this date is the videos can reach to more people the can also watch this video and that how to approach different of variety of food in problems which technique Tuesday Data Structures can you solve problems and you can also learn and you can also Get help from this video please subscribe to my channel and if you like this video please give me the like and subscribe and share it with your friends and colleagues and thanks for watching the video.
|
Swim in Rising Water
|
reorganize-string
|
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`.
The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most `t`. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.
Return _the least time until you can reach the bottom right square_ `(n - 1, n - 1)` _if you start at the top left square_ `(0, 0)`.
**Example 1:**
**Input:** grid = \[\[0,2\],\[1,3\]\]
**Output:** 3
Explanation:
At time 0, you are in grid location (0, 0).
You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.
You cannot reach point (1, 1) until time 3.
When the depth of water is 3, we can swim anywhere inside the grid.
**Example 2:**
**Input:** grid = \[\[0,1,2,3,4\],\[24,23,22,21,5\],\[12,13,14,15,16\],\[11,17,18,19,20\],\[10,9,8,7,6\]\]
**Output:** 16
**Explanation:** The final route is shown.
We need to wait until time 16 so that (0, 0) and (4, 4) are connected.
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 50`
* `0 <= grid[i][j] < n2`
* Each value `grid[i][j]` is **unique**.
|
Alternate placing the most common letters.
|
Hash Table,String,Greedy,Sorting,Heap (Priority Queue),Counting
|
Medium
|
358,621,1304
|
295 |
hello friends today that's so fine the medium from Telestream so the medium is a middle value in order to inter list if the size of the list is even there is no middle value so the medium is a mean of the two middle value so this question we are given a dear stream so we do not know the size of the data stream so for every given number we should add it to the list and we needed to if we call to find a medium we needed to return the medium value of this given list so one simple solution is we use a data structure and every time we add a number we put that integer to our list and the way will cause a fine a medium which is a salt that there are structure or maybe list or array we sought it and we choose a medium value but this is not in efficient we do not take the information of the previous course so how can we use the previous information let's see this question actually is a thought problem but the difference is that we do not know the whole array hmm so can we use a some data structure that already has this ordering information we can recall we have a data structure that is heap if we only use one heap there is no major difference from using a list in the solid again I mean sorry it every time to Cal the middle value how about who use two hips why we can use two hips let's see if we just used to one order the list we needed to get the middle value so that's the middle value but if we use a cheap we can get the picker over these two hips actually two pigs so this is the maximum value for this part this is the medium value from this part if we split by the middle this is the first part this is the second part so this is the maximum value if we want to capture the max value from a hip we should Oh save it has a maximum max hip if we want to get a minimum value from a hip you should save it as a mininum hip mini hip so that's the two hips while we can use tubes because if it's a Xochitl then the left part other smaller elements the right part other larger elements so if we get the max element from the smaller part and get to the minimum value from the larger part we can quickly cut their mean so that's the idea we can use two hip one is extending older we can release peak and then it's a maximum value the other hip is a descending order we can is hip so it's a minimum value and I said as a this max muhib save smaller elements and this minima hip we save large elements so that's the two example this is the negative three and this is negative two both at the hip so we can it's the medium is this main value of these two elements okay so you should know that currently we use two hips one is called minimum hip we save large values and the wheel we can also use another variable to record exercise instead of coal the main hip sighs every time we can use integer value for the max-heap we serve smaller values and max-heap we serve smaller values and max-heap we serve smaller values and we'll also say a Mac size so once we call the add a number let's see how many cases we have wise if it is the first number we can just save it to two mini hip so when the mini size equal to 0 we adds a number 2 min heap if this is the segmental element we already have one element in mini heap we can just save with a current number to max heap can we no we cannot because you should not you should always keep in mind that this min heap will save larger values the max heap will save smaller values so if the current number is less than the minimum heap to pick we can yeliseev the number to the max heap yes we are done but if this number is greater than the minimum hip pick then we should pull this element from min heap and save it a true max heap and the self current a number chooser minima heap because we shall always make sure the minion he saves the larger elements and max heap saved the smaller elements so you should notice this part okay if the current number is less than minimum pick it's not the first order second element is the third or fourth or whatever if this number is less than mini Heba pic that means all the elements in their mini heap are great at the internal number so we cannot mix this order so we should just save their number choose a max heap otherwise we save that element to the mini a heap so that's how we handle a new coming number but it is not unfinished usual every time calls his balance why because if we just want to use this heap this peak from these two hips we should always make sure the difference of this to his size should be less or accordion one so once the difference of the size of these two hips is greater than one we should pour one element from the larger hip to the smaller hip so once if the max size is greater than meeting size we offer one element from Max hip to mini hip otherwise we offer one element from miniature max hip so that's it regarding the fine medium that should be simple we just return if these two hips have different size we just return the peak of them of a larger size otherwise we get the mean value of the pigs of the two hips okay so let's write a code we should use two priority Q 1 is minimal hip maybe their priority Q integer max heap we also use minimum size and their arm exercise now let's do the initialization meaning a heap will save the extending order right let's record this is mini he will again is minimal so it's extending order it's a give order in the priority queue but a further max heap we should revise this order we can write a number a be B minus a we can also use some connections revised older just a change the older and mini size should equal to zero max size equal to zero okay now here comes ad number if the mini hit okay the mini size equal to zero we just put that number two mini hipa at the same time mini size increment by one we return if the max size equal to zero we have some issues to handle here if this number is less than mini hippo topic that means because we needed to save smaller number in a larger heap small numbers to the max heap so it follows this rule so we just saved this number to make skip at the same time max size increment by one if not the case that means we need to swap so we max heap will offer the number poor from the minion heap and we offer that a new coming number two mini hipa a same time okay we're just right here because whatever we need to increment the size of the max heap and we return if not this to case well we should check if this number is less than all the numbers in the minimum Heba we put that number to max heap and the max size will increment by one otherwise me möhippa will offer that number the meaning size increment by one and we also call this balance function okay private Boyd parents what shall we do here if the mass absolute value of the meaning sighs - max size is less all great sighs - max size is less all great sighs - max size is less all great accordion one which has a return it is valid otherwise if the max size greater than meeting size we just move one element from max hip to medium hip so many hip will offer the max heap poor something same time the max size will decrement by one mini size will increment by one as otherwise is max heap of this medium hip then the meaning size will decrement by one max size will increment by one okay yeah so the fan minimum should be simple if the max size created a minion size we just return the max hip topic if the meaning size greater than max size we just return mini hip topic otherwise you get we just return the max heap picker palace meaning hip picker divide 2.0 we should add parentheses divide 2.0 we should add parentheses divide 2.0 we should add parentheses okay mm okay I miss a semicolon okay thank you for watching see you next time
|
Find Median from Data Stream
|
find-median-from-data-stream
|
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.
* For example, for `arr = [2,3,4]`, the median is `3`.
* For example, for `arr = [2,3]`, the median is `(2 + 3) / 2 = 2.5`.
Implement the MedianFinder class:
* `MedianFinder()` initializes the `MedianFinder` object.
* `void addNum(int num)` adds the integer `num` from the data stream to the data structure.
* `double findMedian()` returns the median of all elements so far. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input**
\[ "MedianFinder ", "addNum ", "addNum ", "findMedian ", "addNum ", "findMedian "\]
\[\[\], \[1\], \[2\], \[\], \[3\], \[\]\]
**Output**
\[null, null, null, 1.5, null, 2.0\]
**Explanation**
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1); // arr = \[1\]
medianFinder.addNum(2); // arr = \[1, 2\]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3); // arr\[1, 2, 3\]
medianFinder.findMedian(); // return 2.0
**Constraints:**
* `-105 <= num <= 105`
* There will be at least one element in the data structure before calling `findMedian`.
* At most `5 * 104` calls will be made to `addNum` and `findMedian`.
**Follow up:**
* If all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?
* If `99%` of all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?
| null |
Two Pointers,Design,Sorting,Heap (Priority Queue),Data Stream
|
Hard
|
480,1953,2207
|
35 |
Hello Gas Myself Amrita Welcome Back To Our Channel Technologies So This Is Read Code Series In Which See Are Solving Lead Code Problems One By One If You Also Wish You Join Us You Can Subscribe To Our Channel And I Mention Date Geet Tripulink End Description Box You Can Check Out Doors Which You Are Doing in This Series So Nine Let's Move Forward with Today's Problem is Problem Number 35 Date Search it in Search Position So Let's First Understand D Problem Given an Sorted Array of Distinct Integers and a Target Value return d index of target is found so in the example you can see we have bin given names are and target 5 so see you search five in this particular are you can see every it exists at position you so output should be you and if it Is not found then you need to return d index where it should be inserted in order second se this is sorted are so if c have you search plus you write this note while in this particular right one come you come three so date mens it should By adding the index WAN and all its elements would be shifted by WAN correct and also you must try an algorithm with O of log and run time complexity so you have to make sure what ever approach you are using. Complexity of O of people so nine let's move forward and let's understand what we are going to do to solve this problem so let's see we have de here 1356 and your target element is five correct so in this case what should be the output Let's try than let's zero one too three so if your target is 5 what should be output it should be too correct and let's say if you are target one what should exist without exist between three and five correct after three so after three should be index You so date mains output should be too correct but nine lets say if see you have search zero target it zero which is out of de sure correct so it should exist before van so date mains where should it texas it should it exist and the 0th index And let it become first index tu three for similarly if you are target let it be 7 where should exist after 6 + 1 date is 7 so date 6 + 1 date is 7 so date 6 + 1 date is 7 so date mains 3 + 1 date is four Swar output should be needed mains 3 + 1 date is four Swar output should be needed mains 3 + 1 date is four Swar output should be needed you find d output if see have tu Search a target element which exists and which doesn't exist so now we have to things right when these are sorted and inside when we have to achieve people time complexity so whenever we have these things to find a particular element These are unsorted and also you need to live with me time complexity give you don't think of any other approach directly it should come you are mind since you have these up you binary search if you have these You Things Remember This Point Nine Send D Binary Search What Do You See Do See Divide The Arrange You Are Half Using Riddle Element Correct End Index last element date is 3 correct so date min 0+3/2 which is equal to 3/2 which is 1.5 which is equal to one 0+3/2 which is equal to 3/2 which is 1.5 which is equal to one 0+3/2 which is equal to 3/2 which is 1.5 which is equal to one so date is your middle element should be added first index so date is your middle Element nine in step number you will be checking if your number comes in middle index is equal to target element so can directly check if your number comes in middle index is equal to target element then you can directly write in middle in next in this Case Number Aate D Middle Index Is 3 Will Be Checking Weather Three Is Equal Tu 5 Sunao Si Need Tu Decide Weather Si Need Tu Search Equal Tu Target So Date Men's Here This Number Would Be Greater Give Target And This Number Can Be Less Give Target Correct And number index jump b less give target so in both d cases what are you going to do let's c date if number come d middle index give it 3 if it is greater than 5 so nine let's understand which case is match every target is five and Number Pregnancy Index You Right Which Middle Plus One Change Date Would Become Middle -1 Let's See This Box Again You Have You Repeat These Steps Nine See Are Left With Five And Six So What Is Your Starting Next And This Is Your End Index Correct So Gan you have tu repeat de se steps so de start in next is date let me right give nexus every so this five what is start tu plus 3/2 date is 5/2 start tu plus 3/2 date is 5/2 start tu plus 3/2 date is 5/2 date would be equals tu 2.5 which is equal tu date would be equals tu 2.5 which is equal tu date would be equals tu 2.5 which is equal tu right nine Middle element so date mains number come d middle element is five wether five is equal tu target yes correct mens c can return d index directly so d output should be five sorry give output should be tu because c need tu return let's see this case are target Element zero which DOESN'T exist in this particular are so you are going to find out tha one so see you have to follow de se steps so firstly middle element date would be from date would be zero plus three by you 1.5 which is equal to Van right so you 1.5 which is equal to Van right so you 1.5 which is equal to Van right so this is riddle element will check whether number at d middle element is equal tu target date mains is 3 = 0 no right date is false move mains is 3 = 0 no right date is false move mains is 3 = 0 no right date is false move tu d next step wheter your middle element is greater than zero and less than zero so 3 is Greater give zero right so 3 is greater give zero so date mens it should exist before three correct so it cannot exist every it would exist only in this part of the are so date mens are left with only one element start index remains from end Index is middle -1 and remains from end Index is middle -1 and remains from end Index is middle -1 and index becomes middle -1 so this is d index becomes middle -1 so this is d index becomes middle -1 so this is d start index so end index is also d se which is index zero right so again repeat d se steps nine start is zero and is zero which is equal to zero right so middle element is zero so see are checking weather your middle element date is van equal tu zero right again van give it greater zero so date mains your end index is middle -1 what is your date mains your end index is middle -1 what is your date mains your end index is middle -1 what is your middle zero minus van date is equal tu -1 correct -1 correct -1 correct -1 so date mains in this case nine your start -1 so date mains in this case nine your start -1 so date mains in this case nine your start index is zero but you're end index becomes -1 correct so go back again and remember c have tu becomes -1 correct so go back again and remember c have tu becomes -1 correct so go back again and remember c have tu run this loop while your start index less give equal tu end index So when come back every nine start index is zero less let equal tu -1 this condition becomes false so let index is zero less let equal tu -1 this condition becomes false so let index is zero less let equal tu -1 this condition becomes false so let see don't need tu go tu d next steps c can directly return your start index so whenever you have tu find d target element with daint Exist In D Are When You Are Condition Get Field You Can Directly Return Your Start Index Let's Test It With One More Example To Understand This Gather So Let's Say If C Are Searching The Elements 7 Right 7 Again Middle Element Is 0 + 3 / 2 1.5 Which is equal tu van Correct 0 + 3 / 2 1.5 Which is equal tu van Correct 0 + 3 / 2 1.5 Which is equal tu van Correct so they have already seen this van middle element so nine is 3 = 7 no right falls come made less give again give what do see start index is equal tu middle plus van Correct Middle East van plus van Commerce seven should exist in this part of the arrangement let's repeat d se steps again nine what is your start in next tu plus three by tu date is 5/2 which is plus three by tu date is 5/2 which is plus three by tu date is 5/2 which is equal tu 2.5 which is equal tu right so equal tu 2.5 which is equal tu right so equal tu 2.5 which is equal tu right so date mains jo middle Element is five let's check weather 5= target no falls is 5 < is 5 < is 5 < 7215 middle plus van tell start mains nine you are left with only van element date is six so date mains date is also three and those also three correct let's repeat steps 3 + 3 / 2 witch is repeat steps 3 + 3 / 2 witch is repeat steps 3 + 3 / 2 witch is equal tu three right so date mains six weather six is equal tu 7 six is equal tu 7 six is equal tu 7 false right six ≥ 7 pro middle plus van what is your middle 3 + 1 middle plus van what is your middle 3 + 1 middle plus van what is your middle 3 + 1 date is your four so if let se seven was there denier should i Take Exist After Six Write Date Mains Here It Should Be 7 At D Fourth Index So You Can Return Your Start Index So Wherever You Are So Remember Wherever Target Element Doesn't Exist In D Are Once You Do The Steps You Will Find Date At The End Your Start index should be and output so date mens your target elements you will take just come d start in next right I hope you understood d pras now let's move on to d solution this is un class date is search and search now let's try d method so date would be public static in search element right and give what was your first step is you find d start in next date would be on last element which would be use.len use.len use.len -1 do middle index respect vice see need you check Weather it is greater give target and less give target if it is greater than target give see need you shift r end index date wood b mines van right respect vice start in next wood b middle plus van r start d print statement van right let's take sam Respect input which DOESN'T exist in diary for example 9 so it should exist after seventh so vacancy d code every let's start see can see every it is accepted and when time it gets zero seconds so see can same with d code right this is ho C need to solve this problem if you have any other questions and outs please let me know in comment section and please don't forget to like share and subscribe channel thank you for watching
|
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
|
204 |
so that means if the there is a number let's say six so what are the prime numbers which stick to less than six so it will be adding by 2 3 then 5 so you want to return the count of this numbers so you have to write a three as the answer so that is what the triangle is so usually what we can do is if they tell n equal to 100 and so for in I equal to another phone and check whether n modulus I if it is in the sense of in each number you have if whatever you take so if I equal to two head so again energy so J equal to 2 I have to run them and check now I know this J is it equal to zero so if it is equal to 0 then that will not give and it's not equivalent zero then you add that as a prime number so that is usual method but here you will not use that in this C wolf is using here so first I'll explain the intention behind the algorithm so let's say n equal to 10 so we know if n equal to 10 what is the prime ministerity less than that 2 three so four is not five no six seven then eight then yeah these are the prime numbers present so you need to have the answer as four so what we'll create is so first we'll create an array of size n so why and that means zero to nine because since 10 cannot be here uh prime number we are including it is an area of size 10 will be created as n so here it will be 0 1 2 3 4 5 6 7 8 9. so once you have this high let this array be of type boot here and set all the elements to true so all the elements will be true so all elements are set to true so at the beginning initially where just assuming that all elements from there in 0 to 9 that is less than I are prime numbers so that is the main intuition here suppose you create an array of size and set boot an array and set all the elements equal to this is 0 tonight but the actual array is this so this is the array and this is the indexing now what we have to do so next what's outside all the elements equal to row next what you have to do is number so we start from now for two whatever are the multiples of two you have in Array make it as false so we see here too so 4 is a metagraph two so make this response so this will become false next six is a micro F2 false then again of a 6 8 is 2 so it will also become false then so after 2 now go to three so again make the metal of the response so 6 is already false foreign so for that and see so here I'm just explaining because see for two you're making success for us you can further you need to make successful enough so we start from line itself that is fine so for example for 4 we start from poster four why so that will be made as possible of two four three the diet will also be made forced by a Microsoft code for first 16. so from there you start so that complexity right complexity will get reduced very much for the larger numbers so once you made all these as false next again go four for four step one present five star five not present six or percentage seven or percent eight so this is done so often wants to make it off once now we can clearly see so two if you see in the array two three five and seven are two and zero cannot be or you cannot be a prime number so you start from identifying the length of the new Travis whatever elements are true there is two three five and seven all their prime number so keep on incoming count by one man for each of the elements so if I need to write a pseudo code so first you create a array of size n so here it is an array of size 10. and you set all the elements to okay so once you're setting all the elements into no starter for and I equal to I lesser than you should we go to n no I represent square root of n is fine because that will cover all the cases because as I expected if we have number let's say 60. so two further it and four equals a 16. so in two only we have got the four so again for 4 is do you need to take four to side sorry I'm just getting confused in simple words I tell number is eight so if we know the multiples of 8 lakh two false are eight and four times will do it by two you know eight modules to equal 0 so 2 is a multiple of eight is a matter of two then again it will have a multiple acid so here we will get two and four Leonardo take this so that's the same intuition here also to describe the family mat type square root of 8 only so same here you take the square root of n then inside again here you have to check here while before making a material of all the multiples of that element to false you have to check whether that element is true or not if that doesn't make it as false so it is false you will not make multiples of four and false then connect Ed to check if I mean if I have is I already said to true then keep on multiplying the making the false multiple of that particular number is false so that will be incredible and for the pony so for J equal to as I said it will start from I staring why when you come to 6 here or 3 6 again false may not be done because 2 only make it six are false sorry so I started and say less than n d Plus to make them as false array of yeah software always at last count equal to zero then run the for Loop from I equal to end of the array so if is I equal to then increase so we shall start programming so first we will have a array let's name this is prime so of size n and set all of them to so next for what we need to do start groupings of all and I equal to 2 I lesser than n i plus so if a is prime of I in the second two then make its all multiples response for in J equal to I star I X to the N J plus so here you could see we are starting from command and the length is directly 0 is the answer so if n is less than or equal to lesser than two written or equal to because it is and here instead of n we have a x square root of n so once inside all of them performs so the slope is done so next again in count equal to 0 we will have so again and the follow foreign sorry okay one more minute here so if you press the button here instead of J I have taken J plus equals to I why sine will take a multiple of 2. so after two I need to go to 403 so if I have 3 and I start from 9 often I have to give O2 9 plus into n not ten so that's why J plus equals to I am yes so for Java also it's pretty much the same thing so here you cannot directly us set it as to so manually so I'll submit this one through yeah successfully submit if you understood the concept please do like the video and subscribe to our Channel we found a few other medications then keep learning thank you
|
Count Primes
|
count-primes
|
Given an integer `n`, return _the number of prime numbers that are strictly less than_ `n`.
**Example 1:**
**Input:** n = 10
**Output:** 4
**Explanation:** There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
**Example 2:**
**Input:** n = 0
**Output:** 0
**Example 3:**
**Input:** n = 1
**Output:** 0
**Constraints:**
* `0 <= n <= 5 * 106`
|
Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better? Let's write down all of 12's factors:
2 × 6 = 12
3 × 4 = 12
4 × 3 = 12
6 × 2 = 12
As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n.
Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?
public int countPrimes(int n) {
int count = 0;
for (int i = 1; i < n; i++) {
if (isPrime(i)) count++;
}
return count;
}
private boolean isPrime(int num) {
if (num <= 1) return false;
// Loop's ending condition is i * i <= num instead of i <= sqrt(num)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
} The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple.
Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" by SKopp is licensed under CC BY 2.0.
We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well? 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off? In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition? It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3? Yes, the terminating loop condition can be p < √n, as all non-primes ≥ √n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime.
The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia.
public int countPrimes(int n) {
boolean[] isPrime = new boolean[n];
for (int i = 2; i < n; i++) {
isPrime[i] = true;
}
// Loop's ending condition is i * i < n instead of i < sqrt(n)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i < n; i++) {
if (!isPrime[i]) continue;
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i]) count++;
}
return count;
}
|
Array,Math,Enumeration,Number Theory
|
Medium
|
263,264,279
|
41 |
hey what's up guys this is sean here so uh so today uh let's take a look at today's daily challenge problem uh number 41 it's a very early problem so first missing positive okay so the description is pretty very straightforward basically you're given like unsorted integer array find the smallest missing in positive integer for example this one right so i mean the first missing a positive integer is three here and this one is two and this one is one okay uh let's just forget about the follow-up here the follow-up here the follow-up here so what's gonna be the most naive solution right i mean the most naive solution will be uh we just uh we need to sort it uh not sorry we don't need to sort it i mean one of the thing is that you know we just need to try from one to n basically you know the length of the numbers and the length of the number we just need to get the length of numbers here and then we just need to try uh try n times so why is that because you know if from let's say we have four numbers here so the worst case scenario is this is one two three four right so that's the worst case scenario which means that everything is uh everything from one to four is here so the first missing number will be five in this case otherwise as long as there's anything that missing here which we just need to loop through these four numbers and then we'll definitely find that okay so to do that i mean it's very simple right so we just need to convert first we convert the numbers to a stat okay now we have a set here so and we have n here length of the uh numbers so all we need to do is we just need to do a height in range of n here of n uh and plot m plus one i think yeah we can do this one yeah one to m plus one right so i mean if the i is not in the num set it's not if i is not there we simply return i right otherwise it's this case basically everything from 1 to n plus 1 is in here so which means the n plus one will be our answer which in this case is five right so that's that i think this should just work i'll just submit it yeah so pretty straightforward right i mean so the time complexity for this one is like the uh it's all of n right so and here is also of it so the time complexity is o of n and the space complexity is also o of n because we're maintaining a set here and here is like o one right okay and then the follow-up so we okay and then the follow-up so we okay and then the follow-up so we have one already but can we use constant extra space here i think this is what makes this problem a little bit interesting tricky because you know uh so you know to be able to utilizing like to make to be able to make it like a constant actual space uh we have to somehow use the original numbers field here the original numbers list here so that we can do some markings on that okay um and the way we're doing it is that is the uh we'll be using the uh you know since we don't want to like miss the uh the numbers we don't want to lose the number itself so one of the technique we can use here is we can revert this number basically we revert this number from positive to an active so whenever there's a negative number we notice that okay that number has been already has already seen before so basically we're using this index to represent that number so that i mean so the first for loop right the first photo points that will be a basically okay let me try to write this thing here so the first for loop i mean uh we will remove we'll remove the invalid numbers so what are the numbers that is invalid first one is the ones that uh that's the uh it's smaller than zero okay that's definitely an invalid number and how about the others like the numbers that's greater than the length of n here because we know the missing numbers has to be between the one and n here that's our missing number range here so for anything that's outside of this ring we can simply uh invalidate them so we do this so i in them in enumerate nums okay so if the num is equal small uh smaller than zero okay if it's zero or the number is greater than n so we just mark them to uh we just mark them to a like a big a very huge number like nums you know like the uh we so we don't want to mark them to an active negative numbers because we'll be using a negative number later on so i mean so the easiest way which market to uh n plus one okay basically anything each which is greater than n later on will be treated as an invalid number so now the second loop is because we just need to put and okay and the numbers here right so we're going to use uh we're going to convert this number to its absolute value why is that because you know uh when we are marking uh processing the card numbers those numbers could have already been like converted to its negative version that's why to be able to get the index we need to convert it to its absolute value and then we only do this whenever this thing is visiting the end right because we know that our ranges is in the numbers we need is from one to n if anything that's greater than n here we simply ignore it now we have index here right so the index is like this because you know the number is one base and our index is zero based so and what we're doing here is basically what if the numbers that index if the current num the current index uh the number of current index is pointing at is greater than zero we uh we convert it to an active value okay so why we're checking this because this is just to avoid like double uh double reversing here because you know if it is a negative numbers and we are doing this one more time and the negative number will become a positive number which will be losing our point the purpose of marking it to an active okay so now after this the second for loop here as long as this index as long as the values on this current index is an active value then we know okay we have seen this number okay and so that we just need to do this in range so now we just need to loop through this one last time basically if the nums in the i here right is greater equal or greater than zero okay then we know okay fine uh zero okay i think we don't need equal here because for zeros we have already converted to n plus one here we just need to return i plus one here in the end same thing here if none of those works and then we return unplus one okay submit yeah so um and in this problem as you guys can see so now we have a basically we have a three fold up here n plus n and plus n so three n still o of n okay and the space complexes is one because we're not introducing any of this the new list here we're basically marking the we're utilizing this technique here you know i think for this problem i think this is the technique you might want to master right or understand basically uh we mark this number to its we uh we mark this number to its negative versions to mark this something to flag this number while we're still keeping this value of this number that's one of the technique i mean when it comes to uh to marking off marking the uh the numbers in the array yeah and other than that it's pretty straightforward right i mean i think there's a few like corner cases you might be careful i mean be careful of but other than that you know for example how can you handle the zero case here right i mean in our case right because we are uh we're treating zero as an invalid number that's why we are marking everything including zero be uh smaller or equal to zero to a to an invalid number also the other side cool um yeah i think that's it for this problem yeah thank you so much uh for watching this video guys stay tuned see you guys soon bye
|
First Missing Positive
|
first-missing-positive
|
Given an unsorted integer array `nums`, return the smallest missing positive integer.
You must implement an algorithm that runs in `O(n)` time and uses constant extra space.
**Example 1:**
**Input:** nums = \[1,2,0\]
**Output:** 3
**Explanation:** The numbers in the range \[1,2\] are all in the array.
**Example 2:**
**Input:** nums = \[3,4,-1,1\]
**Output:** 2
**Explanation:** 1 is in the array but 2 is missing.
**Example 3:**
**Input:** nums = \[7,8,9,11,12\]
**Output:** 1
**Explanation:** The smallest positive integer 1 is missing.
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`
|
Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)
|
Array,Hash Table
|
Hard
|
268,287,448,770
|
1,572 |
hello friends welcome again to my youtube channel today the problem that we are going to discuss is matrix diagonal sum problem number 1572 of lead code before starting if you are new to the channel or if you are watching this video first time please don't forget to subscribe and share among your friends also do watch this video till end because it will clear your all doubts regarding metrics so let's get started let's read out the problem description first given a square matrix return the sum of matrix diagonals only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal read out the example to make it clear of this statement so matrix can be of any like 2 cross 2 or 3 cross 3 2 cross 1 also it is not a square matrix so the primary diagonal it is showing something like this one five and nine and the secondary diagonal is three five and seven now if we try to sum them one plus five plus nine plus three plus seven so here we are ignoring five that is part of both primary and secondary so we don't have to sum it two times right so here you can see notice that the element equal to five is counted only once right so for this our program should return 25. likewise there are some other examples let's go to the blackboard for it yeah so here you can see we have two examples one is of two cross two and other is of three cross three and once again it is not given in the problem that it can be a square matrix it can be of any m cross n so what will be this element it will be 0 this element will be 0 1 this will be 1 0 and finally this will be 1 likewise there is 0 1 and 2 here also will put 0 1 and 2 this will be 0 this is 1 this is 2 right and this will be 0 2 1 and two zero friends you can see some similarities you can see with these two examples this both are equal right 0 1 2 3 4 right so if we iterate our 2d matrix and if we say this is i and this is j then we can say that our i double equals to j will form the primary diagonal so now we found our way to calculate the primary diagonal so when we iterate our 2d matrix and when we have i is equals to s double equals to j then we will found our primary diagonal right now likewise is there some math logic with this secondary diagonal you can see so let's drive that so we can see zero one then one zero right this is for the two cross now zero two plus one plus two zero this is for three cross three now let's see the pattern so here you can see i is increasing 0 1 right so i is increasing n minus 1 if you can see here if we say this is n and this is m right so our i is varies from 0 till n minus 1 i value and what is j value is decreasing right it was first n minus 1 and then it comes to the zero right so this is the combination if you can see here also 0 1 2 1 0 what was n here and was 3 right so if n is 3 how i will be increasing 0 1 and 2. and if m is 3 how j will be decreasing it will be 2 1 and 0 right now how we will check if this combination occurs so when i 0 j is n minus 1 now this we have to derive i in terms of j right so here you can see j is equals to n minus i so we have to move j here and i here right so what it will be i is equals to n minus j right so this will be our other condition to find the secondary diagonal now when we have for our primary so this is for the primary and if i double equals 2 and minus j this is for the secondary diagonal right but so in both the conditions we are counting this middle element also right for the and cross and right so if we can say if this executes then this shouldn't be and if this execute then this shouldn't be right so we can put this in if and else if block so that if this condition occurs then this won't occur so that we can avoid the double count of this 5 in the example let's look into the code so that you can get better understanding there so here we will first take one variable which we will return as the answer so diagonal sum we will return which will be having the sum of both primary and secondary diagonal right now we will write the logic to traverse the matrix and this will be so what i am doing here this i is iterating till the column length right 0 1 2 so there are three columns and it will iterate 0 1 2 right for the example one so let's take this also into one variable for the row iteration and this will be our j and this will get iterate till mat of i dot length right let me tell you so mat of i right of i is let's say this we are talking about this zeroth so this will go till sorry this was for the row the outer loop was for the row and the inner loop is for the column now we have to write that condition if i double equals to j okay then what we will do we will update our diagonal sum and do diagonal sum plus mat of i j so this condition is for the primary diagonal similarly we will write for secondary diagonal cool so here we will so i hope this should work and at last we should return our diagonal sum oh sorry cool you can also write something like this shorthand operator we can use it try to run this code okay it's showing wrong answer i might have done some mistake see um okay length minus one yes so length i am taking matte dot length it should be at dot length minus 1 because we are considering from zero now let's try to run again we should take math dot length yeah cool so it is accepted try to submit this code yeah so you can see so yes friends that's it for today i will be providing the problem and solution links into the description also if you want to join you can join us on telegram i will post the link into the description because we are uploading many study materials there and also we are doing daily quiz competitions there
|
Matrix Diagonal Sum
|
subrectangle-queries
|
Given a square matrix `mat`, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
**Example 1:**
**Input:** mat = \[\[**1**,2,**3**\],
\[4,**5**,6\],
\[**7**,8,**9**\]\]
**Output:** 25
**Explanation:** Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat\[1\]\[1\] = 5 is counted only once.
**Example 2:**
**Input:** mat = \[\[**1**,1,1,**1**\],
\[1,**1**,**1**,1\],
\[1,**1**,**1**,1\],
\[**1**,1,1,**1**\]\]
**Output:** 8
**Example 3:**
**Input:** mat = \[\[**5**\]\]
**Output:** 5
**Constraints:**
* `n == mat.length == mat[i].length`
* `1 <= n <= 100`
* `1 <= mat[i][j] <= 100`
|
Use brute force to update a rectangle and, response to the queries in O(1).
|
Array,Design,Matrix
|
Medium
| null |
215 |
hey everybody this is larry this is day 22nd of june uh of deletecode daytime hit the like button hit the subscribe button join me on discord let me know what you think about today's problems a problem cave launches element in an array which is taking his time loading technology is hard how's everyone doing uh it's rainy here in new york so i got i would say i got soaked but i am a little bit wet so yeah hopefully i get to solve this problem quickly and you know just get it over with unfortunately uh unfortunately i don't know what's going on here what's everyone doing i'm just all right let me refresh you refresh your work oh there you go all right sorry for the long intro friends try to do these live and you know try to uh you know just uh be as fresh as possible anyway so given and away numbers are the cave largest element in their way know that cave large spending sorted order not the cave distinct element okay um i mean they're always couple i think there are variations on this problem that's why i'm like trying to think about what to say um and you know um just but that's it this is a ways standard problem uh the cave largest element uh yeah so you just have a min array of the elements and then remove them right so that's gonna be like k for each element and log k um so the variations that you can see is that how maybe you need to do it multiple times maybe you need to um you know maybe there's some weirdness with distinct elements and stuff like this but for now if you like it should be okay i feel like we should be able to just make it a standard heat problem of you know and then the first question about heap things is whether it's just thinking about whether it's a maxi or mean tape right a max c has the max number thing and a min heap as the min element and here we want the main heap because we want to have um we want the heap to contain all the largest um uh elements so that when you remove it you remove the k plus one biggest element and so forth of course you can also sort and then just like return k but you know you do lose some in the log k versus log n which um if i was in an interview or sorry if i was on competitive it doesn't matter right because log k log n usually it doesn't matter sometimes they could write in a way such that matters but for the most part it doesn't matter um because log n and log k is just like way small difference in general that said if you're on an interview they will always you know they know what they're doing they'll ask you about it or if they're nice they'll ask you about it if they don't that means that uh they already gave up on you a little bit or maybe they're just like bad at interviewing which is also possible but in any case so try to do it as optimal as you can uh so let's get started so heap is to go to a heap um so we want to max heap as we said and we get a min heap here so let's um let's uh write some helpers here so we have a thing um and the thing that i do with heaps and uh one thing i would also say is that this is a way maybe this isn't a good thing because i think in other languages you can overload the sorting function or the comparison function in python not so much as far as i know um which makes it kind of painful to be honest because then we have to we to hacks like what i'm doing now where um you know it by default it's a min heap so to get a maxi you can think about multiplying every number by negative one and therefore you know in the push and the pop i have to make it up here to kind of you know so that it's easier to think about and use as a abstract data type um but yeah okay so then now we have four x and nums uh we can say you know we push x and then now while length of heap is greater than k we can pop and that's really all that is and then we return uh h of uh the top right because the top grab the smallest number and i'm just looking at the constraints really quickly to make sure there's no weird edge cases like numbers have zero or k is bigger than nums or something like that um so otherwise this looks okay let's give it a quick submit uh not submit but one test um and this is why we won tests because of these typos i always forget that not gonna lie the python heap thing is a little bit weird and i don't know why that they don't have it in a standard library with you know uh very well designed things maybe they are and i'm using like an old one though to be honest uh oh you have to yeah they're just very returned so this seems maybe i'm off by one the k smallest number okay so that means so k is basically one index right so what we want is actually k minus one so yeah so let's do yeah um because that means that we want to remove the k for elements i think here we oh did i messed up uh hmm so we want exactly k elements no this should be good right did i mess up maybe i messed up somewhere uh okay yeah the top element should be the smallest wow man maybe i am more red than i thought uh okay did i mess up k is two output is five oh largest i returned the smallest for some reason um how did i return to s'mores for some reason i did the one given now max heap so then we've got more than two elements it should be okay why am i returning the wrong thing maybe i have some signs wrong negative one negative two that's weird uh so we want a max heap right oh no sorry i said that we want a maxi we actually want i don't know what i said i think i got i confused myself we want a min heap but then i think as a result of order talking up about um push and pop i think i confused myself with getting the max and the min um this is way too quick it's very easy to mess up but you know this is why you have good debugging tool and as you debug then you can go um wow this is kind of embarrassing because this is literally i would try to put emphasis on it and i got the wrong one um but yeah why did i think if i won the maxi okay uh i think this is a very common mistake and i guess obviously even i make it from time to time even when i need to look for it i wanted to do the max numbers inside the heap so that the number but we want it to sort by or not sort but we want the last number or the top number element to be the min element of everything in the heap so that you drew a line for it i think i don't remember but i thought i explained it correctly but then at some point i confused myself and i switched um but oh well i mean it's a easy fix and this is why you know um we do the thing yeah 813 day streak bound to make some mistakes though i feel like i've been making a lot of mistakes lately maybe i just need to take a break or something but anyway uh yeah so what is complexity right well h will have at most k elements because if it's more than k it picks and also this could be an if statement but i like writing it as while because maybe there's some cases where i muck around on the beginning and then you know um in this case doing variant after this will always be true i don't have to verify it there's a minor um cause an if statement was as a while loop but it's usually minor enough that i don't care um but yeah this is we'll always have at most k elements otherwise so it's going to have o of k space and in terms of time because each of these will have almost k elements each of these will have mo's log k and with n elements of this is going to be n log k right so yeah that's pretty much it that's all i have this is um you must know this for an interview it comes up all over the place in fact i wouldn't expect this problem in an interview because it's too easy or too basic i mean you know um if you have done it in a few times you'll see it and yeah you just have to do it um and there are problems that build off this so you really have to know it and know it well enough to solve harder problems um whether you know uh and this is universal i think not just like you know because i know that some countries have harder oas uh online assessments and stuff like this but this is just very basic so i definitely recommend um you know you're getting into it um anyway that's all i have for this one let me know what you think stay good stay healthy to get mental health i'll see you later and take care bye
|
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
|
1,021 |
remove outer most parenthesis so basically what this question asks is for example i'm skipping this these statements i'm just going to the example so we are given this set of string okay this is a string okay in which we have open brackets and closed brackets and it is asking us to remove outer most parenthesis outermost parenthesis for example in this one basically this one kept so here only basically these two are removed and in this one also or this one is kept here and these two are removed okay so basically if i explain you like this for example if there's brackets like one two three four five and something like this and then something like this so basically it is asking us to remove the outermost parenthesis so how can we know that which parent thesis would be the outermost parenthesis so what we can do is for example if this is a string okay if this is a string that me then we have to divide it in it into components which means that these brackets can be separated for example i can't separate this bracket from this bracket because it is not a different entity these three brackets are some part of some component okay or i can't remove this bracket or this bracket because of this one so again they are part of some entity so if i see a partition over here then i would see somewhere like if this is open then close so i can make a partition over here okay so this could be an segment and in this also oh that's it there can be only two segments in this and answer for this would be somewhat like or this bracket would be there i will be removing this one and this one so it would be somewhat like this one would be the move it would be somewhat like this and for this one would be the move and this one would be removed and this one should be here okay so this is the answer for this corresponding string okay but let's check this one it's oh okay i will just paste it over here okay it's small so basically if i'm i draw it again it would be open close okay so this is my string which is given in this example this is my string perfect now if i want to divide it into components just i said previously we have to divide these into components and after that we will delete the outermost brackets so we can see open close so what i see is that i can divide these brackets over here okay these two components could be there and the answer to this would be i would be deleting this component uh this entity and this entity so it would be this and these and for this i would be deleting this and this would be this so there would be three packets and let's check out if this is the solution or not yeah three brackets open close perfect so now we got the question right okay so now what do you have to do sorry for that yeah so basically now how can we do that okay guys i will tell you this best trick of solving bracket questions what do you want is you want a pointer not a pointer just a variable val a count okay and what does this special count do okay this is just a variable whenever there is an opening back bracket you increase the value of count okay and whenever there is a closing bracket you decrease the value of count and you will notice whenever the count goes zero that means that is a separate component let's check it out if it's working or not this logic in this one basically there's an open bracket so count would be plus one then again an open bracket count would be plus two it is increasing by 1 then again open bracket plus 3 then a closing bracket or it become plus 2 then a closing bracket it becomes plus 1 then again a closing bracket it becomes 0 and here i can see the separating line okay i said whenever we see a zero we can separate it and again use you see an open bracket then plus one again open plus two now closing bracket so plus 1 decreased by 1 and again closing bracket decreased by 1 it becomes 0 so i can see that whenever it turns 0 i can separate that component of brackets okay let's check in this one also okay so first the count is plus one okay then again uh it will increase plus two then it will decrease it will become plus one then again opening bracket plus two then it will again decrease because of closing bracket plus one and it will again decrease it will become zero okay so whenever there is a zero we can see there is a separating line so now you got the logic basically what is happening in this uh concept is that we have taken a count variable and whenever we have brackets work in pair there's an open bracket there's a closing bracket so if we add a plus one for opening bracket when we will uh decrease the value for the closing bracket it will becomes uh zero at some point of time so that is the logic behind this key why we are getting the separate uh component from these okay so basically now we understand understood that basically we just have to use a for loop we will go through the entire string and whenever it is turning zero we will remove that bracket and also at this point if it was one uh the point at which it was one we will again remove it okay or that bracket okay if i will show you again using this example okay there's a bracket open close okay so now i'm seeing that we are using a for loop okay right now my count is zero okay my count is zero initially okay i will write it in a better way count equals to zero okay count is zero now what i want my count will keep on increasing when there is a opening bracket and it will keep on decreasing when there is a closing docket okay and basically at this point this was plus one okay count becomes plus one when there's an opening bracket and uh using the previous example we saw we have to delete this bracket we have to remove this component okay so at plus one we are deleting it okay then basically what do we have to do is it will a grain increase plus two again increase plus three then my uh then it will become plus two because it is decreasing it will become plus 1 and here it becomes 0 so when it becomes 0 then i have to remove this bracket also ok now again it becomes plus 1 so again i have to delete this and then it will become 2 then 1 and again 0 we have to delete this so we saw whenever it becomes 1 we have to delete it and whenever it becomes zero we have to delete it okay but at the same time we have to keep in mind that at this point it doesn't deletes so for that what can i do um what condition should i put on my count so that it gives me a difference between this plus one and this one so um let's see let's try to code and let's see what happens okay so basically now jumping to the code i told you we have to keep a count variable count zero now we have to use a for loop and i equals to zero i should be less than s dot size i plus and then basically what do we have to do is we are iterating through it and one more thing i am doing is string answer equals to i'm making a string variable because in last we have to return the string return answer okay now i will be filling this answer okay so basically what i'm gonna do is for all these elements i'm gonna fill them in the answer and i won't be filling these brackets in the answer so in short rather than deleting from a string i'm not i'm making another string and i'm not putting these brackets over there so that gives same as deleting that these two these entities from that string so what i can do now is i will travel so i said if count equals to oh okay if s of i is equal to an opening bracket and opening it is equal to an opening bracket then i will say count plus if it's a opening bracket then i said count should increase okay count should increase and if it's a closing bracket then it should decrease oh okay else if s of i is equal to closing bracket count should decrease okay count will decrease and then there were two more conditions key if it is or if count is greater than one then answer dot push answer equals to answer plus s of i if it's not equal to okay if it's not equal to and if count is equal to for count equals to equal to zero time hundred percent sure that i don't want to put that okay answer equals to answer plus um if it is not equal to zero if it is equal to zero then i will see i can just say continue over here okay i'm not putting oh anything okay this is done now only one condition is missing so what can i do for that again let's go to our whiteboard hmm so plus 1 plus 2 plus 3 then plus 2 plus 1 basically what i want is like first i have to check for plus one then i have to check for zero and again i have to check for plus one then i have to check for zero this is my thing okay so i need to switch it between two values okay so i would say something like um so you guys you're getting now what's the problem we are facing basically we have to differentiate between this plus one and this plus one so for that what we have we can do oh count plus okay count minus okay this till this much is oh it's okay um how can i delete that segment i want to delete this plus one so for that plus one plus two plus three okay so if i drive on it will delete this i'm going through this it will delete this it will not put it over there then plus two then plus three and this then again it's plus one guys got it basically it should just be greater than one then only we are putting that now for example we are not putting one and we are not putting zero but we are putting this one now we are putting this one so basically if after closing it becomes zero then we have to delete it um so what can i do over here okay and let me check about it and count this super double equal to zero just a second opening closing so first let's basically have to check for plus one then zero then plus one for zero okay so i have to check um if i end flag equals to i will put it pool flag equals to true so first i have to check for true then i have to check for false then i have to check for true then i have to check for false oh so if count is equal to one and then flag equals to true then i will say flag equals to false and continue and similarly if count equals to equal to zero flag equals to false flag equals to true and continue so basically what happened is like for true we can say we are checking for one and false we can say we are checking for zero so i'm saying key if it is true and the count is one okay the count is one it is over here then we have to delete it so i'm saying continue okay and if it is and i'm making it false because now we have to check for zero perfect got it nice and if count is equal to zero and then flag equals to false basically now what we are saying that we have to uh check for zero here this zero okay so if it's count is zero and flag equals to equal to false perfect which it should be flag equals to true and continue and otherwise what we will do is answer plus equals to s of i okay let's check if it gives the right answer or not so basically this was the toggle situation who guys accept it perfect so basically this was the thing that made this question a little bit tricky your the that concept of count was simple and it is very really common in all the parenthesis questions that opening bracket and closing bracket and we take a variable temp for that and we keep increasing and decreasing and that would give us another component of that was just one concept and second concept was like you have to check like first we have to first like we are traversing in the area so for the component we will have a opening bracket and the closing bracket okay so we have to check that when we are reaching this opening bracket after that we have to check only for the closing target okay so for that we were using the that toggle situation and that toggle i did through this flag perfect let's try to submit it faster than 75.74 percent perfect guys faster than 75.74 percent perfect guys faster than 75.74 percent perfect guys so this was our solution to remove outermost parentheses perfect
|
Remove Outermost Parentheses
|
distribute-coins-in-binary-tree
|
A valid parentheses string is either empty `" "`, `"( " + A + ") "`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation.
* For example, `" "`, `"() "`, `"(())() "`, and `"(()(())) "` are all valid parentheses strings.
A valid parentheses string `s` is primitive if it is nonempty, and there does not exist a way to split it into `s = A + B`, with `A` and `B` nonempty valid parentheses strings.
Given a valid parentheses string `s`, consider its primitive decomposition: `s = P1 + P2 + ... + Pk`, where `Pi` are primitive valid parentheses strings.
Return `s` _after removing the outermost parentheses of every primitive string in the primitive decomposition of_ `s`.
**Example 1:**
**Input:** s = "(()())(()) "
**Output:** "()()() "
**Explanation:**
The input string is "(()())(()) ", with primitive decomposition "(()()) " + "(()) ".
After removing outer parentheses of each part, this is "()() " + "() " = "()()() ".
**Example 2:**
**Input:** s = "(()())(())(()(())) "
**Output:** "()()()()(()) "
**Explanation:**
The input string is "(()())(())(()(())) ", with primitive decomposition "(()()) " + "(()) " + "(()(())) ".
After removing outer parentheses of each part, this is "()() " + "() " + "()(()) " = "()()()()(()) ".
**Example 3:**
**Input:** s = "()() "
**Output:** " "
**Explanation:**
The input string is "()() ", with primitive decomposition "() " + "() ".
After removing outer parentheses of each part, this is " " + " " = " ".
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'('` or `')'`.
* `s` is a valid parentheses string.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
863,1008
|
1,235 |
Loot Hello Welcome 28th August Liquid Challenge And This Question Has Maximum Profit In Jobs Scheduling In This Question In The Earth Give Energy Of Job Skin Profit Acid The Video then subscribe to the Page if you liked The Video then subscribe to the Page Maximum Profit in Job During List Code 12358 Problem Exists Don't Feel It's Hard to Believe That Somewhere in Between Two Medium and White Widow A Slack Trend Question Say Swirl Give Multiple Test for Example President Asif Tube Scan subscribe to subscribe And subscribe The Amazing Is A Room In That You Want To Select Talk Page Subscribe if you liked The Video then subscribe to the Page I Want Just One Click Away From This Equation Of Evil Maintain Information Subscribe Time With Him To Return Adhed Ko Subscribe Now To Receive [ Sangeet] I Example Notification Hair is slightly different types of but good holder the concept Vansh through this example A bird request you rise to good night riders team Gautam Andar example set by spider-man Question It will help you to spider-man Question It will help you to spider-man Question It will help you to consolidate the logic Subscribe Three Live Video Profit Job Skin Last Updated On Ek Hafta Lotan Old Age Ko 200 Gram Fennel This At One Schezwan 672 And Half Inch Subscribe Now To The Mission Subscribe To And Sundar Post Entry In The Jobs Are This One Which Starts At One Schezwan Sauce What is the Time of Subscribe and Want to Celebs Ka Time Volume Maximum Profit Tarf Subscribe 100 e Want What We Do You Will Put This Information in Dream of It's Against Time 300 Against Time Free Lilliput Disinformation Notice We Celebs Ka Profit Kar Do Next entry he is this tits set2 justice and profit associated with this 500 f12 select this study what will oo will check how much profit can we make up till the time period you to what is the value of the volume to the time 2012 Subscribe Entry Into A That Ajit This Job Soye Isse 0.5% Maximum Profit Provided With 0.5% Maximum Profit Provided With 0.5% Maximum Profit Provided With Selected This Job Is That Let's Move Ahead Next Task Forces Act 600 What Do You Are Interested In Making Of This Task Solve Will See You Will See How Much Maximum profit in the app will speak what to-morrow I will get information from the app will speak what to-morrow I will get information from the dream of up-tet equal to how much maximum dream of up-tet equal to how much maximum dream of up-tet equal to how much maximum property will get the maximum profit but even get this channel generated on subscribe button and gives information of difficult 400 subscribe To that and what is the that second also guest subjects and six eggs maximum profit to a now electronic edition teacher only this study 634 incentive android what do you mean of the time veer 1000 cc road from and subscribe profit associated with r current job subscribe 508 to turn off birth in time limit electronic 5 the latent in ru protests next verification and prevent pickup difficult 700 subscribe much profit subscribe user information presented with 7766 android distance between to the point subscribe entry into a that chaudhary put his hand difference entry rs. 40 In Chroma 2004 Hai Na Ho What Do This Nitrate Over All Possible Uses Of The Triumph And Find Out The Maximum Viewers Profit In Description Subscribing To This Particular Task 600 11112 Not Developing And Subscribe Now To Receive New Updates Time To Do The Way To Wickets Arrangement of basis of which that time and attractive from time complexity from mode of nr2 login middle name of intense pain in which used to be only to subscribe to is not that let's look at recording section is equally interesting show tune don't ko baat Missal Pav Trackback The Video Then Let's Talk About Record Now Here The Inputs Give What Is Not In Form Of Giving The Independence Youth Incomplete Vidron In Interview For This Object Job Skin Subscribe 113 Of Birds And Laptop Jobs And Decided To Avoid And Subscribe If you have not subscribed the channel then subscribe The Channel Please subscribe And subscribe The Amazing Maximum Profit is aProfitable Time Some Other People Don't Feel Simple Sim Online Jobs Hey Let's Check the Subscribe Entry No Volume Maximum Profit Subscribe Will Create Appointed Subscribe Channel ko subscribe to the Page if you liked The Video then subscribe to the Page A Profit After But Understood That Will Put This Information Back Into The Vidron It's A Jhali Ki Akshay Dead Aaya Hu Invented Depression With Like Share And Subscribe Channel Not Subscribed Is
|
Maximum Profit in Job Scheduling
|
maximum-profit-in-job-scheduling
|
We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`.
You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
If you choose a job that ends at time `X` you will be able to start another job that starts at time `X`.
**Example 1:**
**Input:** startTime = \[1,2,3,3\], endTime = \[3,4,5,6\], profit = \[50,10,40,70\]
**Output:** 120
**Explanation:** The subset chosen is the first and fourth job.
Time range \[1-3\]+\[3-6\] , we get profit of 120 = 50 + 70.
**Example 2:**
**Input:** startTime = \[1,2,3,4,6\], endTime = \[3,5,10,6,9\], profit = \[20,20,100,70,60\]
**Output:** 150
**Explanation:** The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.
**Example 3:**
**Input:** startTime = \[1,1,1\], endTime = \[2,3,4\], profit = \[5,6,4\]
**Output:** 6
**Constraints:**
* `1 <= startTime.length == endTime.length == profit.length <= 5 * 104`
* `1 <= startTime[i] < endTime[i] <= 109`
* `1 <= profit[i] <= 104`
| null | null |
Hard
| null |
1,358 |
so hello everyone today we'll be solving this problem number of 15 containing all the three characters so in this question what is says that this is a string length is six and it has some characters like ABC ad we have to find the number of all possible substrings such that for in each substring there must be at least one of this a b or c for example this is a substring which contains at a it is a valid substring and hence we will increment or count to 1. and this is also a substring this also contains at least a b or c although it contained A and B also increment discount and give a dark count to one more this is a string it contains at least one it contains all of these three so it's also incremental 1 and that's I core and after completing this Loop when we go pick the second element this is also a valid string a valid substring because it contains P which is one of the least one of these values so that's why we have to keep incrementing our count for a valid substring found so how we will do we will build a character array of the entire of three length which will tells about the number of frequency of a b and c we will start from 0 they will increment and indoors will start from 0 and our inverter will also point to zero increment our in pointer and go to C and meanwhile we will also increment the frequency of this character a b and c if all the frequencies is one or greater than one then we will simply at the length of the holy minus the index of the end variable to our count why we are doing it because see when we have the ABC then all the string after it will be a valid substring so we will simply add the length minus index of end into our count so let's see how will we do first we have to create that frequency error so enter count is equal to three then we will initialize our Dot and in pointer and we will also this here lies out after one while ending less than 10 she will go incremental here we will first increment the character in the index to our frequency character counter yes Dot oh yeah let me call it a start otherwise it will collapse with this screen will implement it take a frequency one and we will check not only check but we will increment the count why characters and then corrupted count as first indexes zero we can also do it by two first like we will use two for Loops are hydrate all over this point all the possible summaries and check it possibility and increment account if it is a valid search but that will be your pick of any Square here it's taking only big of n in the worst case if this happens there will be increment our code we are able to n minus it so we are saying here that we are taking all the possible substring if we've got these three then our next all the characters of surface is a valid substrate so I will doing this that's why we will do in this then we have to also decrement the after doing the count we have to also increment our start fighter to here and document its frequency counter to start minus and we have to implement our start fighter to next so instead of doing it on the next slide I'll do it here so after this we have to present our end and then turn the count foreign oh has a lot of mistakes minus a normal test question letter submitted and it's got submitted it returned it was pretty 82 percent so this was this is the code thank you very much
|
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 |
168 |
That I am also one, my name is Ayush Mishra and you have to dress for urination, we are going to talk about the excel sheet column title problem itself, it is a very good problem and very easy but time does not come quickly, let's see what is the question. Tell him that the column number given to you by the teacher is that when the value is ok, what you have to do is to fold the debt of this number, whatever be the title of the column, you have to give it in modern times in the excel sheet. If the work is done in modern times then there is a particular column number. If you look above, you will see the column title written there, like suppose if we are here on the first column, ok saree sample, we will see this, then if we are on the first column, we are written there, it is also written on the second column, on the third one. It comes from 'in', it third one. It comes from 'in', it third one. It comes from 'in', it will be written in 26th, when it will be written 'but', like when will be written in 26th, when it will be written 'but', like when will be written in 26th, when it will be written 'but', like when we go to 127th in the column, then it is written there that why is it so because it can be till 2626, then it is definitely there, now the 27th is asking 27. But it does not mean just this little bit, okay, once we consider it here, this extra will come, okay, now if we say on next 28, then this will also happen, if we say on 30, then what will happen in this will remain. Now see how much is left, add 400 to the total of 264. If you want to say 26 Prashant, now it is 26, otherwise we will write this here plus 4. If you want to enter the fourth number ABCD then it will be added 3430. If you like then you If you want to give this remedy then something like this and why was it coming to me because we had said 27th will be given at this time so that from 26th and once 26th comes then you will give one this plus now this one a what to do this also one How much of a mystery has it become, so some people should think this way and the questions should be the same, if he had said call number is one then we know it will be 1234 126 but when it is a simple app it is ok, now saying phone number 28 in it means 28. 26 plus 2 will be used, AB plus one more bead, then this baby will come, my answer is ok, if I show you on the third order, here it is 701, if you run it, then ZY will come on you, ok and so on to the fourth ones. From this, how big is the value of Vada and the responding answer is coming, so now we will see by clicking on which one we should use it, like we will pick some examples from here, let's also say 28, now let's run 28 first. Look don't fly how are things going ok so first of all let me tell you one thing before writing this code I had thought that in air 28 here I am writing to you how is it that print that plus 2 something like this Things should change from my dead body, I am a basic, we were tuition taken out while he was watching, stuck in the exam, before and tell that A, you call it open here, B, you call it two, CO, Mr., I was imprisoned, B, you call it two, CO, Mr., I was imprisoned, my co-worker. Even if it is from 110, how are the photos, my co-worker. Even if it is from 110, how are the photos, my co-worker. Even if it is from 110, how are the photos, you say suite like this, you say 26, but if I take this to zero, then who is there is no harm in this, what do I do to you, no, I make a list in which this is BCD up to Z. Increase it or it will be 2626 characters, what will be its length, the list will be 26, okay, but one thing, you understand that if you are installing the thing in the hot list, then how will the indexes be, it will be an idea, it will be zero because the weight will be fine, two. Just like this, how much will the roots go, 25, this much I have understood, it is okay, we will make a list according to this index, okay, then we will invest, so how do we get started in this, zeros are started, they will end up on the child while we go, this smell Present six will do this when we are checking the index about the injection. At any time, we will subscribe it by 181. If we talk about our mind, we will do the massage. This is ours. Okay, we have reduced the value of the index by one. Right now, you will submit only on the number 50, what is happening here, that bag, you will get the code on Vijay, the column number from us is given in the input here, so this is the list that I have made below, you will not get the name of that list. What are the capitals doing now in the list? Now see, what was happening was that you are limiting me in this because you, this has also happened, being the root of CO, if we had to keep 1234, then we would have studied for high range, then from one to one. Bareilly up to 100 elements are filled and eaten inside. There is a button as you cannot do that because what do we have to keep ABCD and to keep ABCD, we do n't think that we have to use a little brain here. Brother, our brain has to think that ABCD is 2 3 4, otherwise ABCD is not in the list, how to keep it, you can't write this little bit, you are there for IAS in this range, it is written spread from A to Z that your heart. Either you will have to think something else, see what you think, we know that we are fighters, there is a function called CHR and in the rest of the cases, whatever happens, the festival function, switches function takes input from you and it corresponds with whatever character. What happens is that he tweets, well, if there is a character like it is, then there is a function to get its value back, like in the case there is some character in capital and know what is its value by taking capital, it is sixty five, okay. So let's do this, it's from sixty-five to do this, it's from sixty-five to do this, it's from sixty-five to 26, how much fun will it be if it becomes 26, today the oath is 1628, 1898, we give jobs from 65 to 91, now we know for sure that we are running its value on that, coin range is set. It's okay to take it, okay again we will take it till 9 and now what will we do each person era C omega 6 1 6 7 whatever value we get we send it in this jar then what will four do then sixty five will take input from and mutual idea What does it do to consume it and mix it and give its character? So one is Sky Valley 65. Okay, so if we pass this, then this Chanakya will give this, so we have made a list by using CHR and body and our The complete list was prepared, now how to prepare the school, it can be seen in the report. I said, take out the body of one, you will get electricity from here for 65, take out the body of one set, you will get the value from here, get 26 sets, how many did you get in 19th. What will be done is that we will run a loop in this range from 65 to 92, I have to mint ₹ 90. Okay, to 92, I have to mint ₹ 90. Okay, to 92, I have to mint ₹ 90. Okay, one person will run on this. Now whatever values I get, I will convert them into whatever character they want after the C chart function. And whatever list will be made, we will introduce the name of the actress, then the makers will solve the problem of waves, they can also make it into different lines, because I thought of doing lines, so I made it like this, okay now. We start with you, we have got a career ready, now what do we have to do because it is our answer, we will keep the result, we made idli in difficult times, good man, we got 128 inputs, so what is our first task, yes brother, we got the throat. What it means is that we have to answer this and then the middle because 2019 comes at number 26,000. because 2019 comes at number 26,000. because 2019 comes at number 26,000. Okay, if we talk about our Hey, then this is what it is and if I ignore, then it comes at number two, is it so? So no where does it come, it also comes on the first index and this one which will be on 26 points comes on zero next so if we have to make A from 26 to zero and B has to be made one from our side then I Intact will have to be reduced by one and look at this from above, when it becomes 26 then we will have to divide it by 26. If you understand, then we run it on a register here and understand, so if our in food has come to 28. Sitting so it will take time to keep running in the situation so we will check the camera 28 big zero sub and so we do such an interesting Navgraha minute if zero is given then there is nothing like a hero so we will check it till My column number is from zero, I have to do some work. Now what we will do is we say remove the same column number macrame one because we have done your injection also in the same way that I want to spend some character here after that particular number so I have 28, I have reduced it to 28, how much has it become, it has become 27, okay, now if I divide 27 by 26, I know this, then there are 26 characters, 226 006 My reminder, how much will come, one will come, okay if it remains mental. It is Dubai, it means which character will I choose, what is written in my list of capital names, West Tax, then you see, it has to be taken from zero downwards, it was also mentioned on patients, so we will enter blue and Just pick it up and put it directly in the result. You will write in my result and mine has also come in the last. Okay, what will you do? Now see, mine has also come. What I had written in 28 is 26 plus 2. There is a shop right now. If I have to divide it, then I say that column number - one means 227, if I that column number - one means 227, if I that column number - one means 227, if I divide it by my 26, then it will be correct. You tell it is interior division, then this question comes, I am having tears in the question tower. So it was created and you know how much has passed since my alarm number 28 I have only the first stop I must have fully understood Okay now I would have done this here I would have done this then what is my number 28 Only then how much has passed That is already done, so now we will check whether my big is exactly bigger than zero, then what will we do, one minus one by, tell us AB, please answer, why come, you have become unemployed, now we want this, so one will come that brother, our number will be there. If you reduce then one manager means 040 will be the answer mode, with 26 then Shyamendra will be made zero. Now the zero reminder had come, we have given it as Zakas element, it is lying in our list, you are in capitals, what is lying at zero, it is lying then. If you play one and keep it in East then it will come to Vidarbha in Agra character. Okay, now what will we do, now we know, send it. Even if we want to finish in Capital village, then join the call number - 151 - 1000 and then join the call number - 151 - 1000 and then join the call number - 151 - 1000 and divide 26 from here. Will be kept, I have reached zero number, will zero stop, what number is zero, my big is the condition of zero so that the fan will come out of full sunlight, what behavior, you have understood so much work and at least what are we doing, whatever We get the call number, whatever value is corresponding to it, we reduce one in it exactly because they fill the element according to dowry induction, okay, we will find out its mode, we will find out the models, if it is 26, then whoever will take us in on that. Whatever is very good is different, we have kept it in the plate, then we will reduce that number by one and divide it by 26. Simple, okay, then every person will give the number again, it will be changed a little, it will become smaller, then I will stitch it which will run evenly. So when all the people went to their own country, there were 28 of them, this look gave their answers, gave a list of results in which and this is lying too, it is good but if we want the answers, then we reverse the list. If I have to do so, I have read the result MP list in the reverse phase, how the list was made, it will increase the day also, you must have understood this much, 1 minute, I made a mistake, right here, this is my list, it has become something like this, what do I have to do? Join the characters in this list together, if the answer is there twice, then even if they are finished, give us your answer, then we will add the police on this. How do you know that there are all the characters, so I said, without giving any space, join the element with our list. And I will return whatever answer there is. All of you must have understood everything and now I do not think that you will have to explain to me whether you will join or not, because I have told you in total when question lady that it is very hot. It was a simple code. Here, I started making small observations about how we are going to relate the numbers to each other. Okay, even those from America must have understood that it has a quick effect. How do we preserve it? That after eating, we have made a list here, it is a simple question, B is standing with a profession, I restore the answer in the resort, as long as the number is there is zero in it, I will find out its models in one company, because there are 26 characters, there is one in the middle. That's why I reduce it because hey, do the medium in this way, first pick it up from the pipeline, I will keep it aside, then I will reduce the number, one day we will have a proper list named Beward, I will make it my voice, this part will be added to the office plus team Anna. Okay now Himanshu, if my input comes to 26, then 26 comes, then what will 26 do now, I have just given 25 mode, if you do 26, then there will always be want of capitals and the body will do 25 and 26, the answer is 25, okay. Ok People's 25 minutes to read what is connected, for this we have Hansraj, you must be understanding the account of the customer, how is our loop, go away, there was no one at home, but if you spend some time, you will understand better. I will come ok Jhal
|
Excel Sheet Column Title
|
excel-sheet-column-title
|
Given an integer `columnNumber`, return _its corresponding column title as it appears in an Excel sheet_.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
**Example 1:**
**Input:** columnNumber = 1
**Output:** "A "
**Example 2:**
**Input:** columnNumber = 28
**Output:** "AB "
**Example 3:**
**Input:** columnNumber = 701
**Output:** "ZY "
**Constraints:**
* `1 <= columnNumber <= 231 - 1`
| null |
Math,String
|
Easy
|
171,2304
|
3 |
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 longest substring without repeating characters so it's a very easy problem given a string s find the length of the longest substring with without repeating characters for example let's see this test case see this string is given to us and we need to find out the longest substring we all know right what is substring a contiguous string right so this abc is a substring this a b c b is a substring right this hole is a substring so we need to find the substring and that to the longest without repeating characters for example i cannot take this substring why i cannot take this because a is repeating a is coming two times we cannot have repeating characters okay so i can take abc i can take it has no repeating characters so this is one of the substring without repeating characters and it has length three that three characters i can take this abc also but can i take this no i cannot take this because b is repeating three times all right i cannot take this substring sorry i can take this one because it's cab each character is occurring one time but i cannot take this because c is repeating so the maximum sub uh longest substring right in this case which has no repeating characters is abc this abc or you can take this abc or cab all right so the maximum length the length is 3 abc okay so i hope you understood this problem now let's see how we can approach it see guys whenever we have to uh whenever see in the question only you will get hints what you can do i'll give you some hints try to approach the problem see first of all we need to find out substring so we need to find out sub string so whenever substring is given right you can think of few approaches like you can think of two pointer right you can think of using sliding window right and yeah you can think of using a hash map right so some see these are some cases you can think in your mind right also then what you need to do you need to find the longest so second point is longest means that you need to find out the maximum length right maximum length so here you need to find out maximum length substring and also without repeating characters so the string should be not having any repeating characters without repeating characters so see guys first of all in this problem can we have a benefit of doing sorting because see two pointer is mostly used when we can do sorting over here there will be no benefit of doing sorting because position of these characters will change if we do sorting okay so if we do sorting position will change and we need to find substring right so we cannot change the position of characters all right so spotting here has no benefit so two pointer is we cannot think of using two pointer here will it will be no uh benefit to us second what we can think of is using a sliding window so see let's see if this problem falls into sliding window category or not so see what we need to do in this problem we need to find out the max length that is the max length or what you can say max window so what is a window is what window is a substring only right if you think it window means what a substring or right substring so here we need to find out the substring and that too of maximum length and there is a condition so every time we have a condition so here condition is that it should not have repeating characters so all of these three conditions are pointing to the sliding window approach so here we will use sliding window we have to find a window that window should be of maximum length and it should not have any repeating characters all right so i hope you understood how to identify what we can think of using in a problem now let's see how we can approach it how we can think of the approach so see here what i'm doing is i know that okay i'll be using sliding window i'll be using now in sliding window we have a window right we have a window so for specifying the window or for representing the window maintaining the window you can say for maintaining the window we take two variables i variable and j variable i variable is the start of the window and j variable is the end of the window so basically i is the index starting index j is the ending index of the window so initially i will take both my starting and ending index of the window to be at the starting index so let me do indexing 0 1 2 3 4 5 6 and 7 initially both i and j will be at the starting of the uh this starting of the win uh string right at the zero index now as we all know how sliding window works right we will shift our ending index and we will maintain a window okay now here the condition is that the window has to have a condition what is the condition every time condition will be given in the problem so condition is it should not have repeating characters window and condition is no repeating characters right no repeating characters so guys now one question is we will maintain a window but how we will keep a track that it has the window has no repeating characters just think about it how you can keep a track that there is no repeating character in the window for example let me tell you let me say like this is our window right let's suppose i is here j is here so how will you check whether there is a repeating character or not like a is repeating in this window right a is coming two times how you will check so yeah i think you're correct thinking correctly either you can use a hash map to store the count of each character count you can take a hash map and you can store the count of each character otherwise what you can do you can take a character array character vector or character array so corrected array you will be storing the count of each character so i will be using character array here you can use a hash map also doesn't matter so what i will do right i will be taking an array so alphabets uh i will take the size of that character added to be 2256 right you can take a 26 or if the logic depends on you so how do you are storing want to store the count but i'll be taking an array vector or size 256. so let's say here we have this so in this string i have c only so i'll be taking every just storing the count of these only so i'll be making that much only 0 1 2 3. so something like this will be the character array here a will be stored a count here b account will be stored and here count will be stored basically we'll be storing a minus the sky value of that so if it's let's say it's sky value is 97 so we will be subtracting 97 and it will come at zero index so here is count will be stored okay so see guys now what we will do we will see okay first step is whenever we will have we'll go to each character right we'll go to each uh character in our string first step will be whatever is at j index right end index we will increment its count because we are taking that in our window right so i'll be taking this in my window so let's say this is uh let me name this as count array so first step i'll do is count of this character right this character so let me take the string as s so s of j right whatever is present on s of j a is present so i will increase its count by one because it has occurred once in our window so here one will come this is the count of this a character in the window so window is currently this much okay then what i will do i will check whether this count has become greater than one because in our window correct a specific character can come only once right so i will check here i will check so i'm writing here i will check whether s of j uh whether count of s of j count of x of j is greater than one if it is greater than one i will remove that character right because we cannot have duplicate characters right so i will check and then i will remove so we will see how we can do that but like for now i'm just writing check if it is greater than one so here one it's not greater than one right it's one only so it's fine and if it is greater than one then we will check and remove that character remove character okay after that so i will have an answer variable in which i will be storing the maximum length of the sub uh this substring right so right now answer will be 0 and every time we will be updating our answer like updating our uh length of the substring so answer will be equal to max of answer and j minus i plus 1 why j minus i because we need to find the length right window if this is the end index of the window and this is the starting index what will be the length j minus why we are doing plus one because these are indexes right these are indexes so plus one to getting the length for getting the length so here answer will become what j minus i plus 1 what is j 0 what is i is also 0 plus 1 so length of the window right now is 1 so i will increment answer to one okay now let's proceed further after this we will increment j so j will come to now j will come to one index so first step is what count of j character increment so b's count will increment right now all are 0 so i will increment b's count and will make it one that is b has occurred one time after that i will check whether count of b is greater than one no it's one only so nothing need to return and i and then we'll be calculating our answer so answer will be j is 1 minus i plus 1 so this will become 2 so we will increment it to 2 okay so now let's move forward now what we will do j will again increment so j a plus j will now come to two index here okay so now let me remove this so now let's calculate the count of j character we will increment so j is 6 c is 2 so we will increment uh sorry c uh count we will agreement so a c count will become one okay now we will check whether that count is become greater than one no it's one only so it's fine and then we will increment our answer so answer will become what is j is at 2 index 2 minus i is at 0 index plus 1 so it will become 3 so here answer we will increment max of answer which is 2 comma 3 so max is 3 so we will increment 3 update to 3 after that now let's move forward so j will again go here now see carefully guys j is here now okay so whatever is at j we will increment its count so ace count will become plus so 1 plus 1 it will become 2 so here 2 will come now s of j is what a is count is become greater than one so his count is two and it's greater than one meaning this is our window right starting index is i and ending index is j so in this window this a is occurring more than once right that's why it's count is greater than one so it's coming it's occurring greater than uh one right so how we will remove it now see we have to remove this a because this is occurring two times right we have to make it one time only this a can only occur one time in a window one time in window so how we will do it we will have a while loop we will continue removing the character until this count of s of j is again until it's greater than one right until it's greater than one we will shorten our window right we will shorten our window so see how we'll do it we will see if like until this uh count of a is greater than one we will keep on shifting our window right we will keep on shortening our window because we don't want this a to be occurring two times in the window so what i will do i will check uh what i will do i will just remove whatever is in this s of i so s uh what we will do we will write count of s of i whatever is that i just decrement its count because we will remove it out from uh from our window right and then move i plus just remove move i so at i what is present a we will remove from our window so that's why we are decreasing its count by one so count a of count will become one and then we will shift our i so we are shortening our window so our window will now be till here now see guys again we will go in the while loop we will check the condition s of j is count is greater than one no now a discount is one only so this is fine this window is fine so now we will calculate answer again this is how we are checking and removing the character and we are only keeping that character one time then answer will become max answer uh and we will find out the answer so answer will again come out to be 3 because length is 3 right so similarly guys you can complete the dryer and write now again j will increment so j will come here again we will increment b's count it will become 1 plus 1 2 now again 2 is a 2 so b is occurring in this window c in this window b is occurring two times so we will remove b will shift i and we will decrement the count of b so b will now become one again so our window is now from this i this c to this b so this is of length three so answer will update will not update because it's already three similarly you can again you will increment j so c will now become c's count will now become two c is occurring two times again you will shift this i and i will come here and re c will be the c count will become one so it's fine now okay and this is our window abc so it's length is again three so you can there is three similarly you can complete this j will come till here and you will get the answer value to be maximum three so this will be your output that is the maximum the longest substring which has no repeating character is of length three so i hope you understood this approach and the dryer now let's see the code once try to write code by yourself using uh by uh looking on these steps to see after uh after understanding code right i will highly recommend dryron once so this is the count array i have taken initially all the values will be 0 l is so here i've taken l and r l is your i that is starting index this is starting index of window and r is your j that is ending index of window then answer will store the length of longest substring no repeating correct having no repeating character okay so until r is less than s launch so we will continue our loop until j reaches at the last index first of all we will increment whatever is at j its count will increment then we will check if it's been greater than one so basically we are doing these steps this while loop here up that will calculate answer and we will increment our value okay and at last will return answer so i hope you understood the problem and the approach uh time complexity for this is of n because we are traversing this string once right and space is constant only because we have taken this constant array so you can take it as constant or you can say it's 256 or something so basically it's constant only so i hope you found the video helpful if you found the video helpful please like it subscribe to my channel and i'll see in the next video thank you
|
Longest Substring Without Repeating Characters
|
longest-substring-without-repeating-characters
|
Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with the length of 1.
**Example 3:**
**Input:** s = "pwwkew "
**Output:** 3
**Explanation:** The answer is "wke ", with the length of 3.
Notice that the answer must be a substring, "pwke " is a subsequence and not a substring.
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of English letters, digits, symbols and spaces.
| null |
Hash Table,String,Sliding Window
|
Medium
|
159,340,1034,1813,2209
|
976 |
hey everybody this is Larry I hit the like button hit the subscribe button let me know how you're doing this farm I'm gonna stop alive right about now 976 largest parameter triangle given an array a of positive lengths we turned the largest parameter of a triangle of nonzero area from three of these lengths it was impossible from any triangle of nonzero area return zero okay how many numbers are there so the length is 10,000 so you cannot do any length is 10,000 so you cannot do any length is 10,000 so you cannot do any naive and cube algorithm but that's interesting though hmm this is a easy okay but I think hmm question is then can I do anything greedy with the problem all we have to do is have none so area so it doesn't have to be damn much bigger than zero so if we just take the biggest three numbers can we figure it out or - hmm but basically if you're given a list that you saw it so we sort first by the largest number doctor's order first then let's say in this case we have six three two well this number we just check to whether these three right and if it's true then we could already immediately return it to some of these parameter if this is not true what does that mean why well that means that six is too big so we have to get a number that's slightly smaller and because we're already looking the two largest number we just have to shift it to the one to the right so in this case now we look at the last three yeah the next three numbers I think that's worth Lee right so okay yeah okay because if you have a number that's too big then there's no other combination of numbers that you know because you sorted this already there's no other possibility that two numbers in there are greater add up to greater than seven right in this case so okay so now we can just do a ABC and a and then if B plus C is greater than a you return a plus B plus C at the very end we turned silver okay and now we have to put in order at the test cases so this is an example of a greedy algorithm with sorting so it's good practice for an easy problem because it's not a problem that you would have done before because it's so ad hoc unless you really like triangles but you know once you've done that you know it's just greedy and at least for me I always feel like greedy yeah greedy just requires more practice for me because I have to prove it correct but yeah in terms of I mean in terms of a greedy algorithm I think this is a great way to practice greedy I don't think by itself it's a problem that I would give us an interview because it requires a little bit of playing around with these numbers then maybe a normal problem though that said this farm is a little bit Elementary so maybe they'll be okay but yeah 4.2 and sorting is pretty basic but yeah 4.2 and sorting is pretty basic but yeah 4.2 and sorting is pretty basic and it gives us a structure that we allow grow allowed to allow to solve this farm and as I said the thing is out to sorting and getting the biggest number first the observation is that well if you know in a greedy kind of way you always want to take the largest three numbers but if it's not so you have to think about well that's true then you already have the largest three numbers in the set so you cannot get any bigger the number so you return it but if it's not true how did you get from this you know trying this candidate and then trying another candidate right can it did answer and I think that is an insight that you know that's within reach for most people it should be yeah okay yeah for competitive there's a lot of math leafing so I think this is good practice even if and for like someone that code for is this may be like a problem a and TIF to or something like that way and that really standard but yeah that's all I have for this
|
Largest Perimeter Triangle
|
minimum-area-rectangle
|
Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`.
**Example 1:**
**Input:** nums = \[2,1,2\]
**Output:** 5
**Explanation:** You can form a triangle with three side lengths: 1, 2, and 2.
**Example 2:**
**Input:** nums = \[1,2,1,10\]
**Output:** 0
**Explanation:**
You cannot use the side lengths 1, 1, and 2 to form a triangle.
You cannot use the side lengths 1, 1, and 10 to form a triangle.
You cannot use the side lengths 1, 2, and 10 to form a triangle.
As we cannot use any three side lengths to form a triangle of non-zero area, we return 0.
**Constraints:**
* `3 <= nums.length <= 104`
* `1 <= nums[i] <= 106`
| null |
Array,Hash Table,Math,Geometry,Sorting
|
Medium
| null |
105 |
The Heavens Welcome back to the second series, the video is coming after a long time from the Australian officers, why now what has happened, he had fallen ill for one and a half years, now he said this, he should not, but it is going very wrong for me, but still the dimensions Director, I am right, so now let's start the video. When I was sick, I got music messages from many people that brother, traditions are going very well, I am also getting a lot of confidence, I am a stranger, scrolling, I entered my playlist a little while ago, the literal meaning of the decision. The one who is tied must be watching this, after paying a lot of money to him, how does the year of trimming history ride, problems and 12 more questions will come, today's questions are important for me, soaked, this question is a very good question, Italy is a very good question, there is a lot of opinion in this, I understand it well. This question comes, you will see its answer code, it feels like oh my God, it seems quite meaningful step by step, I thought and wrote quarter, okay, that's why I like the question very much and I too go into the question very big, so this question Understand well what the question is saying by sentimentalizing it that I am telling this question, it will be understood only when you will search and iron out its code. With the help of give one example, I will tell you how to do this in step process. If yes, then let's start and watch Videocon. If this question was asked then look at Construct Binary Tree from Pre-order Endevity Reversal. Like every time, I would look at Construct Binary Tree from Pre-order Endevity Reversal. Like every time, I would look at Construct Binary Tree from Pre-order Endevity Reversal. Like every time, I would recommend you to please pause the video. For this question, I will talk for half an hour. Think. That how can you edit it, you don't write the code but you will understand the procedure, just a little hit, people will do a little fax that how can I make this free mode on Observatory, that would be very beneficial for you and Uddhav said, you will not disbelieve him and Even if one is about to shift, there will be no dream defect. End question. What is the question of understanding? It is quite simple. Now we have quarter given that and an inverter given warrant but this you should know what is N alarm upper meaning first all that is needed okay. The playlist has been told that people who will be making notes also do portrait devices. Beneficial inverter for them means that the note will be in the middle in between these means that we have to put our mind that we people will be able to prepare from these two things which we -Quarter and inverter have been given, we have to which we -Quarter and inverter have been given, we have to which we -Quarter and inverter have been given, we have to make a tree from it, right, it is quite simple, then you will see that it is simple to do, we have one lamp, that node, one and a laptop till the right, now let us tell you that this Priya and always among the inverters, if we Let us tell you what will be the note. We are starting to make the tree but what will be the first note, before that we will put no Vikas or No Doubt. According to the free mode, the note that was wanted first goes, so I have made it here, now on the right side. Now what do we do in these hotels when we search, we found here, now if we search in this, then my department is that in K, this note of Laxman which will go on the left side, that these three of this note we found no. In D, in the body, where is the key three, in the way, whatever the number of elements are on this side, let's side, whatever the number of elements is, what we did is put it 946 whatever number of elements there is, we put it Fashion 2017 A Great Now we will come to the left of it, okay In scalp, we have only one line left in the name of inverter, now we will move ahead on this, so now whatever is there after three, what will be the next note, no, where will it be made here, okay, so what have we done, I have not done it, one take, then our If there is a right on all the rights then 307 is the next cancer and we will have a note, if that is created then one right, then what do we do, address and here, then one is created, now what do we do and search twenty in the inverter. Where is the tweet here, now which element is to the left of it, then there is 5 and which element is next to it, one, so now what we will do is subscribe it, then we will press the village element again, then what we will do is so we If you check then what we are here is free, we are making hand free mode of fashion, what does it mean that Priya and Ko are looking at it, we will remain there, ultimately, every single thing was like a note, we are withdrawing cash. That this is a note and he is finding this note here and he is taking out his left toe right side, taking off and going into his life and seeing that this note is in the next sequence in the pre quarter, then he is getting guava. He is making it and then with the help of a motor which is turning it from left to right side, we are continuing this process while the ribbon is going forward. Now the youth will see its code. Atif Aslam as a Ghaghare. I am understanding the code. First understand one thing before that. Here what is the process but if I write it step by step then what is the first step that create a root node take is making a note from where to make the free mode of address is the free order one is making this precious second one What are the items? We are finding the notes in these Honda inverters. Then we are creating the left and right districts. We are using the left part on the track and for the lesson with right to recall and right left. Again record this step, we keep doing all this, you will be less able to understand what is going on, but again it is very simple, where are we making the note for free and according to that note. What we do is find where that note is in the inverter, then fold it in Hunterganj, there must be some element on the left side of Indore, we consider the left element and know the value of the root. If this note is root then it is left of the root. And then decorate this one and this one, how will we start the procedure again, you will understand how I did the union, what did I do, a free mode of a gross. IS and I am what is it like index of any inverter I start not trust and why are using inverter ink tank Pithora and you first get it from us then we will return you after that you will get a pin code here in two parts Divide and this two that track what are its sanam doing creating a route creating a new route and pre-order print mexico and pre-order print mexico and pre-order print mexico friends we have declared global variable 11 dead zero printers we have what we have when what we spent free Turned on the mode and Trump is making a trick in the reporter's session. We are making every pre-order We are making every pre-order We are making every pre-order limit private, making a note in it and folding that note. What have we done first of all in these hotels? Freedom is three agri. Now what did I say that I have printers, I have zero printer, so the first limit is we made a route named free here, we made a road named Pathri, there is no problem, we increased the prince, so friends, today we have one. Now what we have done is that this one's root gets lost for free, its intake, its water intake, we find out where the president is, then we put a simple loop on it, equal to s.i. Equal is an put a simple loop on it, equal to s.i. Equal is an put a simple loop on it, equal to s.i. Equal is an equal, we have a whole field to search, ray can be anywhere and i plus i n order carrier got the value of the route of i and express, the route we created here on that rally three. That value is a hat-trick, if we three. That value is a hat-trick, if we three. That value is a hat-trick, if we get it here, now what will we do, we will put its integer in this induction, then what is the index, the technique made here, we want that it is the first element of the first zone of one, put it in the root collect and after one After taking the root to the right, what did I do here, called the left of the fruit, C, tricky recursive function, prayer, dedicated inverter, edit, this is a difficult, I started, and in the intake, what will happen in the root right at this time, free water in Udan. From these index plus one battle simple block, what we did was that we partitioned the inverter that on the left side of this route, just cancel this element and in this route, on the left right side, just keep this much and set it and it will go to the left of the route, get up right. It goes in I decided in the last and returned in the last and social nothing complex simple steps first attempt is what we did we created the root then we found the inverter and made its left partition and selected part of the root is the right root of the root On the left, its light point, cut the route, so simple, if I talk about its implementation here, then it is so simple, first of all 20 to 4000 1234, then first BJP, who is getting tension, who would be getting this because of ISI, it is okay if IS does not come. If it is done then we will return the run. First of all, it is printed, why is it global, why is it made because call is being made from all the records, otherwise we still need that we access the printers on the sequence, on the net, we created Prince Guru and in these intakes. It is temporary, isn't it brother because we need to fold the element in the range, Detroit C in the first case, the root is rapid growth and development, Abe Prints is zero, what is zero element, 38, so friends, this is Neuropathy, and friends, if we have added plus, then now the printers are fine. Now I am accepting this cord, now in these intakes in my mind, 1 came, then on the left side of the route, we called inverter 0202, only one more mix, here came 1, so one of us came from the back and one from the front to call the inverter. Now we will start these and 01 Now this function again called Sidhi How did she call c2c tree Half is that what is the order of these What is the content of what is done and what is not done Now create a new one and what is this and where is this from Printers So this time a new knob has been skinned so now here what we did that but from where that in between the hatred and outside of so we called from this then got in touch with this minus one then this Ultimately tap and now here nurses do 10 - at - and now here nurses do 10 - at - and now here nurses do 10 - at - time so this thing will not subscribe and its 10 so here and here this soon like this here this time so here 2015 If you start then copy this code, whatever it is, then something will happen to make you happy by thinking that you are going to subscribe to this channel and do inverters and the left side part is sitting on 103 thing complex and we got this thing crossed premiere. In water and then assigned to it and then returned to it and just come on you must have understood this I will code it and show it to you then you understood that this thing was required then do one thing that one It's wrong in different phones, okay, before the help worker, Prince creates an interview, which printers creates a global variable for us and a separate function I need this, what is the intent and print I write that now this function call Let's do the work that tender's answer and it makes print rear is relative function and passed inside it what is pre-order is inverter and what is it means that starting in 1004 scan tax what will be of these Odisha size vans Size will be in order dot size - We will return the check passing the osm index. size - We will return the check passing the osm index. Now let's complete this paste. Simple life. If you subscribe to this channel, subscribing to the channel will make it a new trend equal to the road. Free water will be given inside it. Afton takes A's rate and then tells friends that we have made an index, what did we do, made a root, now we will find the root, where is it in the inverter, then int in intex, research torch light of inverter, let us fit it, point 5105 Syed Hasnain came equal. And i plus if we just get the aa value of the root in these order if in these order, okay so now what we will do is we will start it in these index where it is found in the index and then one Now we will do this button, we have found out the index in the inverter where that route is being found, now on the left side of the simple route, we will sign this will tree hotel function, a tree is harder, inverter but these hotels are going to this. Bar from where to go come from index - on - on - on cooked and the right of the route is going from where to where is going to return one A plus one to I think last now 9th root som simple let's run it and see if You understood that to subscribe this channel you need not subscribed yet subscribe please share if you like my channel in this video Shri Radhe [ Shri Radhe [ Shri Radhe and listen Shri Radhe
|
Construct Binary Tree from Preorder and Inorder Traversal
|
construct-binary-tree-from-preorder-and-inorder-traversal
|
Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_.
**Example 1:**
**Input:** preorder = \[3,9,20,15,7\], inorder = \[9,3,15,20,7\]
**Output:** \[3,9,20,null,null,15,7\]
**Example 2:**
**Input:** preorder = \[-1\], inorder = \[-1\]
**Output:** \[-1\]
**Constraints:**
* `1 <= preorder.length <= 3000`
* `inorder.length == preorder.length`
* `-3000 <= preorder[i], inorder[i] <= 3000`
* `preorder` and `inorder` consist of **unique** values.
* Each value of `inorder` also appears in `preorder`.
* `preorder` is **guaranteed** to be the preorder traversal of the tree.
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
| null |
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
|
Medium
|
106
|
73 |
hello friends welcome to joy of life so today we are going to look at another medium level problem from lead code it's been a while i have done any problems from lead code so the problem number is 73 it's a set matrix zeros so given an m into n integer matrix if an element is zero set the entire row and column to zero the problem seems to be pretty simple in nature as you can see over here so basically you're given with a matrix and the matrix has some values and wherever you get a zero like you get a zero over here right so you set the entire row to zero and entire column to zero so it will transform it into a matrix like this the one over here right similarly for this case if you see we have a zero over here so this entire row and column becomes zero and we have a zero over here as well right so this entire row and column becomes 0 as well so it will transform into something like this so this part is completely filled with 0 right so this is the problem all about so we are going to discuss the solution and understand it in a lot more details but as i always do recommend that uh do give it a try yourself to try to solve it just like a puzzle and then you can check out my solution so let's move over to the board and try to solve the problem and let's try and understand why this problem is um tricky right so what happens over here let me create a matrix at first so let's say this is the array that we have got the two-dimensional array so have got the two-dimensional array so have got the two-dimensional array so what we'll basically do over here so if you think that what we'll do is we'll start traversing the array and once we get a zero we have to set the rows and columns to zero so what will eventually happen is we will set these guys to zero so let me put it with a different color so it will look like this started with i equals to zero and j equals to zero and now as i increment j becomes one now previously we are here now we came over here so now the problem is we don't know that it was initially 0 or it has been set 0 due to a row and column operation or not right this was initially not 0 right it was having a different value just because this guy was 0 that's why we made this to 0 right so that is a problem all about like we have to keep a track there are various ways to solve this one so we'll pick up a very simple approach so what we'll do basically is we'll uh we will scan through all the elements of this matrix without changing them so let me restore it back to its original values so this was the original value right and we know these are the places where we have a zero so let me underline them so these are the places we have the zeros so we are going to pick up this i and j the pair the index pair right and we are going to store this pair in some data structure let's say it's a list right and this list is going to hold appear and this pair is having two values i and j and we are going to store like 0 as my first pair so let's say this is my object so let me denote it with this the second element would be 1 2 and again the third element would be 2 0 and the fourth element would be 3 what is it one two three now since we have taken this value so what we'll do is we'll iterate the list this list that we have created and we will change the row and order to zero right so this could be one approach there could be several other approach what else you can do is you can keep a track is the row zero or is it a column 0 and you can solve it that way also you can set a flag kind of true and false and you can solve it based on that i will leave that up to you i have solved it in both the way so what we'll do is quickly we will go with this approach wherein we'll store all this indexes wherein we have a zero and we are going to leverage on that so that will make the problem pretty simple so what we'll do is in the first scan we will iterate over the entire array which will give me a order of mn right and next time we are going to get the values from the list in the worst case everything could be zero we can have a array something like this as well in that case what will happen is uh that iteration over the list will also cost me order of mn sorter of mn plus order of mn so it's going to be order of mn only and we need some extra storage over here so the storage would be again we have to we might end up storing everything in our list so it will be order of mn but if you go with this approach over here what will happen is your storage will uh be at order of one but your runtime will still remain at order of mn because anyways you need to scan the entire array right so if i touch all the elements that will cost me order of mn we cannot reduce on that so let's head over to the lead code and try to solve this problem okay so we are here in the lead code and let me adjust it for you guys so that you can have a clear view okay so what we are going to do is pretty simple so we are going to create a class we talked about appear right so we will create a simple class not nothing much over here just we have the i and j so that we can track it right and now what we are going to do is we need a list up here the class that we have created so let's call it pairs and let it be a arraylist right and then we have the simple loop we are going to scan through all the elements so it's pretty much the simple loop that you guys use for iterating a matrix right or a two-dimensional array so i'm using or a two-dimensional array so i'm using or a two-dimensional array so i'm using the same thing over here and whenever i see that if my matrix ij is a 0 then we are going to put that index with us so we are going to add it to the sorry rotate as paris it spears it will be pairs start and we are going to add this new pair so i have created a constructor also that's for the simplicity purpose only so i am going to say that i am going to create a new pair of inj that's it so we have got everything now what we are going to do is we have picked up all the elements now what we will do is we will go through this pair what's wrong why i'm writing paris can't even go there now right okay so what i'm doing over here is i'm going to get the pairs out from this and what i'm going to do is i'm going to iterate row and column so i'll keep the row constant and i trade over the column starting from 0 to the length and then i'll keep the row constant and i draw it over the rows keeping the column constant okay so uh let's do a few thing over here for simplicity uh it will look good also in so how many rows do i have matrix dot length rows and i have n false equals to matrix zero dot length assuming that it's not going to be empty and i guess they have confirmed it over here so here are the constraints so they have clearly said that m equal to matrix length and n equals to matrix 0 dot length 1 less than equal to m and n less than equal to 200 that's the constraint we have um the values could be between minus 2 to the power of 31 minus 1 so here it says that you can do it with order of m n is probably a bad idea the one that we are doing there is improvement to order of mn and but there is a good solution which is a constant time solution so you can target for that i am not going to discuss that solution over here i have given enough of hints for you to leverage on that so if i show you from my submission part um here is one of the solution that i did which is order of one so if you see over here that we have done it in 93.29 done it in 93.29 done it in 93.29 and i have not been using any extra space over here so if you see over here i have not created anything but i will leave the solution um up to you guys i'll create a video on this later i know i have given shown you can pause and see it but i'll keep it to your honesty that you'll give it a try to solve it so let's go back to the problem that we have been solving and let's uh get it done okay so we have taken the rows and the columns and what i'll do is i'll can change this guys i don't need to use this anymore i can just say is my mouse yeah i can just say rows and columns i don't need to write all this over here also i'm going to do pretty much the same thing over here so i'll start iterating over this array so what i'll do is from i equals to 0 i will start and i will go all the lengths to the pulse and i plus okay and uh what i'm going to do now is i'm going to change the pairs so the element that we take took out in pair i'm going to keep the i constant and i am going to vary the um the sorry pair dot i is constant and let's put the name as j it will make more sense to you guys so let's put it as j and let's change it over here as well so what i'm doing is basically i'm keeping this constant and set and varying the j and setting it to zero and another okay another similar loop that we are going to do over here is um this time we are going to start from zero and go till rows this time what i'll do is i will keep the name as i and what i'll do over here is i'll do pair dot j okay so you've got the concept right so what i'm basically doing is i'm keeping the row constant and changing the columns and um i'm keeping the column constant and changing the rows so i'm setting all these values so yeah that's all that's pretty much it that's all i have to say about the solution right so what i'll do is um we'll so yeah that's pretty much the solution that we are discussing over here that's a bad solution you can see over here they have straightforward solution using of mn right but i have shown you the glimpse for the um other solution where we can do in a constant space but i'll do it later i'll leave it up to you guys to give it a try so let's run this code and see how it goes yep i'm good at making mistakes you know so yeah it's um equals to zero perfect let's run the code and let's see what else i've done wrong yes i did wrong all these things will be matrix and not pair matrix oh god what did i do wrong it's i it's punishment for copy pasting anyways um should work yeah it did run time zero seconds let's do a submit and see how it goes yep we are one millisecond 93.29 yep we are one millisecond 93.29 yep we are one millisecond 93.29 memory usage is 40.65 mb less than 62.95 memory usage is 40.65 mb less than 62.95 memory usage is 40.65 mb less than 62.95 of all the submissions okay so i want you guys to improve on this part right then i am going to discuss the solution that i have created earlier though it's showing that memory distribution is 15 percent but i really don't trust this guys over here so i'll just uh quickly show you that i run it a couple of times we're going to have a better result let's take this and let's try it and see like still we're getting the same result or not yeah but uh do give it a try yourself that's highly recommended so i don't need this pair class for this i don't want to look at the code so i'm just keeping it secret so let's do a couple of submit and see um it should be close to 90 or so let's do a submit though i don't trust lead code when it comes to evaluation sometimes because you can see that i have not created anything over here so yeah 97.23 percent so i'm going to yeah 97.23 percent so i'm going to yeah 97.23 percent so i'm going to discuss the solution sometime in the future but do give it a try yourself i have given you a lot of hint about this that you are deleting the first row or not just keep a track of that the way i have explained it over here so do give it a try do let me know what you think about it if you have any doubts or question please feel free to post it in the comment section below i'll be more than happy to discuss it with you guys and give my inputs for the same so yeah that's all from this video i hope you guys liked it to let me know your thoughts about the video and um see you guys stay safe take care and see you soon again bye you
|
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
|
739 |
hello hi guys it has been asked by Amazon Facebook Tik Tok Microsoft Apple Visa sap Google Bloomberg service now phone pay tin of pyan Salesforce Co Adobe Yahoo Uber and so many companies so let's see this problem again Although seeing this you might see it's a traditional easy medium problem but I swear it is not it is actually tricky and medium hard and for sure if you don't even know the standard problem then it's hard if you know the standard problem but then coming on to the most optimal solution it's CH medium hard let's see what the problem says um and yeah again if you are not able to medium like Medi like the last most optim solution I recommend hats off at least you did the standard approach so problem says that we are given an array of temperatures where which represents the daily temperature right and we have to return an array answer such that the answer of I like answer five is the number of days you have to wait after the I day to get a warmer temperature which means the temperature should be higher than that of the higher temperature how many number of days I have to wait so as to get the higher warmer temperature and again if there is no future day for which it is possible then simply put okay zero that is no future day possible for example if I am standing on 69 what is the next day to me which has a higher temperature I can simply keep on going on the right and I'll see okay 72 it is the first day having a higher temperature than me so for him the answer is just one as you can see for him the answer is just one day or if I go back and show you it's much more easier to visualize let's say for example for 74 he will go and ask bro I want the just higher temperature than me I like I just want a higher temperature than me next to me as in like as close Okay so he can go and keep on going on the right oh as soon as he finds a higher which means temperature more than 74 he can see okay in the one day itself I found for example for 75 he will again keep on going in the right okay right he needs to find in his mind he needs to find the temperature more than 75 okay 75 uh 76 oh more than 75 so at the fourth day I can find it so answer is four for him and the same way he can keep on doing for every of those okay for him for this day also he can keep on going on the right so I got to know that okay for every day I can keep on going on the right and the first day where temperature is more than my temperature that is my day and the difference of the indexes is the number of days which I can give so you saw that okay on every index I will have to keep on going on the entire right so it's rough like it's roughly of n Square algorithm but for sure we can see in the with the constraints n Square will never work and always n square is most worst approach but still in some case it can be a good approach also but yeah here it is not but do we see what we need to find out that if you can just convert the same English to something else it just says that you have to go on the right and the first number which is higher than me I have to return that index or that number or that difference between the index with that index and my Index right so I have to return that so first which means closest neighbor which is more closest neighbor to the right which is more than me I have to find that for every number now whenever the things come okay closest neighbor to the right closest neighbor to the left which is more than me or less than me then we for sure no we apply a standard trick called as monotonic stack that's a very standard as soon as the word comes in closest neighbor greater than or equal to greater than me like something like that okay first there are two words closer to me and greater than less than greater than equal to less than equal to anything like that in the left and then in the left or in the right in and like when any of these okay closest greater less any of these left or right any of these so in if this combination comes in we know we have to apply a monotonic stack that's a standard and if you're not familiar with it just go and write on YouTube moning stack by RL you can see many videos in which we have discussed this approach so one thing we have again if you don't know what is mon simply hold on we will see what it is but it is just that whenever we have to find the closest neighbor which is more than or equal to or like more than or less than equal to in the left or in the right we use moning stack now coming on back that how we can actually use it's very simple that we simply know that for every number I want the higher number again it is a monotonic stack so I know that my stack can be increasing or decreasing now I just know in my mind that I will apply a monitoring stack but I don't know if my stack will be increasing or decreasing again this will entirely depend upon the demand of the problem what the problem says what the problem wants the higher to know or to stay so I know okay for every number I have to go and iterate on the right for this number I have to go and itate on the right which means for right I should have the answer so what I will do I'll trade from the right itself okay 73 is the first number and again uh for 73 it is a first but before inserting into a stack hold on let's see now who is actually having a higher temperature but I can see my stack is itself empty oh no worries so for him the answer is zero okay 73 is gone I'll insert my 73 in my stack but you remember right I want the days for days I need to have the index so rather one option is that you can store only index which is only index 7 because with the index 7 you can easily grab the value also from the input temperature array but for Simplicity or for you to visualize I will insert both the values which means 73 and the index 7 73 is to compare the actual values and index 7 is to actually know that what is the difference what is the actual difference in the indexes which will give me the number of days okay then this is gone then I'll go to 76 now again I'll check the Top Value if it is more than me because if it is more if what is available in the St if it is more than me then for sure that index would have higher warm than me so he is actually having a higher warm and that is what I wanted but I can see that 76 on the top is 73 it is not having a higher want so it's obviously not useful for me so for me the answer he will not contribute so one thing now one doubt I will come shall I remove it or shall I keep it so for sure that for the next one now without even thinking that if to push it or remove it for the next one just start thinking for the next one he would know that the high temperature is 76 so when he has found a high temperature he will never be going to a lower temperature which is after him so he which means 73 will never be required if my higher temperature has come in picture so I know one thing for sure I will have to remove my 73 and now because of this I'll push my 76 with the index 6 but still his answer is zero so no worries now okay this is gone now I'm at this index now at 72 he will check okay is the higher temperature already seen yeah 76 already seen bro good oh I'll check okay my index is five his index is six so answer is 6 - 5 one okay answer six so answer is 6 - 5 one okay answer six so answer is 6 - 5 one okay answer is one okay great that is done go on to 69 again you did that but please also push that to a stack because for the future person who is coming in the next he can have this uh as a result so I'll push in this 72 and 5 okay for 69 he can see okay 72 is for sure more okay for 69 the answer is 72 5 - 4 answer for 69 the answer is 72 5 - 4 answer for 69 the answer is 72 5 - 4 answer is 1 okay great answer is 1 69 comma 4 push into the stack for 71 69 is not good okay simply remove it okay then 72 yeah it is good so answer for him is 5 - 3 so answer is two answer for him is 5 - 3 so answer is two answer for him is 5 - 3 so answer is two and then I'll just simply push that to a stack and you see that is the reason is called monotonic stack because it you can see it is actually decreasing so from the bottom top it's decreasing that is the reason it is called as monotonic stack so it will always be storing the values in the decreasing or the increasing order now okay say 71 is done great then went to 75 it is more n remove it okay uh is 72 more n remove it now 76 is more yeah so the answer for him is 6 - 5 6 - 2 which is four so him is 6 - 5 6 - 2 which is four so him is 6 - 5 6 - 2 which is four so answer is four okay then push 75 comma 2 in the stack okay that is done for 74 75 is higher then okay for sure answer for him is 2 - one so answer is one for him is 2 - one so answer is one for him is 2 - one so answer is one for him now go on to last one which is 73 again sorry push the 74 comma 1 now for last one it is 73 again we'll just simply say that 73 higher value is 74 then simply uh like we will get a four sorry we'll get a 1 minus 0 index difference which is the answer and I'll simply push this back also in the stack and then ultimately I see okay I have already done this so answer is already made simultaneously and you saw I did not do anything else I just used my stack and you saw every element was inserted to a stack and REM from the stack exactly once so for sure we know one thing that iners case it will be o of n time because I'm using my stack which means see I inserted my all the elements just once and because of this insertion of all the elements once I'm also removing all the elements once so one time insertion one time new that's exactly o n operation which we are having and thus it's exactly same which you have to do and it's a easy approach to this problem that's it now if you see that again in this example I have taken a stack I've taken a stack but I've taken that a pair of the value and the index but I'm telling you can only solve it just by the index itself because from the index you can very easily go and find the value because of this temperature array but for easy visualization I have taken both the values okay great because space will still remain same space will still be o of n because the stack being used now as I show you I'll go on from the very end I will check if my stack is not empty only then I can start comparing the top of the stack I'll check the top of the stack when I say top I mean the stack value I'm not saying index stack Top Value First is the value I compare the stack top first value if it is less than the current it's good bro please remove it so I'll simply remove that from St because I know that I want a temperature inside my stack Which is higher than me and this is less than me less than equal to me I'll simply remove it okay when this is simply removed simply being popped again until I have got that I simply Mo it when now for the current temperature which means I temperature I to find out what was the actual High when this entire thing is done which means all these smaller temperatures are removed so for sure either the stack would have been empty all the stack top element would have had a higher temperature than me so if the stack is empty then for short the answer is by default are zero but if it is not empty then the answer of I will be nothing but the stack tops index minus my current index because that is the number of days which will be required from the idea the day to the stack top Index right so that is the number of days which I will contribute to my current answer of I and now I can simply keep on going forward just make sure to push the current index like to push the current element which is the I element into the stack so I'll push my temperature and the I index into my stack so as he can use forward like next time and thus I can simply get my answer populated so you saw that it will take o of end time and O of n space and that is a easy approach for this now comes the most tricky part can you please optimize it now stack which means using a monotonic stack is itself an optimization which mostly people think of that okay it's the best they can do but now comes that they are asking for optimization if you remember that okay we use o n time and O of n space now time will for sure be o of n we can never go beyond or basically below o of n because we have to build an answer are of size o of n so for sure we have to go on and iterate on the N elements of the array so answer will for sure be o of n man we can never optimize it the only thing which is remaining for me to optimize is space but now if I am saying to optimize space I'm asking you okay don't use extra space which means don't use stack at all but we remembered that to find the next higher element closest next higher element we use a stack but now we cannot so that is an issue we cannot use a stack here then how you will find it does like again if you were not able to reach at this point I recommend okay that's completely okay please don't think it's actually very tricky to think of now we will start off again we will start off and think off that how we can actually reach or find the value without using a stack so okay if I am at this place I know okay I have found nothing in the left okay there's no temperature even so one case I can put again I'm just saying one case one if condition I can put off is if I found a no if I have found no temperature or basically if I am at the last index then my answer is zero that is I can put a again I'm just trying to build the answer that's it now let's say if I go on to index six now for this uh for this I know the answer is zero because I could not find any higher I cannot find any higher temperature than him on the right so uh to solve it fast one thing I can do I can actually store the highest temperature itself as you know I can as you know I moving backwards so I can keep sorting the highest temperature let's say name it as hottest so hottest temperature so far is 73 if my current temperature which is the current warmth which is 76 if it is higher than the highest temperature I have got so for sure the answer will him will never lie on the right side so one thing is okay I can also make sure that um by default I can initialize my hot test to a smaller value which is minus one and I'll try to maximize it as I'm going backwards now as I'm going backwards as I'm trying to maximize it I know if the current temperature if it is all already more then for sure I can never find the answer so this is I can store a variable okay great then next time go on to next index now for him um hottest okay it is less than the hottest because hottest right now is 76 it is less than the hottest but still hotest can be anywhere um shall I keep the index of hotest that is not efficient like that is not required because maybe like hottest is here or maybe hottest is here but maybe the nearest closest to him which is higher than him is maybe somewhere else so I might not know so I cannot use hotest concept here so what I can do is okay let's go and search for the adjacent one I'll go and ask bro uh the next one to him the just next one to him that bro H are you having a higher value than me higher temperature than me then he'll say yeah bro I have so then the difference is one yeah it is one so are you saying Aran that will you go on again okay let's say if it would not have had the high temperature so you would have gone and asked the next one then Square which you are doing ah wait hold on let's say we go on to next element again he will go and ask adjacent yeah it is high okay answer is one but I that's the best case you are showing us no worries hold on let's say it goes to 71 then he will go and ask his neighbor okay bro uh is are you less no he will say bro I'm not less so now rather than going on and checking his adjacent which means 69th adjacent I'll go and check 69th answer he will say that I the next higher value to me is actually one distance away from me so I'll say okay if it is one distance away from me so for sure I can go onto that specific and check if he is higher than me again it might happen that you might not understand this but keep on going 5 minutes of this video from now and you will understand this now you will say Okay AR then it is it goes to 72 it is higher than 71 so it is answer okay that's true but ultimately are inly saying now that it went on to neighbor and then next neighbor this is your saying right there's a difference between me saying that I went to a first neighbor and then I went on to his answer rather than his neighbor I went on to his answer how his answer will affect that you will see that's the biggest impact which you can actually see how for example you want to find the answer for 75 he will go onto his neighbor for sure to know that if he is high or not like not that high but if he has a higher temperature or not uh so he will go and check okay it is less now rather than going on to its neighbor He he'll go and ask his answer bro he will say that bro the next higher to me okay you got to know that 75 is higher than 71 so for 75 71 is not the answer for 75 5 he need a higher value than 71 so one way was he could have gone to next element but if my 71 had already stored that the next higher value than me is actually storing at two distance away from me two distance so rather directly jump onto that distance okay I'll directly jump I get to a distance I'll get to a value as 72 still it is less than 75 I want again for this IAT index I want the higher element which is closer to him but here we got a 72 Which is less so again I have to jump aw again ask his value okay bro how much you think is far away from you who's having a higher distance than you so he will say bro it is just one distance away so I'll jump one distance and then I got another value which is 76 so you will see okay 75 it is less than 76 so for me this is the answer so I know okay I jumped one distance then two distance and then a one distance so my distance jump will be four okay that's the answer but Arian hold on I can easily see that okay for this element you are doing so many jumps and same way maybe for the other element you will again do so many jumps so indirectly although it is less than n Square we can see it is less than n Square it is more optimized but still I can already see from my naked eyes that is of n Square you will see that no it is not because let's imagine the worst case which means okay you might see now if have so many jumps then what let's see now let's see if I made the exact same scenario in which you will have so many jumps for example again you are going from the you are going on from the very back for this nine okay answer will be zero for this seven the adjacent is nothing but just Adent okay it's the best case Okay one again it's the best case again it's one it's the best case again it is one okay one distance away or one days away I have the answer but now comes the two so he will try jumping so for two he will try and go adjacent one but one will say me next high distance is three okay so in two jumps I was actually able to figure out the answer okay great for him again it's just saying again I'm saying just two jumps he was able to figure out the answer but I will in average show that how it is actually able to optimize by showing all the cases now for four let's say for four he want to find the answer so what he will do is he will go and ask two because for sure adjacent is two again adjacent is two but then two will say bro next higher will be a three then he will just go and check three's higher which is five so he actually go he actually Four went to two directly went to three not going on to one and then three went to my five okay and the same way okay for six he will go to four then four will Direct ly go to five and then five will directly go to seven you saw that the jumps are just three 1 2 and three which means on every element I'm just going twice okay eight will go to six will directly go to my seven and seven will go to my nine so now you have imagine the wor stage which you were thinking in which okay if I had so many gems there so many gems will actually be optimized like this but AR that is seems like a best case which you are showing us can you show some other case yeah for sure there's another case which you think okay what if for every element okay here you showed us just three gems for everyone but what if I have a kind of skewed things if you have a cute thing then for sure you will jump here okay for 75 to know the answer because for 74 adjacent is six adjacent is four adjacent is three adjacent is two and for him for 75 he will go and ask bro what is the P best next so for 75 when he has his neighbor he will direct him to next value then he will next value then you might say okay for 75 he has to do 1 2 3 four five gems that will be a worst case right because for everyone maybe it will happen no because if next element will come now next element can either be smaller or larger so let's take both the cases if it is smaller than for sure adjacent one will be larger and that is what I wanted okay that is a one jump case but if it is larger then I will jump onto my adjacent one which is for sure I will jump and check his value and then 75 will say bro next higher value than me is at 76 so you never jumped these values at all again you will never be jumping these values at all again so you will directly jump on to 76 so you remember like you saw that you jumped onto these values when you were finding their answer which means for uh for finding answer for 71 I went on and jumped on to 72 that is obvious I will jump on okay for finding answer I jumped on to 72 again and this values I jumped on to find again the next time I jumped on was to find the answer for 75 because I remembered 75 is a higher value so I kept on jumping to find his higher value which is 76 now when this specific path is made next time anyone comes on to him because again like when I said time I mean actually going backwards so when anyone next comes on to him he will not be allowing to jump like this he will say directly jump on to these values so you saw that at these points I am jumping at Max twice right at Max twice and does and th you are jumping you are using every element at Max twice and that's how you can simply prove it again it was for you to visualize but it was for you to prove that it will jump at Max once now let's have a quick dry run that how we can actually solve it now we just have these two cases that as we saw we will keep that track of the hottest temperature which we had so I'll keep track of the hottest temperature if the current temperature again we saw that with this case we would not be able to handle the hottest temperature case because he might end up keep on going forward because he could not find it so it's good to handle the case before even going on and checking the neighbors hand this case if the current temperature which you are at if it is more than the hottest temperature which means I can never find hotter temperature in future because hottest temperature is even less so I cannot find any hotter temperature in future so simply update the hottest temperature and then continue and again initialize the answer by default to zero other case that which we saw that if you add the I index we will simply go and check the neighbor is at a days Days distance of one so basically days or distance will be one for neighbor so I will go and check the neighbor which is by default initially again it's a v loop as we saw in the stack also it's a v Loop and again we saw that this V Loop can because of this V Loop it will at Max go to every element just once sorry just twice so at Max it will be of n itself time complexity now coming on back um we can simply see that we have to have temperature we'll check for I plus days which is the next element because days is initially one so this I plus days I is nothing but two so 2 plus days is nothing but one so you'll go and check for the day one value if it is more then okay that's great simply break and find the and attach the answer for him but if it is less then simply keep on going until you find a larger value so I can see 7 F which is this value it is less than equal to my current temperature of I which is this value if it is lesser check the answer for him which is two okay now we need now we know that we will jump two distance which means in the current I which means again you remember my days were initially one this was my day now my he's saying this is the answer which is two so now my day becomes two so I am saying just add this now you will be jumping doing a i + D so now you will be jumping doing a i + D so now you will be jumping doing a i + D so I'll see my days will actually increase by this specific answer which he has given which is two and now my days will increase by value of two so now my days have become a three and now okay I know that I will now be comparing my 72 value with 75 so this I + 3 which my 72 value with 75 so this I + 3 which my 72 value with 75 so this I + 3 which is I plus days I compare that with my I which is I'll compare my value 72 with the value 75 if okay for sure it is less then again simply you'll go and check his answer which is D equal to 1 so you know that D equal to 1 again so your D has now increased ear it was three now it is increased to four so now your D has become four so you know next time you will jump the d i + 4 this is time you will jump the d i + 4 this is time you will jump the d i + 4 this is what you have to jump next time as compare what values so I'll compare the 76 and 75 so I know that 76 is actually more than 75 so I will break out of this Loop and with that I can find the answer for this specific and again answer of this specific I index will be nothing but how many days I had to jump and you can see these were actually Four because you break out of the loop so it be nothing but the days itself which was the variable which I was actually adding the answer to thus the code is as simple as that as I showed above also that we will just simply have and we have the vector as answer initialized to zero hottest is initially minimum value because I'll try to maximize it as I keep on going backwards now as I'm going backwards I'll just update the hottest again if the hottest temperature if the current temperature is more than the hottest temperature then for sure I can never be able to find the hottest temperature so I'll just simply continue from here itself but if not then I'll simply use this y loop as I explained above also and with this I'll get the days as the proper days for the current I index and that's I can simply return the answer thus I'll get my time as o of one o of n because I am visiting all the elements exactly once exactly twice like inverse case twice and space is O of one because we are not using any extra space again please don't count the space of answer because it is required by the question so we don't count something which is required by the question we count something which is we add extra for solving the answer I hope that see you goodbye take care bye-bye and again you goodbye take care bye-bye and again you goodbye take care bye-bye and again if you were not able to solve it is actually the special optimization part was actually tricky especially to prove that why it is O of n bye-bye
|
Daily Temperatures
|
daily-temperatures
|
Given an array of integers `temperatures` represents the daily temperatures, return _an array_ `answer` _such that_ `answer[i]` _is the number of days you have to wait after the_ `ith` _day to get a warmer temperature_. If there is no future day for which this is possible, keep `answer[i] == 0` instead.
**Example 1:**
**Input:** temperatures = \[73,74,75,71,69,72,76,73\]
**Output:** \[1,1,4,2,1,1,0,0\]
**Example 2:**
**Input:** temperatures = \[30,40,50,60\]
**Output:** \[1,1,1,0\]
**Example 3:**
**Input:** temperatures = \[30,60,90\]
**Output:** \[1,1,0\]
**Constraints:**
* `1 <= temperatures.length <= 105`
* `30 <= temperatures[i] <= 100`
|
If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next.
|
Array,Stack,Monotonic Stack
|
Medium
|
496,937
|
1,011 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem capacity to ship packages within D days so we're given an array of weights for example something like this one two three four five starting at the beginning of the array we want to break it up into chunks such that carried by a ship the ship will have some capacity so we have to make sure that the ship can hold all of these weights and then we'll have another ship maybe for this set of Weights our goal here though is to choose a capacity we are the ones choosing the capacity of the ships and our job is to choose a capacity for the ships such that it is the minimal capacity that we need to carry all of these weights given this many ships now you might notice that the context of this problem they're talking about the number of days that it's going to take us not the number of ships but I think thinking about it in terms of the number of ships makes a lot more sense because it's equivalent to this problem and I think they're probably just trying to make it more confusing by making it number of days so let's think about it in terms of number of ships so for example if the number of days aka the number of ships is equal to two that means we have to load all of these weights onto the two ships and we have to choose the minimum capacity of our ships each ship will have the exact same capacity but we have to choose this value maybe let's try choosing one for the capacity so when now when we break up the array we have to start at the beginning and create contiguous chunks our first chunk is just going to be one that's going to fit on the ship and then we have a second chunk that's two well that's not going to fit on the ship so it's not even possible to do this with ships with a capacity of one this is the first observation that I made when I was solving this problem that at the very least the minimal possible capacity that we have to choose will be the max value in the input array in this case it's five so that's the lowest capacity we should even try going with so let's now change this to five but even knowing this how do we make sure we minimize the solution with a capacity of 5 we could do this subarray it has a sum of three we could then do this subarray in another separate ship that has a sum of three we can't include both of these together because that's a sum of seven we can't fit those in a single ship but you can see we're already running out of ships we have two ships and we'll need a third one for this and a fourth one for this that's not gonna work so now what should we do we tried five that's not the minimal answer it doesn't work so then maybe let's try six that won't work either but the only way we'll know is if we go through the entire array we can load these three on a single ship this on a single ship and this on a single ship that's three ships but we can only have two ships so this is a Brute Force approach but you can tell it's gonna be N squared is there any other observation you can make well we know we're gonna need at least this much capacity is there an upper Bound for the capacity as well for sure at the very least we know the highest possible capacity we would want to choose would never be higher than the total sum of all of these weights because why would we do that when we're trying to minimize the capacity we don't need a ship with more than this much capacity and if we have multiple ships we'll probably need less than that but this is still a good upper bound the sum of the input array so in the context of this problem for our capacity we know that the lower bound is going to be 5 that's the maximum value in the input and the upper bound is going to be the sum of the input array which in this case is 15 so this is our search space we know our solution is somewhere in here so we can try the Brute Force approach going through each of these but an even better approach would be to run binary search on this search space now that we have decomposed it into a binary search problem that is going to be the most optimal solution and if you're wondering how I was able to figure it out well as soon as I noticed that the capacity had a lower bound the next question I asked myself is does it also have an upper bound and the answer was yes as I just explained and as soon as I knew that I knew this was similar to another leak code problem that I had solved leak code 875 and this problem is nearly identical so it's all about pattern matching I have a video on this problem as well if you're curious It's Coco eating bananas but now let's simulate a binary search on this so I'm going to initialize our left bound as being five just like down here and our right bound is going to be 15 for our binary stretch we're going to take these two atom together and divide by two that's going to lead us to a mid of 10. it's not a traditional binary search like we do like on here like left and right but we're going to be searching this so it's a bit different but with a mid value of 10 what does this 10 represent it represents the capacity of the ship we have two ships at most so let's try this a ship of 10 capacity we can fit this guy and this guy I would know that by summing all of them up and they sum up to 10 we can't fit the 5 though but now we can add it to its own ship so with a capacity of 10 it does work but we're trying to minimize the capacity so let's try again with a smaller value so what I'm going to do now is set the result equal to 10 that's the minimum so far but I'm now going to try to lower my search space to find maybe an even smaller value so I'm going to change the right pointer now to M minus 1 that's 10 minus 1 which is 9. so now let's try adding these two dividing by two that's going to give us a mid of seven so a capacity of seven can we fit all of these with two ships with a capacity of seven we can fit this and we can't fit the four but we can add it to its own ship but with a capacity of seven we can't add both of these so seven does not work our result is going to stay nine but now we actually want to increase our search space so we're gonna set left equal to Mid plus one it was seven so we're going to set it to seven plus one which is eight and at this point I'm just gonna fast forward and tell you if we try a it's not going to work we're gonna get this and this in its own ship but if we try nine we're gonna get these three in its own ship and this in its own ship that does satisfy the requirement we only needed two ships and this happens to be the minimal capacity that we needed among all of them that we tried so that's the solution now in terms of time complexity it's going to be n because for every capacity we try we have to in the worst case iterate through the entire array so that's where the N comes from now multiply that by the binary search at first you might think it's log n but what we would log is the size of our search space what is going to be the size of the search space in the worst case well the lower bound maybe might be zero or something like that but the upper bound is where the time complexity is going to come from because it's going to be the sum of the input array so let's just say m is the sum of the input array now it turns out that m is not going to be like a huge number because each individual weight is capped at being less than or equal to 500. so this is a pretty efficient solution about as good as we can get so now let's code it up so the first thing we're going to want to do with this pretty non-traditional binary search is to non-traditional binary search is to non-traditional binary search is to initialize our range we know that the lower Bound for the ship capacity we're going to need is going to be the maximum of the weights and the upper bound is going to be the sum of all of the weights and we're going to initialize our results since we're trying to minimize it initializing it to zero wouldn't be great so we're going to initialize it to the maximum of our search space equal to R But ultimately we're going to try to minimize it so now to move on to the actual binary search this is how I like to code it up because you can pretty much do it almost the same way every time I usually set left less than or equal to the right pointer then I compute the mid so the simplest way to do it is left plus right divided by 2 though sometimes this can give overflow but then we want to know does this m which is the capacity maybe I should rename it cap can this ship all of the weights given this capacity can we ship all of the weights if true and I'm going to Define this helper function in just a minute but if it's true then we're going to do something otherwise we're going to do something else if we can ship it maybe this is a new minimal result so we're going to set the result equal to the minimum of itself and the capacity that we just computed and we're going to update our range we want to now try to find an even smaller capacity so we're going to set our right pointer to M minus one in the other case we would want to increase our range because we're trying to find a higher value so we're going to set left equal to Mid plus one after this binary search is over we know result will have the minimum capacity so we're just going to return that now the only thing left to do is our helper function which we know is just going to be a loop we're going to Loop through the entire input array so can ship given some capacity so we're going to go through every way in the input weights what we're trying to do though is count the number of ships it's going to take us I'm going to initialize that to one because we know we're going to need at least one ship and I'm gonna set the current capacity of that ship equal to the capacity that was passed in as a parameter so now I'm going to go through every way and we're gonna subtract from the capacity the current capacity the weight that we're adding to the ship but it's possible that the current capacity can't hold the weight meaning the current capacity subtracted by W is going to go negative that means the current capacity can't hold the weight so then what we're going to do is increment the number of ships that means we need another ship let's increment that by one and then reset the current capacity equal to the original capacity this is a fresh ship therefore it should get a fresh capacity and then we will subtract from the current capacity now if we execute this if statement this is never going to make the capacity go negative because remember our search space was initialized like that deliberately we took the maximum weight so no matter how big an individual weight is it's never going to make this go negative if it's a fresh capacity after all of this is done we're going to return the result is can we ship or not and we know that if we take the number of ships that we computed is less than or equal to the number of days that was given as a parameter which you know I've pretty much ignored the context of the number of days this should just be the number of ships but oh well that's the entire code though and of course I called these M instead of cap because that's what we were doing in the drawing explanation so let me fix that and rerun it as you can see it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neat code.io it has a ton of free out neat code.io it has a ton of free out neat code.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
|
Capacity To Ship Packages Within D Days
|
flip-binary-tree-to-match-preorder-traversal
|
A conveyor belt has packages that must be shipped from one port to another within `days` days.
The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days.
**Example 1:**
**Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5
**Output:** 15
**Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
**Example 2:**
**Input:** weights = \[3,2,2,4,1,4\], days = 3
**Output:** 6
**Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4
**Example 3:**
**Input:** weights = \[1,2,3,1,1\], days = 4
**Output:** 3
**Explanation:**
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1
**Constraints:**
* `1 <= days <= weights.length <= 5 * 104`
* `1 <= weights[i] <= 500`
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
393 |
this is little question number 393 etf a validation this is medium question let's get into it a character in youtube eight can be from one to four quite long subjected to the following rule first for one byte of character the first bit is zero followed by its unique code number two four and byte character the first and b are all ones and m plus one bit is zero or followed by a minus one byte with the most even got to beat being ten okay uh this is how the youtube8 encoding would work okay let's check with example okay this is one bit and one bit mean is the first uh first bit is the zero so there won't be zero and then next is if it's two bit that mean is same as a number of one so this number one is two so one two this one is the number of verses three and one two three number four one two three four given an array to integer refresh into data return whether it is a valid utf-8 return whether it is a valid utf-8 return whether it is a valid utf-8 encoding okay so we need to check the format is valid if the this one is valid the utf-8 will the this one is valid the utf-8 will the this one is valid the utf-8 will return true authorized first so in this time we need to check the three thing first is the first two characters the first bit so if it's zero is one and then if this is a two and then we also check second is the ten uh okay let's say if there are one more ten is here what is the return value that's right this is first because one means there are only one is 10 one required if there is another 10 one we need to check the first and then okay let's say if the this one is missing which value we need to return that's right we also return first because for me needs uh the writer there's comes up with three more characters and then that one must be start with ten one zero if this makes sense okay let's check with example one so given data is 197.131 so 197.131 so 197.131 so first we need to change it to binary so binary first is the two one so one we need to check this one and the second one must be stat 110 there are only one required so this is a valid we can next check there are no one here they mean this one is one bite so this one true and this one is true so return must be true uh okay let's check example two is the 235 144 which reference one was set okay this will change to binary is this one there are three a so next there are uh we need two more bytes start with only one so this one is okay but oh this one is not one so return first if this one is a one start one and then next is zero we need it to return true okay how are we gonna do all right uh today i'm gonna use the uh the bit operation and especially i will use a bit mask so first and then i will use it to checking the numbers end and then next is i will do i will keep the rule i will check the rules step by step and then every the rule is the valid for utf-8 utf-8 utf-8 i will return to otherwise i return first okay let's influence the code first i will make the function name is count once and i'll list knowns num and then i needed a counter that is zero and then for i in range uh this is okay this is utv8 means that it is need the 8 bit so every iteration only the zero to seven and first bit mean is uh okay first i need to check one and then there are seven zero so that mean is this one read shift seven same as distance shift saber that's right so first i will start cheat seven and then to zero and then decrease one by one and i will check if num and bit mask bit okay let's generate speed mask one i i7 this is what minis this if that means this is bit mask and then there are some values four five six seven it will compare this one with this so one mean is this one must be one so in this case i will increase count one otherwise i will break because somewhere over there is the zero so i need to break and then before that is the count is the same as number one does this make sense okay and then we need another counter this one needed a different with this one so now first i'm gonna check that the number of this one and then put into the counter and then if the check the next one i will reduce counter and if counter is zero i will also check how many uh number of ones the start read and then i will iteration again and again to check it so next i will utilize early trade i will get a data i will get item from data so 4d in data and first if counter count is general that means this is the first if that is the first this is counter zero i will get that this one right so in this time i put column is count once and d and then now in this case it will return true two right and then next okay let's uh let's make some let's pick some wage case okay let's say if count is zero that mean is this is just one byte right so if count is zero i just continue to check next also we also need to check the counter that means if this one is zero and then this one will be valid so we will check next one and then we will check the number of one right and then as if counter is one in this case uh if the 10 one is the first it this time we needed to reach out to our first yeah that's right first because uh one only one number one is only one it cannot that cannot position in the front there are no one zero right zero and one zero always uh place this from the second not the first that this makes sense so one and then another thing if there are five one that is valid no because we just check one two four by two low so the five it means that the point is not valid so this one or count is more than four return first and then next is uh if that is the two how many check the one two start with it itself so next mean is we need to decrease counter so one two minutes only one we need to check the one you want so it is time we need to reduce one yes as mean is now we are here so we need to check this before check i will decrease counter for next two iteration and if count once is t is not one because next must be a number one is must be one in this case it is not valid and then finally we checked count is zero ten minutes uh as i mentioned before if this one is two three minutes our next two byte we need two more byte if this is only one what this is three that does not make sense that must be returned first that is legion we why we need to change the left counter okay looks good awesome okay let's check time complexity um in this case you take linear and how about this yeah that's right there are one iteration but luckily this one is the constant only it reiterates eight times eight time means we can say this one is take constant time and then this one take a linear time so and then is there any the extra space no there are no extra space so i can say uh it take a linear time with a constant space thank you
|
UTF-8 Validation
|
utf-8-validation
|
Given an integer array `data` representing the data, return whether it is a valid **UTF-8** encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).
A character in **UTF8** can be from **1 to 4 bytes** long, subjected to the following rules:
1. For a **1-byte** character, the first bit is a `0`, followed by its Unicode code.
2. For an **n-bytes** character, the first `n` bits are all one's, the `n + 1` bit is `0`, followed by `n - 1` bytes with the most significant `2` bits being `10`.
This is how the UTF-8 encoding would work:
Number of Bytes | UTF-8 Octet Sequence
| (binary)
--------------------+-----------------------------------------
1 | 0xxxxxxx
2 | 110xxxxx 10xxxxxx
3 | 1110xxxx 10xxxxxx 10xxxxxx
4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
`x` denotes a bit in the binary form of a byte that may be either `0` or `1`.
**Note:** The input is an array of integers. Only the **least significant 8 bits** of each integer is used to store the data. This means each integer represents only 1 byte of data.
**Example 1:**
**Input:** data = \[197,130,1\]
**Output:** true
**Explanation:** data represents the octet sequence: 11000101 10000010 00000001.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.
**Example 2:**
**Input:** data = \[235,140,4\]
**Output:** false
**Explanation:** data represented the octet sequence: 11101011 10001100 00000100.
The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.
The next byte is a continuation byte which starts with 10 and that's correct.
But the second continuation byte does not start with 10, so it is invalid.
**Constraints:**
* `1 <= data.length <= 2 * 104`
* `0 <= data[i] <= 255`
|
All you have to do is follow the rules. For a given integer, obtain its binary representation in the string form and work with the rules given in the problem. An integer can either represent the start of a UTF-8 character, or a part of an existing UTF-8 character. There are two separate rules for these two scenarios in the problem. If an integer is a part of an existing UTF-8 character, simply check the 2 most significant bits of in the binary representation string. They should be 10. If the integer represents the start of a UTF-8 character, then the first few bits would be 1 followed by a 0. The number of initial bits (most significant) bits determines the length of the UTF-8 character.
Note: The array can contain multiple valid UTF-8 characters. String manipulation will work fine here. But, it is too slow. Can we instead use bit manipulation to do the validations instead of string manipulations? We can use bit masking to check how many initial bits are set for a given number. We only need to work with the 8 least significant bits as mentioned in the problem.
mask = 1 << 7
while mask & num:
n_bytes += 1
mask = mask >> 1
Can you use bit-masking to perform the second validation as well i.e. checking if the most significant bit is 1 and the second most significant bit a 0? To check if the most significant bit is a 1 and the second most significant bit is a 0, we can make use of the following two masks.
mask1 = 1 << 7
mask2 = 1 << 6
if not (num & mask1 and not (num & mask2)):
return False
|
Array,Bit Manipulation
|
Medium
| null |
347 |
hi everyone let's delete code 347 top K frequent elements we're given an array of integers and an integer K we want to return the K most frequent elements to better understand this let's look into the example the output is 1 and 2 and K is equal to 2. it means that they wanted the two most frequent elements in this input array in this case three appear three times two appear two times and three appeared one times so if we look at the most frequent elements is one and two hence the output is a list of one and two one way of solving this problem will be to use a heap there is a function called hipify in Python the hipify function converts an input list into a mean Heap and this function takes big O of n time so one way doing this will be to create a heap and then pop K times from this hip and each pop in a hip takes big O of log and time if we were to use a mean Heap the final time complexity would be K log n where K is the number of times we're going to pop and log n is the time complexity it takes to pop from a heap we can do better than this another way of solving this problem would be to use something similar to account sort so we would have an array where each position in the array is going to represent the frequency of the elements that are inside the array so let me explain this a bit better one thing to note that the resource opposition zeros this is going to be an array but we are not going to have elements with frequency zero so that's why I then put it here in order to use this solution we are also going to need a hashma so in this case the harsh map is going to look like this basically the hash map is going to contain the frequency of each number that is appearing in the input array so as you can see the value is going to be the actual frequency and the key is going to be the number in this case one is mapped to 3 2 is multiple two and three is about to 1 because 3 only appears once we have filled the hash map we won't fill this frequency array let's call it like this so in this case 1 is appearing three times so we are going to have a list here with all the elements that are appearing three times in this case it's just one two is appearing two times so 2 is going to go here and 3 is appearing only one so three is gonna go here let's say for example we had another number here let's say 4 which was appearing one time that 4 would go here as well so as you can see this is a list at the end once you have filled this frequency array we want to start a loop that starts at the end we're going to have a result list where we're going to append on the actual result elements so we want k equals to 2 in this case we're going to start here are there any elements here now any here no not here we reached the first most frequent element which is one so we're going to add one here and we still need one more because k equals to 2 we are going to go to the next one we pick all the elements here in this case is only two and we add it to our result and at the end we are going to have our result array one thing you can notice is that this frequency array only has six positions without counting zero this is because the maximum frequency given this input we can have is six let's say every element in the input was all one or six ones we would have just a one here and the rest would be zero so that's the reason why frequency to the a comes up until six time complexity in this case is O of N and same for memory complexity because of the hash map we are using memory complexity is O of n as well I hope this was clear okay let's try some code now the first thing we need is a hash mark to count the currencies of each number in the input list so we're gonna use a hash map the next thing is the frequency list the index of this list is going to be how many times the number has appeared in the input and the actual value is going to be the list with the element that has appeared that many times and we're going to actually initialize it as well the length of this frequency list is going to be the same as the number of elements in the input array now we want to fill the hash map so we want to find the count for each number and we need the for Loop and we simply update how many times this number has appeared here we're going to use the get function of the hash map if the entry doesn't exist so that you are just going to return a default zero so we have fill the hash map now we need to actually fill our frequency list we need the number and the count from the hash map okay so the index is going to be the count at that position we're actually going to append whichever number has discount C we need to declare a result list now so this is what the actual logic goes so now we have all the elements we need to calculate the most frequent element so we need a four we need to go all the way to zero so we're gonna iterate from the end of the frequency list all the way to zero and decrement by one each time each position in frequency could have multiple elements because as you define in line 7 frequency is a list and at each position there could be at least with the results so we need to iterate over that internal list frequency of I so now we can append to our result we know that this is a frequent element and we keep appending until the length of our results list is equals to K once that is true we're just going to return our result let's see if this works well there is a missing in as you can see it does work please like And subscribe if you found this video useful please also check the other blind 75 questions thank you
|
Top K Frequent Elements
|
top-k-frequent-elements
|
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,1,1,2,2,3\], k = 2
**Output:** \[1,2\]
**Example 2:**
**Input:** nums = \[1\], k = 1
**Output:** \[1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
* `k` is in the range `[1, the number of unique elements in the array]`.
* It is **guaranteed** that the answer is **unique**.
**Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
| null |
Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect
|
Medium
|
192,215,451,659,692,1014,1919
|
145 |
hey everyone welcome back in the last video we saw in order traversal of a binary tree in this video we'll see postorder traversal of a binary tree in post order traversal as you know we traverse the left subtree first then travels the right subtree and finally process the root node post order traversal is slightly tricky compared to pre order traversal or inorder traversal so I'll explain the algorithm as we see the visualization now whenever we see a new node or visit a new node we add the node to the stack and then move to its left child here node current points to 5 so we'll add 5 to the stack and move to its left child no 9 is not null so we'll add 9 to the stack and move to its left child node current is equal to null in this case we'll have to check if the node at the top of the stack that is 9 does have a right child so stag dot P cut right is it equal to null yes in this case we will pop the node at the top of the stack and process it so let's create a temporary variable called temp and assign the reference to 9 will process 9 and now we will have to check if this temp node is the right node to the top of the stack so his temp equal to stack not peaked out right no in this case we will have to check if the node at the top of the stack doesn't have a right child it's tagged or peak dot right equal to null no in that case what we'll do is we'll assign current the reference to sag not big dot all right now current is pointing to 8 so 8 is not null we will add 8 to the stack and no to the left child of current is equal to null again we will check if node at the top of the stack does it have a right child so a stag lot big dot right equal to null No so we'll assign the reference of big dot right to current so current is equal to sine dot P got right note 4 is not null so we'll add note 4 to the stack and move to the left child of four note 3 is not null so we'll add note 3 to the stack and move to the left child of current so current is equal to null we'll check if the node at the top of the stack does it have a right child so slag not big not right is it equal to null yes so we will pop the node from the top of the stack so temporary node is assigned the reference to 3 will process 3 and then we'll check if 3 is the right child to 4 so temp is it equal to stack dot peak dot right so is it the right channel of 4 no again we will check if 4 has a right child or not so it's tagged not picked out right equal to null no so current is assigned the reference to stack dot peak dot right now no 10 is processed sorry no 10 is added to the stack and we'll move to the left child of current is equal to null we'll check if the node at the top of the stack has a right child so it's tagged not picked out right equal to null yes so we will assign temp the nodes double stack so temp gets the reference to 10 now we will process 10 and then we'll have to check is temp the right child of the node at the top of the stack his temp equal to stack not big not right yes so we will again pop the node at the top of the stack and assign times the same reference so temp is equal to stop stack dot pop will process this node and then we'll have to check again if temp is the right node to the top of the stack it's my coolest act or peak not right yes so again is assigned staggered pop now we'll process node eight and again check if temp is the right child to the top of the stack in stem Pecola stacked or P dot right yes so temp is assigned the reference to five we'll process five now the nodes in the stack is empty so it will break out of the loop where we check if temp is the right child to the nodes the top of the stack and then we will go to the main loop where current is equal to null and the total number of nodes is also empty so this is the end of post order traversal with this understanding let's try to code here the return type is a list of integer I'll create a list of integer part output will create a stack of tree nodes will create a node called current and the sign the reference to root we could do some null checking if root is equal to null we can immediately return the empty list so while stack is not empty or current is not equal to null that means we have nodes to process here if current is not equal to null then we will add the node to the stack so stack dot push current and current gets the reference to current not left if current is equal to null then we'll have to check if the node at the top of the stack does it have a right child or not so if staggered peak dot right is it equal to null if this is not equal to null then we can assign current the reference to stacked or peak dot right if it is equal to null then we'll have to pop the node at the top of the stack so I'll create a node called temp and then pop the node at the top of the stack will process this node so output dot add temp dot value now we'll have to check if this temp node is it the right child to the node at the top of the stack the new top now so we can do this while stack is not empty and this node temp is it equal to stack dot peak not right if it is if this node temp is the right child to the nodes that of the stack then that means we have done the processing of the right subtree so we'll pop the node at the top which is a which is the parent to this node temp so temp is equal to stack dot pop and we will process this so this will this loop will continue until this temp node is the right child to the node at the top of the stack now with this I think it should work I'll return this output let's run the code for some reason it took a little more time to run I'll submit the solution so it's working fine thank you very much for watching this video if you liked it please hit the like button and also do subscribe in the next video I'll be talking about level order traversal thank you so much
|
Binary Tree Postorder Traversal
|
binary-tree-postorder-traversal
|
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[3,2,1\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of the nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
94,776
|
57 |
welcome back to algojs today's question is leak code 57 insert interval so you're given an array of non-overlapping you're given an array of non-overlapping you're given an array of non-overlapping intervals where interval i is equal to start i and i represent the start and the end of the if interval and intervals is sorted in ascending order by start i you're also given an interval new interval which is equal to start and end that represents the start and end of another interval so insert new interval into intervals such that intervals is still sorted in ascending order by start and intervals still does not have any overlapping intervals return intervals after the insertion okay so in this question we just need to find if there is an overlap between the new interval and the intervals and we need to insert it into the correct order removing that interval so we need to merge potential intervals that are overlapping so here we have one three and six nine and the new interval is 2 5 and the output is 1 5 6 9. the reason for that is 1 3 and 2 5 are overlapping so we take the smallest from both of them which is 1 as the first value and we take the largest 5 as the second value so it's one five six nine and in example two we have this intervals array here and the new interval is four and eight and this is going to overlap with three and five because four is greater than three but less than five it's gonna overlap with six and seven because six and seven can be found within four and eight is also going to overlap with eight and ten so like all the other interval questions we need to start by drawing out the intervals to give us a visual representation okay so this is what we currently have we have one to three we have six to nine and we also have the new interval as two to five and we need to insert this and remove all overlaps as you can see there is clearly an overlap here right so this is where the merge will need to be but before we even do this firstly we already know that the array is sorted so there's no need to sort this secondly let's carry out say an edge case say we have an interval that is say minus one to one do we need to merge this with any of it no because there is no overlap with the new interval that is here so we can just insert this into our result array so let's say we have the result array down here if for example the last value so we have start and end so if end at this interval is less than start at the new interval that we're going to be inserting then we can just insert this interval so that'll be a potential edge case right now we can focus on merging these two so there is an overlap here we have current with start and end we have new interval which we'll call new i start and end and if current start is less than new interval end because remember we've already covered that base case where the end value of the current interval is less than start we'll just push that into res so we don't need to look at the n value now we just are concerned with the start value of current so we check the start value of current against the end value of the new interval if it's less than then we need to update this new interval to equal the minimum between the current start and the new interval start and that will be the left value so that'll be one and then we also need to compare the end values of the two and that will be the second value so that's going to be five now before we push this into res we need to compare or we need to look at the second interval here so this is going to be the new current we're going to have start and end we're going to check if interval at start is less than new interval at end it's not so based on that condition we can push this into results so one and five okay because there is no overlap here we don't have to worry about that then all we need to do if that is the case is just loop through the rest of the current array so loop through the rest of this array and add whatever is left into res so that's just going to be six and nine okay let's look at the second example so let's draw this out with this let's populate the result array so we said that if intervals at end so the current interval we're on is less than the new interval at start then we can just add it into the result array so we can add 1 and 2 directly into the result array so we don't have to worry about that so that has now been seen we move on to three and five end is not less than start so we check the start to see if it's less than end in this case it is so start is at three the end of the new interval is at eight this start is less than the end so we can create a merge from this so we take this value from the start because it's the smallest between the two and we take this value from the end because it's the largest of the two so let's just expand this out now so this is what the current new interval looks like we're going to update the new interval over here as well so it's going to be three to eight we've now seen this one so we can remove that okay so we move on to the next one is the start of this value less than the end of this value yes it is and we have an overlap because the end here is greater than the start over here so again we're going to update the start and end based on this information so the start is going to be the smallest of the two so it's going to stay as this value so as three and the end is going to be the largest of the two so it's going to stay as eight as well so we've seen this interval now so we can remove it okay now we're on this interval so we have start and end is end greater than the start of the new interval yes it is so we check the start is start less than the end no it's not but this right here at the same value at eight is still classed as an overlap so what we'll do is we'll call this current so if current and start is less than is what we've been going with up until now or equal to new interval at end then we update new interval so we need to make sure that we're checking for the less than or equal to in this case we have an overlap so we're going to update the start value and we're also going to update the end value so the start value is going to be the smallest of these two which is already three and the end value is going to be the largest of these two which is going to be 10. so we can expand this now expand that outwards we have now seen this now we move on to the last interval so we'll call this current start and end is current end less than the start of the new interval no it's not so we check is current at start less than or equal to new interval at end no it's not all we do now is push new interval into results 3 and 10 and then we push current into results which is 12 and 16. and that is the final output that we're looking for time complexity for this algorithm is going to be of n because we have one while loop which was traversing through a number of times and then space is going to be one even though we're using this result array to populate our output it's considered the output so we class it as one so let's write this out so res is equal to an empty array we're going to utilize while loops throughout this so we're going to have an index which we start off at zero we're going to initialize start as zero and end as one to make this more readable and then while i is less than intervals dot length so it's inbound and intervals at i end is less than new interval at start we're going to push into res intervals at i and then increment i because there is no overlap between the current interval and the new interval we just push this interval within res then we'll have another while loop so while i is less than intervals dot length and intervals that's i start so start value is less than or equal to new interval at end then in this case we have an overlap so we need to merge the two so we're going to merge new interval so we're going to say the new interval that start is going to be equal to math.min math.min math.min new intervals at start and intervals i start so we're comparing the two start values and we're grabbing the smallest and then we also need to update the end value which is going to be the maximum between the two and then we just need to increment i again so once we've looked through all the intervals where the starting value of the intervals is less than or equal to the end value of the new intervals once we've exit all of those we can just push into results new interval and then there may be some intervals still left within the intervals array that we haven't considered or we haven't checked yet so we need another while loop just to push in the rest of these intervals into results and then we can return red okay let's run this okay so there's a spare mistake let's give it another try submit it and there you go
|
Insert Interval
|
insert-interval
|
You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval.
Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return `intervals` _after the insertion_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[6,9\]\], newInterval = \[2,5\]
**Output:** \[\[1,5\],\[6,9\]\]
**Example 2:**
**Input:** intervals = \[\[1,2\],\[3,5\],\[6,7\],\[8,10\],\[12,16\]\], newInterval = \[4,8\]
**Output:** \[\[1,2\],\[3,10\],\[12,16\]\]
**Explanation:** Because the new interval \[4,8\] overlaps with \[3,5\],\[6,7\],\[8,10\].
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 105`
* `intervals` is sorted by `starti` in **ascending** order.
* `newInterval.length == 2`
* `0 <= start <= end <= 105`
| null |
Array
|
Medium
|
56,715
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.