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
971
hi guys welcome to algorithms made easy in this video we will see the question flip binary tree to match pre-order traversal so over to match pre-order traversal so over to match pre-order traversal so over here this question is a little bit ambiguously phrased so let's go ahead and see this question in detail as what this question is asking from us to do with an example so the question would be having a input tree that is given to us and a pre-ordered reversal for the and a pre-ordered reversal for the and a pre-ordered reversal for the desired tree so i have mapped this pre-order so i have mapped this pre-order so i have mapped this pre-order traversal into the tree that it would represent so now the question is to tell that can this particular input tree be converted into the desired tree but how by flipping the left and right childs of a particular node so over here in this input tree we can say that if we flip the left and rights for this node 1 we can get the same tree that was desired and so our result would contain the parent node for which we flipped its child if in case there is no way to make this particular tree or the desired tree from input tree by the rules given then you need to return minus 1 in that list and if both the trees are equal that is you need not flip any nodes then your answer would be a empty list so these were the examples also that were shown into the problem statement given to us for this video we will use this input and the preorder and we will try to see how we can get our result so over here we'll start with the node 1 and check whether these are equal or not if these are not equal that means there is no way to form this particular desired tree from the input tree given because there is no way we can flip the root nodes we'll only flip the child nodes now if that is equal we need to check whether it's left is equal or not so if this left is equal to the left of the desired tree then we can move ahead with our basic dfs or else we need to flip these two nodes so over here as this is not equal we are going to flip this and so add 1 into our result because we have flipped the nodes that were left and right to 1. once we are done with this now since we were on 1 we need to perform the pre-order we need to perform the pre-order we need to perform the pre-order traversal on the input tree also so we'll go to its left that is to the node 3. since these values are equal we'll move ahead and check its child since 5 is also equal we'll move ahead to its right that is root.right which would be 4. since these root.right which would be 4. since these root.right which would be 4. since these are also equal we will be moving down in our hierarchy and so now we'll move at 5 and then we'll move at 4 so that would give us this that 5 and 4 are also equal so now since we have traversed all my left tree i'll go to the right tree and since these two are equal and the children are also equal that is null so the traversal now gets completed and we return the result that is formed with us if in case the root node itself or the parent node for which we are checking the left right itself is not equal we would have just returned -1 in the list so now we know that we -1 in the list so now we know that we -1 in the list so now we know that we just need to perform a pre-order traversal on the input tree a pre-order traversal on the input tree a pre-order traversal on the input tree and wherever the child nodes are not equal you need to just flip those nodes and by flipping over here in dfs what we are going to do is we will not be flipping the tree but we'll be flipping the order in which we are calling the tree so as in pre-order we call as root left so as in pre-order we call as root left so as in pre-order we call as root left and right in that case we'd be calling root right and left so that would give a view that the tree has been flipped so now let's go and code it out so first let's take a few global variables or class level variables so these will be my index my result and my voyage and over here i'll assign them with this will also have a dfs function which would have a return type of boolean and in this we will pass the tree node over here first thing that we check if the node is equal to null that means we can return true otherwise if my node's value is not equal to the ith value from my voyage then i'll return false over here i am doing an i plus because for the next steps we would need to go on the left and right of the tree so we will be doing a i plus now we will check for the left because our pre-order for the left because our pre-order for the left because our pre-order traversal says that once you have visited the node you need to first visit left so let's check whether my left of the input tree is equal to the left of my desired tree if these values are not equal we need to flip those values and add it in the result so for flipping we'll be doing just our reverse dfs that is first on right and then on left if we do not need to flip this that means the example is correct and so we need to do our normal dfs so we do return on dfs of left and right in our main method we'll call dfs on root and check whether we are getting a true or a false if you are getting a true we need to return the result as it is and if it is a false we need to return a list with -1 in it so that's it let's try to run this code and we need to use the node let's run this again and we are getting a perfect result let's submit this and it got submitted so the time complexity over here would be going on to each node that is the number of nodes and the space complexity would be o of n to store this error list that could go up to o of n so that's it for this question guys i hope you like the video and i'll see you in another one so till then keep learning keep coding bye you
Flip Binary Tree To Match Preorder Traversal
shortest-bridge
You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree. Any node in the binary tree can be **flipped** by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: Flip the **smallest** number of nodes so that the **pre-order traversal** of the tree **matches** `voyage`. Return _a list of the values of all **flipped** nodes. You may return the answer in **any order**. If it is **impossible** to flip the nodes in the tree to make the pre-order traversal match_ `voyage`_, return the list_ `[-1]`. **Example 1:** **Input:** root = \[1,2\], voyage = \[2,1\] **Output:** \[-1\] **Explanation:** It is impossible to flip the nodes such that the pre-order traversal matches voyage. **Example 2:** **Input:** root = \[1,2,3\], voyage = \[1,3,2\] **Output:** \[1\] **Explanation:** Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage. **Example 3:** **Input:** root = \[1,2,3\], voyage = \[1,2,3\] **Output:** \[\] **Explanation:** The tree's pre-order traversal already matches voyage, so no nodes need to be flipped. **Constraints:** * The number of nodes in the tree is `n`. * `n == voyage.length` * `1 <= n <= 100` * `1 <= Node.val, voyage[i] <= n` * All the values in the tree are **unique**. * All the values in `voyage` are **unique**.
null
Array,Depth-First Search,Breadth-First Search,Matrix
Medium
null
1,614
all right so let's talk about the maximum depth of parenthesis so basically you just have to pump the number of opening and closing and you just basically just keep track of the maximum opening and if you see a closing you have the decrement right away so you will get the number of the next uh message of the expect so i'm just going to call it and you'll just follow along five and i also have a map for my uh i mean for my record and you can actually save it to zero or you can say go to integer email it doesn't matter like it depends on how you actually do it and i'm going to traverse the entire race up to chart right so i'm going to say c go to opening i'll just increment my counter and you see that here closing i'll get to my concrete and every once in the photo i have to make sure my maximum is the maximum in this current spot then as after while return max and this will be a little solution all right so i have a typo so this is apple and image file again all right submit and here we go so let's talk about time and space complexity this is fine often travels every single character in the string and this is space is constant so this will be the solution and i will see you next time
Maximum Nesting Depth of the Parentheses
maximum-nesting-depth-of-the-parentheses
A string is a **valid parentheses string** (denoted **VPS**) if it meets one of the following: * It is an empty string `" "`, or a single character not equal to `"( "` or `") "`, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are **VPS**'s, or * It can be written as `(A)`, where `A` is a **VPS**. We can similarly define the **nesting depth** `depth(S)` of any VPS `S` as follows: * `depth( " ") = 0` * `depth(C) = 0`, where `C` is a string with a single character not equal to `"( "` or `") "`. * `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are **VPS**'s. * `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a **VPS**. For example, `" "`, `"()() "`, and `"()(()()) "` are **VPS**'s (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not **VPS**'s. Given a **VPS** represented as string `s`, return _the **nesting depth** of_ `s`. **Example 1:** **Input:** s = "(1+(2\*3)+((8)/4))+1 " **Output:** 3 **Explanation:** Digit 8 is inside of 3 nested parentheses in the string. **Example 2:** **Input:** s = "(1)+((2))+(((3))) " **Output:** 3 **Constraints:** * `1 <= s.length <= 100` * `s` consists of digits `0-9` and characters `'+'`, `'-'`, `'*'`, `'/'`, `'('`, and `')'`. * It is guaranteed that parentheses expression `s` is a **VPS**.
null
null
Easy
null
1,287
hello hi guys good morning welcome back to the new video subi I hope that you guys are doing good this video Problem elements appearing more than 25% in sorted array now sorry for than 25% in sorted array now sorry for than 25% in sorted array now sorry for being late um like while I was making notes for you uh I could not write properly because like I got into an accident yesterday so my right hand is not working properly I have to hold it and then write so yeah uh let's start the problem itself um it just says and yeah that's reason I cannot also type fast not sure like these two fingers are not working so I'm typing with just three fingers cool um it just says that we are given and the problem itself is in the title itself elements appearing more than 25% in the sorted array right now than 25% in the sorted array right now than 25% in the sorted array right now it says that I am given an element array integer array sorted in non decreasing order which means I have a sorted array that is again see everything in a problem can be used in future so please remember that I have a sorted array and it is in the non decreasing order that is the order which I have given there is exactly one element one integer in the ARR that occurs more than 25% of time ARR that occurs more than 25% of time ARR that occurs more than 25% of time again it says there's exactly one integer which occurs more than I'm not saying more than equal to I'm saying more than 25% of time if I say that I more than 25% of time if I say that I more than 25% of time if I say that I have n elements in my integer array that element should occur more than n by 24 so let's say my target is n by 4 so my frequency should be more than the Target now okay when I say frequency should be more than this target it is simply I'm reading the question down return that integer okay I have to just return that integer same example only one example is more than sufficient to handle these kind of problems again we will go on to all the approaches to solve this so uh first very basic thing we wanted the frequency to know the frequency of every element in standard we use the hash map right hash map or unordered map so we can just simply do one thing we can iterate on all the N elements of my entire array and when I'm iterating on all the nend elements I can keep track of the frequency of every element then I would know if the frequency exceeds n by4 then that element is my special element I can return that integer itself so it is the same thing I have this AR I will have a hashmap I know my count should be more than n by4 is my target which is what I aim for so I can just simply use a hashmap to know it frequency as simple as that you can just have a hash map of counts or frequency whatsoever you want you will just iterate on all of your elements and will keep on increasing your count of frequency and here see there's another modification which you can do you can hear itself check as soon as the count exceeds your n by4 you can just simply return the nums from here itself or else what you can do is you can just simply again iterate on the entire map and see if any of the values is more than count simply return that specif specific key which is the element itself because map con contains key and value key is the element value is a frequency so by this you can ultimately get your ke and else you can simply return a minus one in the end if that is not possible so you saw that you simply on the entire array but you use an unordered map to keep the frequency so the space is O of n also and time is O of n so is it good now the interval will ask you a followup which is what can you improve now you just heard one thing in the beginning I said specifically Mark everything which is given to you were given that the array is sorted again you have these two stuff right now I ask you just optimize one thing you cannot optimize time without optimizing space it is like it is kind of not directly possible to optimize time when both are same it is not directly possible to optimize time without optimizing space so firstly it's obvious that if I want if the interv asking me to optimize I have to think of optimizing space first which means I have to get rid of this unordered map which I was using so why was that again why was that unordered map used unordered map was just to know the frequency of that specific element again I know that the array was sorted now when you hear the word sorted the first thing which comes in your mind is binary search but then you can just again go into a deep hole that how to even apply a binary search but again my main task is not to apply a binary search my main task was to get rid of my unordered map yeah so what I can do is I know okay I have to get rid of my un map so indirectly I should be able to know the frequency of that element as soon as possible so one thing what I could do is that I know the elements are sorted which means Elements which are same will be together and my only condition I don't know to I don't want to know all the frequency of element I just want you to know if the frequency of that specific element if it is more than my target here the N was 9 so my target was n by4 which is 9 by4 it is sorry for bad writing uh it so it is two so now my main aim is that my target should be more than two that's my main Aim so if I'm at this element can't I just simply go and check for my target like I can just simply go and check for my if I am at the I index I'll go and check for i+ at the I index I'll go and check for i+ at the I index I'll go and check for i+ Target because that will indicate I will include three elements which is more than my target as simple as that and if it is same with that of this element which means and if it is same which means a and a these two are element same for sure in between all the elements will also be same why because it was sorted so that is how again that was not how we thought of okay we will we can apply binary search our main purpose was just to get a rid of our unordered map which was using space and that unordered map was used just to know the frequency now we figured out that we don't need to actually know the frequency we just need to know if I have sufficient number of elements of the same type of the same like number and that is for what we can just go and jump on to the i+ Target index go and jump on to the i+ Target index go and jump on to the i+ Target index and check if that has the same value which means okay I'm very good with it so what I'll do is I am at this index I'll check for I plus Target index if it is same no it is not same which means I don't have these Target + one I don't have these Target + one I don't have these Target + one consecutive elements okay cool no worries if you are at one check for this it is again not same which means I again don't have 2 to2 as the three count as elements I again go and check here okay that is not still there go and check here yeah it is same which means I have Target plus one consecutive elements so if I am at the I index I'll simply go and check for i+ Target and with that I and check for i+ Target and with that I and check for i+ Target and with that I would know I have Target + one same would know I have Target + one same would know I have Target + one same frequency elements so again simply I know my target is a size by 4 I'll simply go on inter my entire array and again I'll go and check if a of I is equal to a of I plus Target if that is the case then I will have Target + one the case then I will have Target + one the case then I will have Target + one consecutive elements and then simply return your AR of I ultimately simply turn minus one so with this you saw that you still are using an entire AR but still now you are using a space of one now again the interviewer can ask you optimize it again now in this if you had not known the problem it will be very hard for you to even think of how you can optimize it because the next thing which I'm going to show you is not directly intuitive and in an interview where you have not seen this problem or not seen the optimizations it will be very hard for you to come up with it in that given time frame although if I gave you like if I give you let's say 1 hour you can still come up with it but in the given time frame you should be knowing how to solve it so that is how again we will see that how we can optimize it again we saw one thing that the only thing which was given to us was binary search in the last method we did not use binary search right we thought of optimizing it but we did not use the actual functionality of binary search how about if you can use that binary search but then comes is the question comes is how to even apply binary search I want Count frequency and all that stuff but if you are saying byya if I want to apply search so the only thing which I can think of is I will go onto an element and for that element I will go and check what is the last location so assum the frequency but for that I'll say bro you will take o of n log and time and I have already solved this in O of n so why are you increasing time itself so that binary SE which you are thinking right now is not good let's think of something else now rather than going on to all the elements is it possible that for any specific given I just go on to any specific given index and with that index I'll just do a binary search for that specific index of the value and I can get the left most in the rightmost index for that specific value and from that I can know it count butya the same thing you showed previously also you went on to one index you went on and check for the left most and the rightmost to know the count because left most and rightmost you can just simply do by binary search left most Index right rightmost index you can simply get to know by binary search but ba uh did will it still not be o of n log n no bro why because when I say I will do it for this index I mean I will choose some specific indexes by but you will have to go to Every index how will you choose some specific index and will only go to that specific index and do a binary search to know the actual range which means left and right how will you do that byya so that is how the concept which was given n by 4 will come in picture I said everything in the given problem is useful this n by4 it indicates a lot of stuff let's see firstly when because in the interview you might not get clicked but yeah again I just showed you everything it is being used n by4 also has a significance in this problem to optimize it how let's see in this question I have my n was n my again my target will be two my count will be three so I need three same elements so if I just go on from the very beginning I can make a box of three from the very beginning and I can just say for sure if I want these three elements to be same so if I'm imagining okay it will be X XX as in okay these are same elements so for sure if I can just only check this element at index 2 I'm very good with it I don't have to go and check for this and this also right because I'm imagining my first box will contain but byya uh what if it is a next box yeah if it is a next box still if I can go and check this value at an index two still it will consider this box yeah true what if it is this box yeah still it will consider this value now I say okay by that is done for this box it is done for next box again I can go and check for one value this will help me this again this one value it should not be this extreme value it can be also but because in this case it can be because you will see that you can still go and check if you just go and check for six because you just want to choose one element which can take all the possible boxes you have to choose just one element so that you can take all the boxes again I'm just telling you by dry next I'll show you the formula also for the same that how actually mathematically we can drive it so okay we would need this one element mid it can just solve it out and for sure for the end portion I can just take as the element six and that can also sorted out so with this given example I can see that I can have index 2 index 4 and index 6 I can only check for these three indexes because these three indexes will cover all the possible boxes of size three and that is more than sufficient for me to check that okay I have three elements or not so it will be 3 into login for this N 9 still we have not figured out that it is possible or not but yeah still it is n 9 let's try for the other values of8 what if n equal to 8 then still I will have this box again I can go and check for this value 2 4 and six again same what if it is Nal 10 then again can I make this box which is this box then again by the above formula which you showed I'll go and check for two four and six will you do this but ba now the issue will come how what if I have these elements are same and none of the elements are like have a count of three so you did not check this yeah bro you are true so rather checking for six in this case I will check for seven so ultimately you saw one thing I checked from the left which is I'll check from the left count of three okay I'll check from the left count of three I'll check I'll go and check for this is the index which is n by4 right I go and check for this value which should be in this last box okay that is true and I can go and check for the mid now B in mid which one will you check bro if I go check this I will consider this box also and this box also so that's good still it's just that you should remember that okay I'm going and checking for the last box and when I say last box I mean the last box because the box has a count of three so I'm going and checking for the last box which is this last box first box which is this box and the middle box now this box stuff okay I'll check for this Index this index and this index again you can also go and check for index 4 also uh that is option like either index five or four both will work it is just the middle index now comes that how you actually it is just for the intuition like dry basis how you are actually going and trying to just minimize the number of checks you want here comes mathematical intuition how you know that I need to have n by4 elements I need to have n by2 elements all right so and when I say like N by4 I actually just mean that if I have a size array of size n I can just bifurcate that to n by4 n by2 sorry n by4 that will sum up to n by2 + n by2 which will sum up to n by2 + n by2 which will sum up to n by2 + n by2 which will sum up to n right so it is just kind of again it is a logical intuition which you can derive out of the above thing which you wanted again as also mentioned it is highly unlikely if you have not solved this question or if you have not solved this particular uh followup it is highly unlikely that you can be able to get this in a interview time like interview time limit now we know that okay uh we just need to consider these n when I say N by4 I actually mean uh the count which is three and ultimately it will just overlap this portion will overlap if I just go and check for the seal values but no matter what we can just still go and check for the most values which is in the end and that will give me my answer so I can go with this above and again that is simply by dry running multiple values I DY for nine 8 10 and you can try for more values let's say 12 and stuff so here you saw I tried for 12 also that if it is working or not cool so here we saw that we will can bifurcate that and we can just take okay I'll take the mid element from the mid like n by Two element I can take the mid uh I can take uh 3 n by4 from the end and I can take n by4 from the start with this I'll take three elements which will for sure overlap with the count of t Target + one and again uh just for of t Target + one and again uh just for of t Target + one and again uh just for this n = 12 I know my count is 14 uh 12x this n = 12 I know my count is 14 uh 12x this n = 12 I know my count is 14 uh 12x 4 is actually three so my target needs to be four as in sorry my target is three my count needs to be four which means I need to have a group of a size four so I can just make it will be n by4 this index again for last although you can just say simply drive it from here but it should follow for every n values here it is directly well but no ways it can be a 13 14 and 15 with that itself we just figured out that again that value this value what value to check which is in this case was 3 n by 4 what value to check we could a we could only be able to derive by looking at the examples and try running the examples itself and again for the mid you can just simply go and check for a of N by2 and that is how you can just simply go and check for these three values which will cover all blocks of size four you will see it will cover this if I am at this index it will cover this block that is done this block so this these three will cover all blocks of size n by 4 + 1 that is or blocks of size n by 4 + 1 that is or blocks of size n by 4 + 1 that is or like I should say n by 4 + 1 yeah so like I should say n by 4 + 1 yeah so like I should say n by 4 + 1 yeah so that is how you can be easily able to derive that you can just need these three blocks to cover everything whatever you want now again the candidates whatsoever you have right now are n by4 by 2 and 3 n by4 and you will just go and try to check the for these candidates okay this is the candidate now just go and check for the leftmost index of this candidate and the rightmost index of this candidate which will give the count for this specific candidate and that will give me that for sure I have the count and if this count because I'll go and check for the left index for that specific candidate I'll go and check for the right index again upper bound gives a one plus upper bound gives one plus so do a minus one so you know the left you know the right just simply do a right minus left + one just to know the right minus left + one just to know the right minus left + one just to know the length if it is more than the target which was actually n by4 in your case so if it is simply more than Target simply return the candidate again this formula worked only because I have a limit of n by4 this will change depending upon whatsoever other limit you are given that is a reason I told you it's specific to this example and we are trying to utilize the problem obviously the hints which are kind of given obviously the points which are given in the problem itself I hope and for sure with this it will be three to log in because you only Ching for three candidates and that will be overlog in itself and time is and space is also over fun because you are not using any extra space I hope that you guys got it again bye-bye like casually someone like
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
1,646
The Freedom Fighters And Doing Surveillance Get Maximum Pin Generate A Problem Seizures To The West What Is Now Statement Is This Government And Are Not Sufficient And Placid In The Language Of The Giver And * * * Whatever Happens Here Will And * * * Whatever Happens Here Will And * * * Whatever Happens Here Will Always What do we say here and here forever that we have to do computer plus one and for that, subscribe us, so come here, subscribe to us, do quilling, first want the sad old man, click and go to * Vansh to number one number Panchgavya to * Vansh to number one number Panchgavya to * Vansh to number one number Panchgavya Ghee is clicked, our 137 president here will go one and plus one two and that our I am folded, let's see you in a good way. Don't forget to subscribe and subscribe, we have made here subscribe and all these idlis are the biggest. If we have to do it then we subscribe to it by the subscribe function 2014 - Prem only exam punctures are made by 2014 - Prem only exam punctures are made by 2014 - Prem only exam punctures are made by rice, whoever we start with zero and end with will be our exam and what do we have to return that if we have clicked on next then come in this function Solve ₹ 10 then come in this function Solve ₹ 10 then come in this function Solve ₹ 10 What is our interesting point in this and in this is our It's kind of in point Okay so what is our breast cancer when our starting increases in these So here Singh has to click on the secretary and go after putting the plates otherwise if your Starting only if Eastern is equal to one then the account statement giver is what will happen for 041 if our behavior will not happen then it means what do we have to do in Chief Tasty, we have to keep Simply Tasty otherwise what to do, you have to do some tips that our here we have I told you that all these will be even and I will give you this number Sunil, you will have to check what is our number, what is our current starting point, if it is my even then we will simply come and taste, what will we do with our vector. Off are doing strike 232 because see here you are to *i hai to because see here you are to *i hai to because see here you are to *i hai to mean appoint multiple now I have I what you have to do is simply also off tasty mein humko kya rakhana aur hi off festival by two plus twitter steve bittu [ __ ] Why one because we have bittu [ __ ] Why one because we have bittu [ __ ] Why one because we have defined that we will get subscribe okay and here we get subscribe can be ours this can happen so here we subscribe and subscribe then this is the correct answer let's submit it tomorrow morning okay so Guys, there is no big problem in this, the only problem in this category is that whenever your values ​​come, that whenever your values ​​come, that whenever your values ​​come, you have to calculate I and whenever you believe in God, I and I are plus one way computer. Karna hai Sonam thank you for watching my video thanks for this
Get Maximum in Generated Array
kth-missing-positive-number
You are given an integer `n`. A **0-indexed** integer array `nums` of length `n + 1` is generated in the following way: * `nums[0] = 0` * `nums[1] = 1` * `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n` * `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n` Return _the **maximum** integer in the array_ `nums`​​​. **Example 1:** **Input:** n = 7 **Output:** 3 **Explanation:** According to the given rules: nums\[0\] = 0 nums\[1\] = 1 nums\[(1 \* 2) = 2\] = nums\[1\] = 1 nums\[(1 \* 2) + 1 = 3\] = nums\[1\] + nums\[2\] = 1 + 1 = 2 nums\[(2 \* 2) = 4\] = nums\[2\] = 1 nums\[(2 \* 2) + 1 = 5\] = nums\[2\] + nums\[3\] = 1 + 2 = 3 nums\[(3 \* 2) = 6\] = nums\[3\] = 2 nums\[(3 \* 2) + 1 = 7\] = nums\[3\] + nums\[4\] = 2 + 1 = 3 Hence, nums = \[0,1,1,2,1,3,2,3\], and the maximum is max(0,1,1,2,1,3,2,3) = 3. **Example 2:** **Input:** n = 2 **Output:** 1 **Explanation:** According to the given rules, nums = \[0,1,1\]. The maximum is max(0,1,1) = 1. **Example 3:** **Input:** n = 3 **Output:** 2 **Explanation:** According to the given rules, nums = \[0,1,1,2\]. The maximum is max(0,1,1,2) = 2. **Constraints:** * `0 <= n <= 100`
Keep track of how many positive numbers are missing as you scan the array.
Array,Binary Search
Easy
2305
430
hello guys my name is lazaro and today we'll be doing a leak code problem this problem is called flatten a multi-level doubly linked list multi-level doubly linked list multi-level doubly linked list you're given a doubly linked list which contains nodes that have next pointer a previous pointer and an additional child pointer this child pointer may or may not point to a separate w linked list also containing those special nodes these child lists may have one or more children of their own and so on to produce a multi-level data structure as produce a multi-level data structure as produce a multi-level data structure as shown in the example below so here we go this is what i mean by multi-level multi-level multi-level uh this node three has a child that points to seven and then inside this list starting at seven node eight also has a child that is just eleven and twelve so you can think of this as three separate lists uh and that's what i mean by multi-level and that's what i mean by multi-level and that's what i mean by multi-level so given the head of the first level of the list flatten the list so that all the notes appear on a single level doubly linked list all right so we know where we want to return you we just want to return one list uh that is all in one level let curve be a node with a child list okay so curve for example can be three because it does have a child list the nodes in the child list should appear after cur all right so 7 8 9 and 10 should appear after 3 and before curved on next in the flattened list all right and then 10 should appear right before four return the head of the flattened list the nodes in the list must have other child pointers set to no this is the first example i'm actually write it out or write down a example similar to it in the notebook this might be pretty big so let's see if we can make it exactly as the sixth first example okay so here's the list uh we have the multi-level data structure where the multi-level data structure where the multi-level data structure where three has a child point to seven and eight oz the child so what do they want us to do well first we need to recognize other nodes that do have children in this case it's just three and eight and we want to do is take the children list and put it right between the node that has a child and the node that has a child dot next so if we were to transform this on the first go we would have 1.2.3 1.2.3 1.2.3 three points to seven points to eight and we want to take this list and put it right in between eight and nine so eight is going to point to eleven then eleven is going to point to 12 then 12 to 9 and then 9 to 10. then going back here same as before 4 5 and then 6. now we notice how three still has a child list so we want to do pretty much the exact same thing take this whole list right here and put it right in between three and four aka as i had in the problem where this is occur and this is kerr curd.next curd.next curd.next they said to put the list between cur and curd.next now i don't really have space on canvas and i feel like it'll be kind of repetitive but you understand that how it would look it would be one two three seven eight eleven twelve nine ten four five and six all in one list and then we would change this pointer to point to no so how do we want to do this well the first thing that we want to realize should probably raise can't go back anymore is that once we reach a node that has a child we want to separately keep hold of its next nodes so once we get to three we realize three has children so let's keep a hold of this four five and six somewhere let's just place it on the side in fact i am going to do that see if i can make this work perfect so let's keep this four five and six on hold for now and let's change the no the child node the child pointer of three let's make it look to something as none so let's change this make it look to none and let's make the next of three be its children so this is just so far some really small rearrangement so what we're going to be doing is pretty much bringing it right there and we're going to be setting this child pointer to no or none and then let's continue iterating through this so now we have seven then we have eight and now eight also has a child so first let me just erase this now eight also has children oh a child pointer that's not none and it contains 11 and 12. so just how we did for three let's hold the next nodes of eight whoops let's hold the next child nodes that sorry the next nodes of eight put it right here for example let's move his children list to be its next nodes and let's also set the child pointer to none so far this is looking pretty good we have 1 2 3 7 8 11 12 but once we get to 12 what do we do well this 12 is pointing to none so should we stop here well we really shouldn't stop the reason we don't want to stop is because we have nodes that we were holding on to and we eventually have to bring them back just gonna give myself some more room here and we eventually have to bring them back so while we are if the next pointer does not point at anything and we have we're holding on to nodes let's bring those nodes back so we something like we have something like that right there let's continue iterating now where we went from 12 now we're at 9 and then now we're on 10 and 10 is pointing to nothing but like i said since we're we have nodes on hold the 4 5 and 6 let's bring it and change it so and put it in front of the 10. so here we have this right here we can bring the 4 5 and 6 and put it right in front of the 10. and then we can continue iterating we get from we go from 10 then we go to 4 then we go to 5 and then we go to 6 and then since 6 is pointing on none we check if we're holding to any head if we're holding any more nodes but since we're not holding on to any more nodes we know that we don't have to add anything and we can successfully finish and if you we were to look at the list now we have one two three seven eight eleven twelve nine ten four five six and then here is one two three seven eight eleven twelve nine ten four five six and the exact same order so that's really the main idea of this problem let's hold on to the to curve dot next right and we can hold it in a data structure called a stack and then remove the child pointer make it point to none and change the next pointer to look at that child list and we only do this for nodes that do have child lists so now that we talked about it let's actually program it and see if it will work so let's just create a temporary variable or the root i like to call it the root set that equal to head and let's call let's create our stack initially empty now let's iterate overhead and if the current node which is head if that has a child and if it has next nodes so if he has a child and the next pointer is looking at some nodes the reason we want this if is because the last node right here the 6 could have a child but it could not have any next nodes if it both has a child and next nodes then we want to append to our stack those next nodes now we want to overwrite the next nodes and set it equal to the child lists then make head dot next dot previous equal to head because remember we also have to update the previous pointers this is something i forgot to mention uh in my drawing i was doing a singly linked list but we must remember this is doubly linked list but it's really not that big of a difference all that we want to do is we make the child list in front of cur then make sure that the first node in the child list is pointing back at the current so change is seven you see how its previous is none right make that previous 0.23 because we're make that previous 0.23 because we're make that previous 0.23 because we're going to put the 7 8 9 and 10 uh in front of the three and then of course like how we did mention let's change the child pointer and set the equal to none check if not had done next so we're at the end of our list so if we're at the end of the list and we're holding nodes aka our stack is not empty then what we want to do is new underscore node is equal to stack dot pop and then add those new nodes so head down next is equal to new node and head dot next dot previous let's also update that previous pointer and make it equal to head then we are just going to normally iterate through the linked list by setting head equal to head dot next and then outside of that we're done with it all this logic and now we can use return root so that works and now let's submit and it works perfect so hopefully you guys are able to understand this problem now uh it's a bit of a big problem to kind of tackle on because there's a lot going on there's a lot of pointers that needs to be updated but realistically the main idea of it is that we want to store the next nodes for nodes that do have a child list then once we're we no longer have a head dot next or a next node and our stack is not empty then let's pop our stack and add those nodes back in now this is going to be uh time complexity and space complexity are both going to be big o of n our stack might be the same size as the amount of nodes if every single node has a child for example and we're usually iterating through all the single all the nodes just once and that's where the big o of n for time complexity comes from so other than that hopefully you guys enjoyed the video if you did please leave a like and consider subscribing and thank you for watching
Flatten a Multilevel Doubly Linked List
flatten-a-multilevel-doubly-linked-list
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional **child pointer**. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a **multilevel data structure** as shown in the example below. Given the `head` of the first level of the list, **flatten** the list so that all the nodes appear in a single-level, doubly linked list. Let `curr` be a node with a child list. The nodes in the child list should appear **after** `curr` and **before** `curr.next` in the flattened list. Return _the_ `head` _of the flattened list. The nodes in the list must have **all** of their child pointers set to_ `null`. **Example 1:** **Input:** head = \[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\] **Output:** \[1,2,3,7,8,11,12,9,10,4,5,6\] **Explanation:** The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: **Example 2:** **Input:** head = \[1,2,null,3\] **Output:** \[1,3,2\] **Explanation:** The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: **Example 3:** **Input:** head = \[\] **Output:** \[\] **Explanation:** There could be empty list in the input. **Constraints:** * The number of Nodes will not exceed `1000`. * `1 <= Node.val <= 105` **How the multilevel linked list is represented in test cases:** We use the multilevel linked list from **Example 1** above: 1---2---3---4---5---6--NULL | 7---8---9---10--NULL | 11--12--NULL The serialization of each level is as follows: \[1,2,3,4,5,6,null\] \[7,8,9,10,null\] \[11,12,null\] To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes: \[1, 2, 3, 4, 5, 6, null\] | \[null, null, 7, 8, 9, 10, null\] | \[ null, 11, 12, null\] Merging the serialization of each level and removing trailing nulls we obtain: \[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
null
null
Medium
null
519
and what's up guys so let's solve this 590 190 uh one line random flip matrix so your agreed matrix with all values set to zero and uh there are you need to there are three functions right one is uh initialize and the one is uh randomly pick a flip indices so you pick up i say where originally matrix is zero and flipped it to one right so this is this uh original trivial right because suppose i just maintain a matrix with i just build a matrixes in this uh do the matrix and i just generally choose holder zero and the changes to one and then there are reset okay so for example one zero two zero to zero and uh in this case let's say zero one two right so maybe in flip it choose one zero because in this case so this guy choose to be one and the next time you call uh you could flip you can only choose these two right you can only choose uh like the uh you can only choose like the two zero right and then you choose to zero okay so finally when the third time you call flip you can only choose zero and then every time you can reset okay reset become different uh reset and then you call flip to zero okay so let me just explain uh the knife idea so the first naive idea is that uh when you first create a set you can create a matrix right you can create uh you can and you go through it and set the set to be take each set uh you create a set will collect all the indices so the number in the sets mean the two-pointer set means that uh two-pointer set means that uh two-pointer set means that uh yeah it's not used it's zero okay so every time you flip you just randomly choose a number in a two-point set and choose a number in a two-point set and choose a number in a two-point set and then remove that number in a set and return it right so every time you flip you just randomly choose something in the set and uh whenever you reset you just reset all the sets okay the problem is that the in this case if you keep resetting that the url takes m times n steps to create a set right so this problem is this is tle but uh can solve a almost every case but uh probably too large okay so this is the knife approach okay but we can try to do another idea is that we create sets but with empathy so this is just the another idea that uh you're not recording what you're not recording that what you have not used but uh creating what you have used okay so this is just philosophy change so in this case when you reset the trivial right you just reset so this is constant time right because you don't do anything and when you flip you choose okay so this is the another idea that this is the 2d array right but the idea is that you can flatten into one d array right suppose this is n and n okay and then let's say sou then let's say zero this is mn minus one sorry and then uh yeah m minus one let's see okay and then you so you can choose any number in up to m minus one but uh do the division right so you can just for the first column you just division with n right now you get this right so this is the division and this is the module the mod with n will give you this so this is x and y okay the idea is that you just randomly choose this from this number and uh if it's not in a use uh y is in seven you then continue because you have already used so you need to do it again right if you find something which you don't have to uh which is you have not used you can add it into use and the return accordingly right so this approach uh the difference with these two approaches that in this approach uh when you keep calling reset the reset will takes the one time right uh but it's very actually i think it's very difficult to analyze the complexity because imagine there are one situations that you never call reset then this code will be very efficient right because each time you already remember everything but if you call reset a lot then this code will be more efficient so depends on but it doesn't tell you that uh what is the percentage of library reset so it's not very easy to analyze complexity the only thing i know is that this code works but it's called not okay let's see you guys next videos
Random Flip Matrix
widest-pair-of-indices-with-equal-range-sum
There is an `m x n` binary grid `matrix` with all the values set `0` initially. Design an algorithm to randomly pick an index `(i, j)` where `matrix[i][j] == 0` and flips it to `1`. All the indices `(i, j)` where `matrix[i][j] == 0` should be equally likely to be returned. Optimize your algorithm to minimize the number of calls made to the **built-in** random function of your language and optimize the time and space complexity. Implement the `Solution` class: * `Solution(int m, int n)` Initializes the object with the size of the binary matrix `m` and `n`. * `int[] flip()` Returns a random index `[i, j]` of the matrix where `matrix[i][j] == 0` and flips it to `1`. * `void reset()` Resets all the values of the matrix to be `0`. **Example 1:** **Input** \[ "Solution ", "flip ", "flip ", "flip ", "reset ", "flip "\] \[\[3, 1\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, \[1, 0\], \[2, 0\], \[0, 0\], null, \[2, 0\]\] **Explanation** Solution solution = new Solution(3, 1); solution.flip(); // return \[1, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned. solution.flip(); // return \[2, 0\], Since \[1,0\] was returned, \[2,0\] and \[0,0\] solution.flip(); // return \[0, 0\], Based on the previously returned indices, only \[0,0\] can be returned. solution.reset(); // All the values are reset to 0 and can be returned. solution.flip(); // return \[2, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned. **Constraints:** * `1 <= m, n <= 104` * There will be at least one free cell for each call to `flip`. * At most `1000` calls will be made to `flip` and `reset`.
Keep prefix sums of both arrays. Can the difference between the prefix sums at an index help us? What happens if the difference between the two prefix sums at an index a is x, and x again at a different index b? This means that the sum of nums1 from index a + 1 to index b is equal to the sum of nums2 from index a + 1 to index b.
Array,Hash Table,Prefix Sum
Medium
null
1,309
hello viewers welcome back to my channel I'm back with another problem from leadcore decrypting a string from alphabet to integer mapping so we are given a string s formed by 8 digits 0 to 9 and hash symbol we want to map s to English lowercase characters as follows basically characters a to I are represented by numbers 1 to 9 respectively character j2z are represented by 10 hash to 26 hash respectively right so return the string form after mating it's guaranteed that a unique mapping will always exist for example s is given as 10 hash 11 hash 12 right that is the input string the output should be J K a B so that's what it is you might be wondering 10 hash 11 hash 12 XO j k l thus what you might be wondering bar as per the definition right from j 2z they should be ending with a hash symbol so 10 into the hash symbol that is j xi ending with a hash symbol that is k but 12 is not ending with a hash symbol that means there is another mapping that we need to look back that is one treated need to be treated individually and to also need to be taken individually so one what is 4 1 is a right likewise 2 is B if it was like 12 hash symbol right then obviously the output would be JK and but in this case since hash symbol is not there at the end of 12 right its JK a B right so for example here in the second example 1 3 2 6 hash right so 1 3 so 13 but 13 is not ending with a hash symbol right so 1 &amp; 3 should be taken symbol right so 1 &amp; 3 should be taken symbol right so 1 &amp; 3 should be taken individually so 2 6 and a hash right - 6 individually so 2 6 and a hash right - 6 individually so 2 6 and a hash right - 6 should not be taken individually so Dave since it is handing with hash symbol the two preceding characters should be combined with a heart symbol that means 26 hash is Z 1 is a 3c and 26 else is Z so wherever there is a hash symbol you need to look to previous symbols to come up with a right character so that's the catch here that's it so let's go to the last example the number 4 right so that this is a pretty large string which has almost all the lowercase letters right so this is how it is this is a good example to look at actually so 10 hash 11 hash 12 hash all this right so wherever hash is there you need to look to create the previous symbols so that's how it is so the logic for this program is very simple so for when you have a hash symbol in the third place right that means you need to read first and second letters are the characters together right so here in the third place there is a symbol that is hash symbol that means you need to read 1 0 2 there and after we process this right again from here third place 1 2 3 right third place there is a heart symbol so you need to read this together so that's the basic logic so let's go look at the code how we are going to do this right so since we are going to return string let's form let's declare a string builder with variable here and we are going to start with the index I is equal to zero so while I the index is less than the strings length s is the given input strain so what we are going to check is if the I plus two is hash so basically let's go right one two to six a let's say this right yes so this is 0 this is 1 2 3 4 5 this is just the indexes right this is a string right so now I is at 0th position what we are checking is I plus 2 is e is equal to hash or not yes I plus 2 is I is 0 plus 2 is 2 so in this case plus 2 this is fact yes of course this we need to check because if it is already at the let greater than this length right and then we won't be able to check s plus s fi plus 2 because it will fail right if this is if this condition satisfies that means we have to read these two characters together so that's what we are reading so just convert this SFI plus when it is string and convert that to a character so 12 hash right so this whole thing is 1 so what is 12 as per the definition 10 is j xi is K to always L so we need to convert this 12 hash to L right and 26 hash is Z so that's what we need to convert to all right but how do we convert this 12 H to L is the question so we are going to take hell of the ASCII table ASCII character table ASCII right so small a the lowercase a this value is 97 in s so ASCII our ASCII of a is 97 that's harder so we are going to use this data point in our code but as per the given directions right a should be going as one right so one should be treated as a so what we are going to do is in order to get 97 right we need to add 1 to 96 right so 96 plus 1 right so this one if we see anywhere in our string right that means it is a so we are going to take the base number as 96 and add all the numbers that we encounter in this string so for that case we are saying 96 plus whatever the string that we obtained here so that is 12 right so 96 plus 12 we have to convert that to a character that character will be appended to SP so in this case what we are appending is else in our example in this case 1 2 right we are appending L and we need to increment I by 3 places because we have read as of 0s of 1 and s er - so we are read as of 0s of 1 and s er - so we are read as of 0s of 1 and s er - so we are here SF take know so 26 that we are we have to read right so we'll go back I is at number 3 plus 2 is 5 you too still and so essa five plus two is equal to hash yes it is hash and then Italy what we are going to do this twenty six two six these two letters and 96 plus twenty six that we will get converted into Z this time so our output is C let's say we will take a similar example right one to two six hash right let's say this is our string this time and the indices are zero one two three four right we are going to go through the same thing same chord right anyway this ASCII information we are going to use in the same similar manner so now so we are at zero and I is less than a start length yes I plus 2 is less than a certainly yes s fi plus two is hash but s fi plus two is not harsh right in that case what we are going to do is we are going to read one single letter one single character so that is just one so that one we are going to add it to 96 plus 1 is 97 if you convert that to cat it will be a 97 is a that's what we learned ask you of a is 97 right we'll just reverse engineer that 97 is a converting it to your cat right and then we increment I by just to one space one place so I is at 1 so that is 2 so 2 plus 2 is still less than length but 2 plus 2 that is 4 so we are at I is equal to 1 plus 2 is 3 so but trees at trees index right the characteristics is there which is not equal to hash so now we will go to else part again we are going to take one single character that is just this - what is - we are going to add to this - what is - we are going to add to this - what is - we are going to add to 96 plus 2 is 90 a 98 is be right asked here 98 is B and we are going to increment I by 1 I is now at 2 so 2 plus 2 is still less than s Jordan but this time yes the 5 plus 2 is equal to hash yes we are at I is equal to 2 right plus 2 is 4 this is hash in that case what we are going to do is we're going to take two characters this time 2 and 6 right so 96 plus 26 which is Z that's what we are going to return so a bzees the answer for this right so the time complexity for this is time is equal to order of length of s right so if you say length of s is let us say n right sir it'll be order of n time complexity but space complexity right space complexity so since we are converting the string which is in the integer and hash format we will be able to only approximate it right will be only able to approximate the space so it will be anywhere ranging from n2 sorry and by 3 2 so if n is the length right and in the strings length the space which is required to return the answer will be anywhere ranging from n by 3 to M so we can just go through one example here right so 1 2 hash to 3 right so here the length is 6 right but the output just for simplicity let's say 26 right yeah so 12 hash is what all right 12 hash is L and 26 hash is Z so the length that we are returning is 2 right so where n is 6 the output is and just two characters that is n by 3 right that is six carry a six by two right which is equal to 6 by 3 right so that's the reason why this is the minimum that we need for the space right let's say if this is the thing if that is the pain right which doesn't have any hash symbols that means all of them are falling onto the a2i a 2 i right all of them are 400 to 1 to 9 right so that means we need the end space right here the space required is the length is 5 so in the answer also what we need to do is a b and a right so this is of also equal to so what we will say is the space is order of n by 3/2 and so since space is order of n by 3/2 and so since space is order of n by 3/2 and so since we in general the Big O notation we don't really need take the constants or anything right so overall we will say order and
Decrypt String from Alphabet to Integer Mapping
sort-items-by-groups-respecting-dependencies
You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows: * Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively. * Characters (`'j'` to `'z'`) are represented by (`'10#'` to `'26#'`) respectively. Return _the string formed after mapping_. The test cases are generated so that a unique mapping will always exist. **Example 1:** **Input:** s = "10#11#12 " **Output:** "jkab " **Explanation:** "j " -> "10# " , "k " -> "11# " , "a " -> "1 " , "b " -> "2 ". **Example 2:** **Input:** s = "1326# " **Output:** "acz " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of digits and the `'#'` letter. * `s` will be a valid string such that mapping is always possible.
Think of it as a graph problem. We need to find a topological order on the dependency graph. Build two graphs, one for the groups and another for the items.
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Hard
null
1,915
hey what's up guys this is chung here again so this time uh lead called number uh 1915 number of wonderful substrings okay so a wonderful string is a string where at most one letter appears an odd number of times okay so this one is another like problem that's you need to uh work with the parity right apparently of the occurrence of some letters and this one is like uh it's there's a little different uh constraints here so for example we have this string here and this one and they are wonderful because in this string so c uh num a letter c uh has an odd uh number of times right appears r number of times and j appears even number of times so which is fine and this one a b is also fine because in this one both a and b appears basically there's no letter that appears at uh odd number of times but a b is not because both a and b appears uh an odd number of times okay and then you're given like a string word that consists of the first 10 lowercase english letters right so this and return the number of wonderful none empty substrings in the word okay and then if the same substring appears multiple times in word then count each occurrence separately basically you have duplicated same string appeared multiple times each one of them should be counted to the final answer right so for example we have aba right so this one the answer is four because obviously you know the lighter is soft it's a sub is a valid one single letter is always a wonderful uh string here right that's why you know we have a b a and then in total aba is also a one for substring right because this one uh only b appears uh odd number of times and then we have another one a b the number the answer is nine right so this one like it's h and e because the letter itself is always the answer right the uh one of the answer and then constrains 10 to the power of 5 and this one right so look at this so the only 10 letters in total okay um yeah so for this one actually you know a brutal force way it's all obviously just trying to do a like find other sub substrings right and then you will you basically find the uh the for each substring you check if that substring is like it's a wonderful three or not but that will definitely tell you because just to find the sub or the substring you need an n square time complexity right okay so for this kind of problem you know and this one is a count right so for this kind of problem you either use like a dp to solve it right or um yeah actually most of these kind of string counting problems are can should be uh will be solved by using the dp concept here and for this one uh the tricky part is that how can you efficiently check right at the current state at the current uh index how can you efficiently check uh what are the wonderful strings uh i mean so far right that's why you know we need to use this kind of like uh english 10 letters right a and j so we have to use this one otherwise it doesn't make sense give us this one right i mean this one actually is very similar uh with one of the problems we just talked about like a while ago and for that problem like i believe that problem is for to find the longest uh substring whose um who's uh i think oval letters all the overall letters are even right i if you guys remember that problem you know i think that's what i think one 1044 that's a problem number in that problem you know we basically we use the uh a bit mask with five digits to represent the uh the parity at each state basically for each of the prefix right and for this one actually you know it's we will be using the same concept here so this one is also dp with a beat mask so the reason being is that you know uh so first right i mean let's say we have this kind of like uh substring here let's see at the current state right remember so we uh we have a 10 bit mask right so it's going to be a 1 0 let's say 1 0. for example this is 0 1 0. for example this is the beat mask i'm not uh writing all the djs here but in reality which there's there should be like 10 degrees here let's say you know so the way we're maintaining the speed mask is that you know whenever we have a seal numbers here we revert this uh bit values from one to zero or zero by one which means that you know at each bit values it represents the parity for that letter because this one's going to be a b i think it's going to be like this so a b starting from here a b c d e f g h something right so 0 means that okay by at this low location for example here right at here we have even number of a's and one means that i at this location the prefix stop here the has odd number of c's and why do we need to maintain this one because you know so first you know if uh if we can find the same like uh same beat mask uh appeared before then we know okay so basically two same beat mass you if we subtract that you know let's say we have another one let's say here right if this one has a bit mask these ones also have beat mask assuming they are the same okay if they're the same what does it mean means that you know the substring in between like this one all the appearance uh i mean the uh the appearance for all the lighters they must all be even because the parity are the same right so odd subtract odd number of equal to even right and even subtract even also equals to e right so that's the first one basically this one covers the uh one of the scenario so the scenario that you know since this one is for this problem you know we are allowing at most one uh odd even uh letters so this one you know if we find the same like uh bit mask and then where we have covered all the substring who has who have zero uh odd appearance right then how about the one at most one right so for that one you know actually uh if we have the beat mask right so i think if you think about it a little bit more right so how can we find all the bitmap uh even uh out case with one letter we can simply try to reverse each bit value right one by one for example you if we remove if we revert this zero from zero to one right and we keep everything else the same what does it mean means that okay all the other if we can find such like bit mask before somewhere here right that means that okay between that bit mask and this one let's see if this is a mask one right so if we change this one it means that this substring here it means that okay this substring has a as a appears odd number of times because all the others are the same only a is different then it means that big and in this case it means that basically the odd subject even equals odd right and even subtract odd also equals to odd right that's how we use this one you will revert one of the bit value and then we can get this odd case here right and as you guys can see we need to uh do this for each of the beat value right that's how we check all the possible scenarios right who has only one uh letter appears odd number of times right so that's that and about the counting right so what if the you know since here we're only like checking the existence but instead we should have like a dictionary to count the uh to store the appearances for each of the bitmask because so the reason being is that you know let's say we have um for example we just use this as the bitmap the same mask as in as an example which means that this even case here it means that let's say this bit max appeared three times in total okay let's see this is the first time right it appears the mask here and then here it appears again right okay let me remove this one so let's say here it appears again mask here again right same mask and then in the end here we have another appearance here okay so for example we are at dislike index here okay so if we have three appearances of this one right so how many if we have if at this one so how many substrings right basically ending with the current this i are wonderful strings the answer is two right so why two because we have see we have two masks that have the same mask with current one so which means that you know so this is the first one right so this is the first substring basically that substring is a this is a wonderful one i mean in terms of the uh they're all even appearances right and the second one is this one right from here to here see that second one ending with the current uh lighter here right so now as you guys can see so which means we need like a counter to keep track of the current the appearances right for the for each of the mask right and then at the current mask right we just use that to find the total substring uh by using the count of that mask so either is this is the mask itself or we try to flip each of the lab the digits and try to find the odd even the odd appearance case uh yeah i think that's it right i mean once you figure that out then you the coding actually is pretty short you know so we have a mask starting from zero right and i have a count i guess uh house card count it's gonna be a default dictionary right so the answer is zero right and then for c in word so we need to find the index right so i mean the index is going to be the ord c minor we're going to convert this one to its uh integer value and then we use it this one to do some uh beat manipulation so the mass is going to be this one right index right so this one basically every time we see a numbers here we find it's a corresponding index and then we basically we use this one to re to revert the bit value from either from zero to one or from one to zero by doing an x or with this one right so this is like small a small trick uh of how you can revert a bit value okay and then of course so when we have this one so the first one is this one right we're going to count this one the mask so this is the scenario right so all letters uh appears an even number of times right so this is the even number type case and then for the out even out number case each slider right basic one ladder right one ladder appears an odd number of times so for this one we have to basically to check each so check each number right so for i in range of 10 right because we have 10 lighters in total so the uh basically i'm using a pre mask here so it's pretty much going to be the mask uh this one dot right that's how we revert this a flip that flips the value off of a beat of a bit and then we're trying to check that right so this one's going to be a count of pre mask right and in the end don't forget to uh don't forget to update the count for each mask right cool and then in the end return the answer right so that's it but this is there's like small things we have to be careful which is the uh the base case which is the single ladder case right so for a single letter case you know so let's say for example a should be a itself should also be counted as one so if we're doing this a will be lb0 basically right because you know for a of course the mask itself is some t but if we flip a right so a is one right if we flip one to zero so we're like expecting one right but since the pre mask will become to zero and zero does not have any values that's why you know this one will be answered which means for zero right count zero this one should be equal to one it means that you know the base case is one for all the single ladder case so which means there if there's nothing here right that's how we can for the single ladder case you know we can use this count pre mask count basically comes zero to give us one right and that's it right so if i run the code so it's not accepted right yeah cool so that's it right because this one it works because the time complexity as you guys can see is uh this one is n right so this one is and here right here we're only uh we're only having a 10 constant 10 loop here which is 10n okay and the space complexity right space complexity this one is the so this is a time complexity right time is this one and the space is what space is the uh this one basically the two to the power of 10 right that's a total possible number of the uh of the beat mask uh cool yeah i think that's it right for this problem yeah it's very interesting problem you know this is the second one that i have uploaded regarding the parity of the uh of the count for a lighter right so for this kind of problem just remember i always use the beat mask okay and to represent the odd and even and we use the other even characteristics to find the uh the even number of appearance of even number of times or at most one uh odd number of times cool thank you for watching this video guys and stay tuned see you guys soon bye
Number of Wonderful Substrings
check-if-one-string-swap-can-make-strings-equal
A **wonderful** string is a string where **at most one** letter appears an **odd** number of times. * For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not. Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-empty substrings** in_ `word`_. If the same substring appears multiple times in_ `word`_, then count **each occurrence** separately._ A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** word = "aba " **Output:** 4 **Explanation:** The four wonderful substrings are underlined below: - "**a**ba " -> "a " - "a**b**a " -> "b " - "ab**a** " -> "a " - "**aba** " -> "aba " **Example 2:** **Input:** word = "aabb " **Output:** 9 **Explanation:** The nine wonderful substrings are underlined below: - "**a**abb " -> "a " - "**aa**bb " -> "aa " - "**aab**b " -> "aab " - "**aabb** " -> "aabb " - "a**a**bb " -> "a " - "a**abb** " -> "abb " - "aa**b**b " -> "b " - "aa**bb** " -> "bb " - "aab**b** " -> "b " **Example 3:** **Input:** word = "he " **Output:** 2 **Explanation:** The two wonderful substrings are underlined below: - "**h**e " -> "h " - "h**e** " -> "e " **Constraints:** * `1 <= word.length <= 105` * `word` consists of lowercase English letters from `'a'` to `'j'`.
The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters.
Hash Table,String,Counting
Easy
889
639
hey what's up guys uh this is chung here uh again so this time lead code number 639 decode ways number two okay so this one you know it's very similar to the decoded ways number one right so you know the only difference for this one is that you know uh is besides the numbers from zero to nine we also have like a wild card which is star but anyway so basically uh we want to decode a string of letters of digits into uh the mapping the mapped uh in english letter version right so basically so a can be mapped a maps to one b maps to two and z maps to 20 up to 26 okay and to decode you know if you're given like this kind of a string right so we can decode this one into a ajf or kjf right but this uh this 1 11 and 0 6 is invalid because 6 cannot be represented by 0 6 it has to be 6 not without the leading zero right and then so what's interesting for this problem is that you know we also inter we're also introducing a wild card so basically a wild card which is star can represent any digits from one to nine okay keep in mind so zero is excluded which means that this one can start cannot be cannot represent zero you know i didn't notice this part that's why i got the wrong answer at the beginning right so we have to be careful so it's only from one to nine uh yeah and then and since the uh the final answer could be large we do a modular right so for example uh example one if there's a single star obviously then the answer is nine because it has basically from one to nine without zero right because zero because the our numbers are our letters starts from one not zero right and then one star we have 18 right uh so on so forth like this one and then right so for this one you know if i think you guys all know how to do the soft decod decode waste one right basically we're gonna use a dp solution right we have a dpi here okay so dpi means that you know from zero to i how many uh how many ways we have to decode this uh string here right and at current i here we i mean we do two things right so first we check if the isi right so if the eyes i is greater than zero if it is then we do a dp i uh plus dp i minus one right so basically we have two scenarios you know if the current one is not zero that means that no we can use the current one to as a separate letter that's why you know we can just accumulate the previous one which is dpi i minus one right and then the second one we will check right basically if the s i minus 2 to i is within a range of a 10 to 26 right so if that's the case right and then we have another solution basically we can use the current one the previous one to represent the ladder from 10 to 26 which is uh i think from j to z i think this is i think something like that right so and then we can also accumulate that second inversion is this right dp i minus two in this case right basically similar like this is a one uh one here right so we have some letters beforehand let's see where we're at here so first it's this one basically we can use this one to represent a that's the first one right and then the second one is that you know since we also checked the previous one and the current one right we checked if these two numbers are within the range of 10 to 26 right this one's 11 it means that we can also uh decode this two as a as i like as a single letter i think it's uh i think this one is gonna be k if i'm not mistaken right that's why you know once we do this you know okay so first one if we use the current one as a separate letter now of course right uh the previous uh count will be i minus one right or if we use the pre these two uh digits to represent to rip uh to map a new ladder here then the previous one of course will be dpi minus two right so we just accumulate this uh all the way down to the end right and then we simply return the dpa dp minus one that will be our final result so that's the decode way number one but for this one since we have a wild card star right so we have to consider it separately you know so for me i uh i think i just have like write a bunch of if statement basically i just uh consider them separately you know the first one is like this one right the first one is oh it's obviously sorry it's one right so this is the similar the same case as the uh as a decode one right the second one is what second one is this one right one star right third one and then we have star one right and the last one is star right this one isn't this one can be any anything right i'm just using one as an example right so basically this is the four uh scenarios we have right i believe there's a there should there can there could be a way to combine all these things into one like sec section of code but i just handle them separately okay so this one we already know right so for this one okay so if the current one is a star right and the previous one is not it's not star so what does this one means it means that you know uh it means that you know obviously the current one can be from one to nine right and then it means that okay uh it means obviously we have dp of i minus 1 times 9 for sure right because if we treat the star as a separate ladder and we can have like whatever before we have plus one to nine that's why we have dp i minus one time times nine right and then depending on the previous letter right we could have like a different we could have different uh a few more right for example if we have one as a preview as a previous uh digits here what does it mean it means that we can also have like 1 11 to 1 to 19 right because remember this one can represent anything which means that you know the with this case we also have like dp of i minus 2 times 9 right so that's the that's a that's the second part because with 1 we have this but if this one is two okay if this one is two so what do we have so first oh this one is always valid right depending on what the previous value digit is you know the second part could be different so if this one right if this if the previous one is one because the previous one it's one we have this right if the previous line is 2 we can only have 21 to 20 26 right know what this one it means that we have dp of i minus 2 times time 6 right so this one is dp i minus two times nine right what do what how about three two three to nine or three two to zero doesn't really matter right so if it's three if it's if the previous one is other than one or two then this part is gone right okay cool so that's that and so that's the first scenario how about the second scenario right so the second scenario is this one so the current one is not it's not one sorry the current one is digit but the previous one is a star right so for this one you know uh obviously we have dp of i my minus one so it's similar like this one right and then plus what plus the previous one so the previous one only has like two scenario like same thing so the previous one if you want to include two uh two digits at for this case the proof zone can only be either one or two right i think for one you know we will definitely have dp of i minus two because you know if this if you if we use the wild card to represent one right it doesn't really matter our current number it can always be dpi minus one right and then for the second for second dp i minus two which is the case this one equals two then i need to check if the current one if this one is within zero is in zero it's within zero or six right if that's the case and then we know okay we can use the 2 to represent the plot to which this one to represent a valid letter right okay and so that's the second one you know or you can just always what do you can always do a for loop whenever you see a star you just do a for loop from one to nine right and then you just um basically iterate all the combinations and then you always check if the ladder is within 10 to 20 to 26 then if it is you just what you just increase the count by one i'm doing this just to avoid that for loop to improve the performance at a little bit you know even though it will not affect the big o but you know still it's a 10 if you have 10 times 10 for loop is going to be a 100 right for the case of this one okay back to here right so this one is like if we have two stars so what do we have uh two stars of course we have this one right so first we have dp of i minus 1 times 9 right so that's the uh the case of using this the second star as a single letter plus what plus dp of what dpi minus 1 i minus 2 times what 9 plus 6 right because we already know right if we want to include the first these two letters there are only two cases that this will work if either if this one is one or if this one is two right and we have already calculated that you know if we need it is one we have nine possible ways when this two we have six so total will be nice plus six right so that's how i did it i just analyzed all the different scenarios and that's it and cool yes and then we can start coding that let's see we have gonna be a length of dp right zero uh n plus one right because i uh dp zero equals to one right so because you know if we have two letters right like one right i mean we do a dp i minus two you know right so this one if when i is equal to two dp zero should be one right this means that dp zero equals to one means that you know if it's an empty string right if it's empty one there's nothing which means it means that we have one way of decoding it which is nothing right basically that this is the base case number mod was to 10 to the power of 9 plus 7 right uh and then the dp right so for in range one two and plus one right so the first case is like if that's i minus 1 right it's not equals to star all right so i check if the s if the end i think i can do this if this one is not equal to this to zero right and now i can do a dp of i equals to dp of i minus one right or you can do a accumulate it doesn't really matter so this is the first step right so this is the uh the what uh maybe this case right it doesn't really matter this case maybe basically the current one is not it's not like uh a star right maybe two yeah i don't know if i can write a proper example here the second one is the uh basically here's only decode right one current digits to ladder right so the second one is decode uh two digits right two ladder right so this is the second one to do that we have to do a check basically we can only do this which is five is equal greater than zero uh greater than one right and then if basically here i'm separating them into two scenarios right so if the previous one is star right so if the previous signs is it's not star okay so if it's not star and then that's the uh that this is the decode one base right decoder ways one scenario right which is the they're all letters right like 2 23 something like this right so if that's the case i can i simply check this one right so if the that's 2 is in within the range of 10 to 26 right i minus two to i uh to 26 right then i just accumulates i to this dp i minus two right so that's the let's decode one case else this is the uh the wild card case basically it's going to be a star one a star or star two right so that's the uh the wild card case so for this one right we so first we have dpi plus dp i minus 2. so this is the case of use star as s1 right so for if we use stars one you know it doesn't really matter what the current value is it will always be a valid one right and then the second one is that you know if the end of s uh i minus one right is smaller than six if the current one is smaller than six then we can also uh basically accumulate this uh i plus two one more time right so this one basically we use star as two right so when we use stars two the current one has to be smaller than six right so this is the two scenario here right okay now we have handled all the scenario when the current one is not start and then else is when the current one is a star right when the current one is a star uh first we have this right so we have i dp of i minus one times nine right so what does this one mean it means that this one is means that you know we use the current one as basically decode current star to lighter right which means from a to uh i think i yeah so basically this one we decode current star to ladder which is a to i that's why we have nine times this right and then the second uh scenario not a case is that we have to consider two letters two digits right basically similarize the as the previous one we have i equals to greater than the one all right so this one we have this one right we have like i said we have three scenario here so the first one is that you know if the s i minus two if the previous one is equal to 1 right so what does it mean that you know we have dpi times dp of i minus 2 times 9 right so this is the case of 1 11 to 19 right else if s i minus 2 is equal to 2 right so for this one we have i can copy and paste this one is six right so this is the 20 to 26 sorry 21 to 20 to 26 yeah so keep in mind be careful this is not 20 to 26. i was a i was using seven here that's why it gave me a wrong answer because remember the star can only represent from one to nine not does not include zero that's why this is one twenty one to twenty six not twenty okay else if as i else if the previous one is a star right then it is a this is a knight nine plus six right basically this is like the combination of the first and second case right so this is the uh eleven times nine plus right so that's a combination because you know star can become star can represent anything from one to nine and only one and two uh can give us some valid uh decode ways okay that's it right i mean and don't forget to do a modular every time we fin we're finishing the dp right and then in the end return the dp of minus one i think that's it right um yeah i think let's try to run it see if it works okay this will accept it if i run it again cool so it works right uh yeah i think that's it right i mean for time complexity obviously this one is like o of n time complexity right n is 10 to the power of five because uh we're not we're simply doing some like off one uh calculation here right and another way you know we have a lot of e-files here of e-files here of e-files here i think another way of doing this is that if we don't have if we don't want to separate these things here you know every time we see like a star here we can always do a for loop we always do a for loop from one to ten right so that way we can do some combinations to always check if this one is like so do something like this we always check if this one is in the two digits is in the increasing range of 10 to 26 right basically we can rewrite this part into some like nested for loop right if there is a two stars so for the first one we have a for loop from one to nine and then we have a second nested four loop for the previous one as an one to nine and then we can just do some comparison right i think in that way i believe we can combine some of this uh conditions here right but that i think that condition will be a little bit slower because we all have we'll we're gonna check some unnecessary uh combinations like three star four star and five star those kind of thing you know i did it in this way because this way is fast it's faster and we don't have to add that and that's it for loop there anyway that's how i did and i guess i'll just stop here and thank you for watching this video guys and stay tuned see you guys soon bye
Decode Ways II
decode-ways-ii
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 "`. **In addition** to the mapping above, an encoded message may contain the `'*'` character, which can represent any digit from `'1'` to `'9'` (`'0'` is excluded). For example, the encoded message `"1* "` may represent any of the encoded messages `"11 "`, `"12 "`, `"13 "`, `"14 "`, `"15 "`, `"16 "`, `"17 "`, `"18 "`, or `"19 "`. Decoding `"1* "` is equivalent to decoding **any** of the encoded messages it can represent. Given a string `s` consisting of digits and `'*'` characters, return _the **number** of ways to **decode** it_. Since the answer may be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "\* " **Output:** 9 **Explanation:** The encoded message can represent any of the encoded messages "1 ", "2 ", "3 ", "4 ", "5 ", "6 ", "7 ", "8 ", or "9 ". Each of these can be decoded to the strings "A ", "B ", "C ", "D ", "E ", "F ", "G ", "H ", and "I " respectively. Hence, there are a total of 9 ways to decode "\* ". **Example 2:** **Input:** s = "1\* " **Output:** 18 **Explanation:** The encoded message can represent any of the encoded messages "11 ", "12 ", "13 ", "14 ", "15 ", "16 ", "17 ", "18 ", or "19 ". Each of these encoded messages have 2 ways to be decoded (e.g. "11 " can be decoded to "AA " or "K "). Hence, there are a total of 9 \* 2 = 18 ways to decode "1\* ". **Example 3:** **Input:** s = "2\* " **Output:** 15 **Explanation:** The encoded message can represent any of the encoded messages "21 ", "22 ", "23 ", "24 ", "25 ", "26 ", "27 ", "28 ", or "29 ". "21 ", "22 ", "23 ", "24 ", "25 ", and "26 " have 2 ways of being decoded, but "27 ", "28 ", and "29 " only have 1 way. Hence, there are a total of (6 \* 2) + (3 \* 1) = 12 + 3 = 15 ways to decode "2\* ". **Constraints:** * `1 <= s.length <= 105` * `s[i]` is a digit or `'*'`.
null
String,Dynamic Programming
Hard
91,2091,2251
94
Ka Sevan Kaise Aap Log To Can Say That This New Series Distributors Juice And Friends Use Jor Code In Java Script Only So Friends Now Without Further You All Subscribe The Tree Of Hello Friends Please Forgive Me For This Handwriting This Is Tay Be Taken Into Consideration And Solutions to solve different types of what happens in hotel traversal subscribe and subscribe the Channel subscribe particular bluetooth tension hai okay so let's any record here celebrity function is in order which also has tracking route na that airways simply slide also In odd numbers ok so this is the roots in the city to international a new year to * process the left subreplies who invented a new year to * process the left subreplies who invented a new year to * process the left subreplies who invented famous fruit a nerve win to famous rights activist that 100% simple room for innovative work but as that 100% simple room for innovative work but as that 100% simple room for innovative work but as you can see a gift to 10 of making changes according to a passing this root is and spider in this what will be doing this increase will ask item given are that and from is what we can do we can simply return this reference this root and sorry other wishes for this function And simple algorithm and returned the extra running first any1 submitted i office such can see are code have been accepted norms and standards call set a so friends what happened at all i let me down that a first so friends the first annual day function will be Called For One Day A Rook From The Morning This Point 00 Calling For Absolute Element This To A Notice To Win The Calling For Its Left And Slept And Don't Know The Laptop This Is This Element Criminals Who Also Will Hand Over All Song To Pure Sweet Corn Final 80 left call voice mail rural and s well written this is particular k to do subscribe to a novice and professional left for this particular not know when placid under root ok thank you to so will play in the root and two three do and what we Can do the element null were so prince dictionary will also written test and now e two not have any for the speed of code withdrawal on the other hand lines for the tonight and will be returning back to 9 subscribe that they can control this one ok like To The In This Particular Waterfield 215 I Suresh Know Where Possible For Saif And This Supreme Is The Cost Of Wave Will U Guys Loop Control 44 And Subscribe And Widening And Subscribe To Our Channel Subscribe Now To The Part Of Speech 500 Or Also Got Toe nail first British element day processes flight is root and feel process the life partner lage ok band abhi subscribe kar tha Indian Doctor bhi MP na thanks olive oil second line should have it's ok friends that today this is the call pack aayog ne bean Able to make you understand so friends this is the first question of series and woman middle aged subscribe the video like share and subscribe thank you
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,3,2\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
98,144,145,173,230,272,285,758,799
1,558
hey what is up guys today we got another leak question number 1558 minimum number of function calls to make target array i literally just finished this question and i don't want to do this but i'm going to explain the question really nicely and you'll fully understand the answer really quickly so we have this function okay and our task form integer array numbs from an initial array of zeros array that is the same size as numps return the minimum number of function calls to make nums from array the answer is guaranteed to fit into a 32-bit sign integer 32-bit sign integer 32-bit sign integer so if you're here ready you obviously read the question already so i don't like explaining it uh too much but basically um we have this uh we're basically going to act like we're starting from an array with just zero so zero let's say it was of size three and we're given a target array and let's use this example that i worked with which is two five right four two five and we need to perform a set of operations to get from this to this and we can only do two operations one is we can multiply all the numbers by two and two um right there we can increment a single um index or a number whatever you want to call it by one okay and so basically we're gonna have to work backwards so we can either do like zero one and then multiply by two so we get something like zero two and that's that but um so when you're doing this kind of problem you have to think of it like this we're starting with zero okay and we're trying to reach a goal which is four to five when we're going from one place to the next you can always you can either go from your starting to your goal right and then kind of work that way or you can try to if you know your goal already you can start from your goal and work backwards and sometimes it's a lot easier and in this case it's a lot easier because every answer will have a standardized goal which is an array of all zeros right an array of all zeros so this is our original um uh array sorry zero we're trying to get to four to five but instead we can think of it a little differently we're trying to get we're given an array of nums and we want to turn this into all zeros think of it like that and depending on how quickly we can take this to this um that will be our answer so we just want to work backwards and the way we're going to approach it is kind of like this so let's say we had this number 425 and we want to get it quickly down to zero okay well if you played around with some examples you'll notice that um it has to do um with even and odd numbers okay because let's say we had one and we divided one by a two we could either end up with um zero or with um or uh one we could have started from zero or one and see that's a problem we don't know which one is going to be which or let's say but basically let's say you're right dividing three by two that would that wouldn't work because you know now you can't you couldn't have come from 1.5 right that's not possible 1.5 right that's not possible 1.5 right that's not possible so we know that if we were if we notice that if we're not if we notice that if we are at an odd number that means we can only have come from it by adding one meaning it was originally two and we added one okay and if we were at an even number then we came from it by dividing by two okay that's kind of how you want to think of it so that's one thing to notice that if we were an odd number right the only way we could have came to that odd number reach that odd number is if we added 1 to an even number now so let's just try to work backwards and now you'll kind of understand that so now let's say we have four to four well we want to start bringing it down well we see that they're all odd they're all even so let's just divide everything by two that'll give us one operation and that will quickly recommend all our numbers so four two four will turn into two one two and we'll do one operation on it yeah sorry so we have four two five and then we see that one of these numbers has one of these numbers odd so we'll subtract one so we end up with four two five as you can see we've added one operation and previous had all odds so subtract one now this is a little weird the way i wrote it but whatever and then so from here right we can we see that they're all even so let's divide by two so that's how we got here so previous one was only even so we divided by two that was another operation then we see now we see one odd number right and so now we're gonna subtract one so we get two zero two now we see they're all even so we'll divide by two we see one zero one so then we see it one of them is odd so we'll subtract one we move that we'll start from that one now we get zero one we see another one is odd once again we subtract and then we end up with all zeros and that's kind of how you wanna approach it but the problem is now and that's why some people came with one liner solutions uh if you see so many people other solutions because you can do it that way if you have function calls like a reduce or something that will apply to the whole entire um array at once but i don't really think that's what the uh interviewers are looking for but that is really cool so i like seeing that but um i don't think you can do that in java maybe you could do that with job with some laminar functions i don't know okay so but we can't really iterate like that in the code in java so what we're going to do instead is we're going to start decrementing each number one by one okay so we're gonna go to four and we're gonna take four all the way down to zero then we're gonna go to two sorry the two right here and we're gonna take that all the way down to zero and we're gonna go to five and we're gonna take that all the way down to zero so we're either gonna divide by two subtract by one we're gonna divide by two subtract over one now every time we subtract by one we have to increment our account right because that's one single operation but when we divided by two right if we divided by two that will apply to the whole array right that will apply to the whole array so we need to keep track of how many times we divided by two already okay so basically our maximum number of divides by two that we had previously so let's say over here we divided by two to get four we divided by two so do four you divide by two and you'll end up with two divide by two you end up with one make sure that's gonna end with zero then when you're working at two you divide by two you can't increment the counter again you can't say that's another full operation because we already divided the whole array by two in this previous operation right that's something you need to notice we already divided by two in that previous operation okay so we're going to divide by two or with one then we subtract one we'll end up with zero so that's basically the gist of it we can't really write that and close that we iterate through the numbers and for each one we divide by two and subtract by one each time if we divide we only increase the count if it's greater if we subtract we increase the count every single time once the number hits zero we can stop here so this is the code so we're gonna work backwards we have a count of zero and basically this our current divides how many times have we currently divided this number by zero by two and you'll see that and this gets reset at every iteration right here we'll get to that in a second and this is our maximum number of divides the most number has been divided by two basically it's dependent on the largest number in the array um uh and then so now we're iterating through all the numbers for every time we iterate we hit a new number we're going to reset to zero get our current number and then while that our current number is still greater than zero if it's an even number as we mentioned we're gonna divide by zero we're gonna divide by two and we increment uh the current divides now our count our current divides and then we check if our current divides more than the maximum number of divides we already had right then what are we gonna do well we're just going to um well let's say it's not if it's not that we can't recommend our account we don't we set our maximum number buys and we just keep going but if it is right let's say we were doing two um i don't know like this example we just mentioned the for the four the two of the right here right if it is well that would be like if it is then we know we need to divide by two again so we're gonna divide so then well we did divide by two forgive me so we know we need to increment our count this time because like if you think of it abstractly we haven't divided by two yet so then we can divide by two we increment that will be another operation that we do so we increment our count and we reset our max divides and we keep going and let's say it was odd well if it's odd the only thing we can do is we can subtract by one because as we mentioned if we were at an odd number like let's say three we couldn't have gotten to three by multiplying 1.5 because three by multiplying 1.5 because three by multiplying 1.5 because that's not that's a decimal right that's a double um so we had to the only we could have gotten from that is if we added one to the next even number which is one subtract one minus that which would be two um so then we subtract from n and we just increment count and we keep doing that until we finally hit zero and then that's it then we move on to the next number and we keep doing that for each number and eventually we're going to have an array full of zeros and then return our account and that's basically the final answer yes this is a friendly reminder to like comment subscribe uh if it's helped you or not let me know if i can improve any way somehow what just let me know uh i'm one of the reasons i'm doing this is to practice my uh speaking ability and my communication so if there's any tips you have on how i can improve that please do let me know and don't forget to hit the subscribe button and hit a like if you enjoyed and leave a comment if you didn't and also hit the dislike if it wasn't a good explanation um but try not to but yeah
Minimum Numbers of Function Calls to Make Target Array
course-schedule-iv
You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function: You want to use the modify function to covert `arr` to `nums` using the minimum number of calls. Return _the minimum number of function calls to make_ `nums` _from_ `arr`. The test cases are generated so that the answer fits in a **32-bit** signed integer. **Example 1:** **Input:** nums = \[1,5\] **Output:** 5 **Explanation:** Increment by 1 (second element): \[0, 0\] to get \[0, 1\] (1 operation). Double all the elements: \[0, 1\] -> \[0, 2\] -> \[0, 4\] (2 operations). Increment by 1 (both elements) \[0, 4\] -> \[1, 4\] -> **\[1, 5\]** (2 operations). Total of operations: 1 + 2 + 2 = 5. **Example 2:** **Input:** nums = \[2,2\] **Output:** 3 **Explanation:** Increment by 1 (both elements) \[0, 0\] -> \[0, 1\] -> \[1, 1\] (2 operations). Double all the elements: \[1, 1\] -> **\[2, 2\]** (1 operation). Total of operations: 2 + 1 = 3. **Example 3:** **Input:** nums = \[4,2,5\] **Output:** 6 **Explanation:** (initial)\[0,0,0\] -> \[1,0,0\] -> \[1,0,1\] -> \[2,0,2\] -> \[2,1,2\] -> \[4,2,4\] -> **\[4,2,5\]**(nums). **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109`
Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array.
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Medium
null
1,420
Hello everyone welcome to my channel Quote Surrey with Mike So today we are going to do video number 15 of our playlist of DP Concept and Questions Okay first of all watch a motivation Yankee speech Excuses are like drugs it makes you feel good for a moment but If You Keep Doing It In The Long Run You'll Never Be Able To Suck Okay So I Promise Not To Give Excuses Any More Okay Keep Going There Are No Excuses Okay In Life If You Want Some Success Means Achieving Okay In Life Stop Giving excuse and keep on moving okay so let's move ahead and you will know that in this playlist we are understanding DP from the core, Nadi bass DP was going on and we were doing variation of AIS, right alias means alias of longest e sequence, we already We have done it from recurs and bottom up in video no. 11 12. After that what we did was start making its variants. In video no. 13 we made the maximum length of chain pair. Okay, we made the longest string chain. In video no. 14, right today. Video no. It is 15 and today's variant is one of the toughest Als variants. Okay, this is a hard variant of Als. Now look, it is hard, so it is obvious that it cannot be made with the code of exactly the same Als. It is ok. If you look at the question, you will understand. According to the requirement, the code will also be very simple, okay, there is only one tough part in this, that is where AIS is hidden in it is okay to identify it, rest of this is going to be a very simple DP code, it is going to be simple, it is okay. The name of the question is Build Are you able to find the maximum? Let's read the comparison question exactly and understand what the question is trying to say. Lead code number is 140 look is hard marked but actually its code is going to be very easy, its ok. The tough part is to understand in the beginning what we have to approach in this, okay and which company has asked that I don't know the age of now but I will soon update as soon as I know okay then let's see the question is quite straight. For words, it has been said that three integers named n m and k have been given to you and an algorithm has been shown to you here. This algorithm is very simple. What is this algorithm? The algorithm to find the maximum value is fine and its index is of both in the starting. The value is -1. both in the starting. The value is -1. both in the starting. The value is -1. Okay, as soon as you get a value which is greater than the maximum value, you update it and add the search cost to it. Okay, lastly you send the index of the maximum value. This is a very simple algorithm, I have shown you but the tough part is here. Look, you should build the array which has the following properties. You have been given AA and you have to build an array. Following these three properties, what is the property? There should be exactly n integers only. It is okay and whatever values ​​are there in are only. It is okay and whatever values ​​are there in are only. It is okay and whatever values ​​are there in are okay, its value in are should be between one to m only. It is okay, you can repeat the value also, but from one to m. It should be between How many possible ways are there that you can make such an array? Total number of ways to build the array is an RR. Under the mentioned condition, it is okay and the answer can be very big, so it is okay to send the answer in module, so understand from this example. Many things will become clear from this example, like what has been said here is that n e 2 means only two sizes, hey, it is okay, m = 3 means sizes, hey, it is okay, m = 3 means sizes, hey, it is okay, m = 3 means that you have three numbers, bt and th, out of these three numbers. You can use something to fill this array, okay k = 1, to fill this array, okay k = 1, to fill this array, okay k = 1, what does it mean that whatever array you create is fine, it has a search cost, one should come, now what does search cost one mean, only once, this one. The condition must have been true only once. This condition must have been true only once. Okay, only then the search cost would have become one. Right, let's see what is possible. So first of all, I feel that if I become one of the forest Okay, then my search cost will be one. Let's see how. Pay attention to this algorithm. In the starting, minimum maximum value is -1 and In the starting, minimum maximum value is -1 and In the starting, minimum maximum value is -1 and maximum index is -1, so maximum index is -1, so maximum index is -1, so maximum value is -1. Okay, I came here, it is value is -1. Okay, I came here, it is value is -1. Okay, I came here, it is greater than -1. Yes ok so one comparison became true greater than -1. Yes ok so one comparison became true greater than -1. Yes ok so one comparison became true so how much did my search cost become one ok and my maximum value has been updated one ok now I came here ok earlier my index was here now I came here so Is this one, is it bigger than my maximum? Otherwise, if the comparison is not true, then the search cost remains one of one. Okay, now I came forward, it came out of bounds, so look, pay attention, this is my one valid, so there is one way. This is done, now it's ok and look, the search cost is one, keep the search cost only for the eve, you can keep the search cost not more than this, okay, after that, what else is possible, one more, hey, I am seeing this, 2 earnings, look at this in the beginning, mine The maximum value is minus and the search cost is zero. I came here, my index is here, is it more than the maximum value? Yes, I updated the maximum value. Okay, I have done the search cost. Now I came here. Is it more than the maximum value? If it is not there, then the search cost will not increase. Okay, look at the search cost of this too, it is equal to one. Okay, like this, more can be made. Also, look, it will give the same search cost. Search cost will give one. 3 1 3 2 3 So total. There are six possible ways, total is six possible ways, this will be your answer, okay, there are total six possible ways, in which your search cost will come exactly only one, okay, so little by little, I started getting hints from here itself that you are looking at this index. Let's talk about index number zero. Look here, first we tried one, then we tried two, okay, we tried three too, okay now look at index number one, we tried two, we tried th also. So I got a hint that I will definitely try all the numbers in every index and see how many numbers I have one, two, and even one, so I will try one in every index, too. I will try three, I will also try, okay, it is understood that I am seeing options, so I note down here, I am seeing options for every index, okay, it is clear till now, so now let's move ahead, this is our thought process. While it is building, first of all I have understood one thing that I have options for every index, now see what is hard in this problem, what is the thing that is making this problem hard, look, pay attention, first of all. Not only this, I did not understand in the beginning how to approach this, but one of them gave me some hint that I will try no options on each index, first I will try one, then I will try two, then I will try three and so on till M, then I will try a little. I got relief and some help here, I am fine as to how to approach, I am feeling light, now it is fine, the second tough question is that brother, why is this DP, I tell you like every time, let's go. You are not understanding that DP should not be run by DP value only, you should do whatever your thought process is telling you to do, okay then right now you are not running by DP value, okay and the third and most important question. That's why I am saying that this is a variant of Als, it is okay and this is a hard question, it is a hard variant of S, so do not expect that if the same code of Als is pasted here, it will work, it is not so, okay. Just want to show you why this AIS is hidden in it Okay, let's look at that first so let's look a little bit here at how this AIS is hidden in it Okay so let's take an example Let's assume that my search cost right now is zero. What was in the algorithm, here the search cost is zero, okay and I have been given some value of A and K. Okay, so let's go by the value, A and A will have some value. Let's go by the value that k was not the value. Let's go with the value, okay, if there is three, then keep four, okay, and you have created no, the first element of which is something, the second element is something, the third element is something, the fourth is something, let's assume something, keep any value. Yes, okay, end so on, okay, there are so many elements in it, so think of one thing like going by the value, now you are standing here, okay index, you are standing here, if you see any element then strong, remember the max value in the starting, so obviously. It is a matter of fact that in the beginning there will be minus and till now you have seen only max so far minus and so the first value which is there is assumed to be bigger than the max value. Okay so yes it is a matter. If the comparison becomes true then the search cost becomes one. Okay, after this let's assume that the value is just equal to the value of search cost and just sorry value of search cost is just equal to max value, I must have updated the max value here, let's assume its value was x then max value. Now, because of the value, it was also x. Okay, so the search cost will not increase. Okay, this was also the same value. When ID 1 came here, when ID 1 came here, maybe I could get another bigger value. Found it which is greater than Value, its value is z but it is smaller than y, so the search cost will not increase, the max value of y will remain y, till now the max so far is my y, it is ok, it will not increase. Now let us assume here that another value is shown which is smaller than s is ok d let's assume one here is obviously more than the max value otherwise the search cost will increase and max value I will update s ok but pay attention to one thing search cost is three here right and search cost me Exactly four have to be done okay now go ahead got a big value here and let's assume t here okay adi one here it is bigger than a so t and this is four okay my search cos atl k So if we assume that there is some other element in front, you have created a line which has another big element in front of it. Okay, it is bigger than Joti, so see, the search cost will be reduced. Let's assume that this was my point. So I updated Max Wali from page to page, but this is the poor thing you have made because look, the search cost has not reached five, we had to keep it till four only, so we have to take care of this thing, okay brother, search cost is not in my mind. You should run away from this. Well, leave that aside, but one thing you noticed, here we are looking for the longest increasing sequence, that is, we are looking for the increasing sequence. Look at all the sequences. Earlier, X was a little bigger than We are looking for the increasing sequence, why did this problem become hard because here we already know that the length of the longest sequence has to be kept only four. If you see, then here the length is fixed, the fixed length is L is that is K. Okay, first one, this is done, secondly, why is it a variant of Als, that here it is not given for us, it is not given, we have to make it and we have to make it in such a way that the increasing sequence which AIS we will get is exactly that. It should be good, that's the way it becomes tough, so you know why I told you just to make you understand that there is an alias hidden here, right, you see there is increasing sub sequence, just why it is tough because here the alias is fixed. We need only this much AI, we have to make an AI whose AI is equal to K plus there is no AI given in it, we have to make it, till now it is clear why AI is hidden, now how to solve it, I told you. Do n't even think that it is the problem of DP. Forget about DP. It is ok. Forget about DP which we had just built in so that we were seeing options. For each index, we try the same options. No, we try the same options. Okay. Now let's see how we will get the approach, okay let's move ahead, let's see, I have taken this example, the first example of the lead code is n2 m3 cave, what does it mean that what does n2 mean that the size of my hey is only two. There should be only m 3, what does it mean that we can use either one, two or th, we can use any of these three numbers, okay, the length of k = 1 means the length which is the longest sub length of k = 1 means the length which is the longest sub length of k = 1 means the length which is the longest sub sequence or the total. Search cost is there should be only one, there should not be more than that, okay so this is my Hey and in starting I have to fill for index i one e 0 this index is zero index is one okay so I write that starting In this my e is a = 0 and that starting In this my e is a = 0 and that starting In this my e is a = 0 and what is my length till now I have not filled even a single element yet so the length of my ales I will store it in length now its length is zero and my max value I just know that My max value is still -1, till now max value is still -1, till now max value is still -1, till now I have not entered any number, okay, so the max value so far is -1, okay, so see max value so far is -1, okay, so see max value so far is -1, okay, so see how many options I have here I can either keep one or two. Should I keep either 0 or m = 3, then at this index 0 or m = 3, then at this index 0 or m = 3, then at this index zero I should either keep one, or two, or three. This option is visible and I had told you in yesterday's question, see. There are so many options to put the index at zero, so where did T3 come from, did it come from m? The value of m was three, so A, one put, then explored, then two put, then explored, then three put. I explored it, so what am I actually doing? I am writing the for loop only, that is why I am saying that we will have to write the for loop also, now what will be that for loop, what will be the number, my number will start from one, which will be My lesson will be equal to m, number plus will go on, so number e is equal to one, so I will explore this path, if it is two, then this is three, then it is clear till here, okay, then there will be a for loop, that is necessary but First let's look at the tree diagram. Okay, if we assume that I have tried to place a forest here, then first of all see that if you take a forest and put a forest here, then what is maximum so far? Right now, only Miva is right maximum. Sofar right now, it is human and neither is the forest that you have chosen. So, yes, it is bigger than maximum. Right, if it is bigger than maximum, then it is obvious that this will increase your search cost. Right search cost will increase, right. Length, one more add. It is fine in my LS, so I will make it one plus here, the search cost is increasing because this one is bigger than the maximum one, so yes there will be an update, now see my max value, what will happen, pay attention, now I am in the next index. I will go, this is an obvious thing, I will go to index one, okay, and look at the length here, why did I send one, because look, I got one element, right, one, which is in increasing, the maximum value was earlier -1 and now another update has happened. Which is one, was earlier -1 and now another update has happened. Which is one, was earlier -1 and now another update has happened. Which is one, okay, so after this, what has happened to me, max so far, my max has been updated and has become one, right, it is clear till now, and why we were able to do this because one, which is greater than the previous max value, right. Now what does it mean here that one is filled here, I am talking about this path in this case, right now I am only talking about this path, okay, now my index is here, index is equal to two, right here. What can I fill here I will have three options, either one, two, or three. Look, the tree diagram will be very big, but I expect you to make the tree diagram yourself, it is completely fine, I am just this branch. Okay, now look carefully here, if you put one here, okay, if I put index one on one here, then okay index is mine, I put one, so here I came, there is one here too. Here also there is a forest, so was this forest bigger than my maximum value? No, this forest is equal to my maximum, so the length will not be increased, no length means I assume the search cost, either the longest is the length of the sequence, ok then the length. Mine will remain the same, so what will I send here? I will send it okay and look at my length, it remains one of one and my max also has not changed because the max will not change now, it is only one, the next element is okay, great now. So here the index is out of bounds, the right index is two, so the index is out of bounds, so I will just check whether my search cost or the length of my increasing subsequence is equal to k. See. This length had become one, yes that is equal to k and this is my result, one way, I have got one way from here, no one way, that means one possibility is found, so I will return one from here, that brother, I have got one possible way. Okay, now let's look at this second branch here, if we assume that I had written 'to' here, then see what would be the problem, written 'to' here, then see what would be the problem, written 'to' here, then see what would be the problem, I have written 'to' here, okay, so let's see I have written 'to' here, okay, so let's see I have written 'to' here, okay, so let's see what will be created and 'to' is created what will be created and 'to' is created what will be created and 'to' is created and What will I send here? D one = and What will I send here? D one = and What will I send here? D one = 2. Okay, what will I send? Length. I will send length two because this two is bigger than my maximum value. Till now my maximum value was one. Now I have got this two, which is bigger than that. Let's go to the length of the increasing sequence, it has become two, okay, the length is two, that is correct, see, this search cost increased by one, then a value greater than this was found, the search cost became two, 1 P 1 2, okay, so here we say length. We will use the name of the same variable as search cost, it will be more clear, okay and we will update the max value, I have also got the max value 2, so the index is out of bounds, so I will stop here, but I will check here that Is my search cost i.e. then either the my search cost i.e. then either the my search cost i.e. then either the length of Als is equal to k or not. If the value of k was one, then what does it mean that I will return zero from here that this is possible, this is wrong, this is what I have created in this. The search cost is not equal to k, it is more than k, it is coming to 2, it is clear till here, okay, now let's go to the third one, here hey, what will I get, I will get 1, 3, okay, here is my index. 2 will be ok and 3 is bigger than the last maximum value, so the maximum value will also be updated. Max = 3 and since the Max = 3 and since the Max = 3 and since the maximum value has been updated, it is ok, so the length will also have to be increased. If the search cos will have to be increased, then the length will have to be increased. = 2 then since it is out length will have to be increased. = 2 then since it is out length will have to be increased. = 2 then since it is out of bounds then I will stop here. After stopping I will check that which is my search reason i.e. then the length of Ayas is which is my search reason i.e. then the length of Ayas is which is my search reason i.e. then the length of Ayas is equal to k. Here it is not k. The value is one, right? If it becomes two, then I will say, this is not a possible way, I will return zero from here, that is, from this branch, I got only one, okay, zero from here, what is the sum of all three, if it is one, then I Sent one that from here there is only one possibility, only similarly this branch will also expand, okay, it is clear till here, so many possibilities will come here, let's assume that I would have taken two, look at this, here two remains okay. And my index would have come here, the index is still out of bounds, otherwise here also we see three possibilities that if we put one here or two or three then the tree will be very long but you must have understood the gist of what we are doing. We are fine, so whenever there is such a tough question, the best thing is that first look at the example like I showed you the example here, then I noticed that I am looking at the option on each index, first put one or So then you are seeing by putting 2 or you are seeing by putting tha, then it means that I got the idea that a tree diagram will definitely be made. What is a tree diagram? In a tree diagram, we only see the options, what is the option in this index, three. There is an option, what is the option in this index, so the tree diagram is about right all the options, that is why the tree diagram is the best, so according to the story and tree diagram that we have created, our code will be, see how simple it is going to be. Well, this was not a tough question, you just had to catch one or two things, if you catch them, then this question will become very easy, so see, let's start, I had said first of all that whatever index I will start from zero, so this is my index, okay. And after that what I said was that my search cost or the length of AIS or the length of the increasing sequence is fine, what is that, so in the beginning its length is also zero, I name it search cost variable, this is a better name. Ok, it should be of search cost only, I had talked about search cost, I had said, what is my max value till now, so the max value in starting is given in the question itself. Remember, it was mentioned in the algorithm above, what is the max value in starting? If you want to keep -1 then it's ok, -1 then it's ok, -1 then it's ok, I have kept -1 as the max value in the beginning, ok so I have kept -1 as the max value in the beginning, ok so I have kept -1 as the max value in the beginning, ok so what is my variable max so far till now I have seen this much max, ok if you keep zero instead of -1 then it will work ok if you keep zero instead of -1 then it will work ok if you keep zero instead of -1 then it will work ok now Let's start our solve function is going to be very simple int id one right now I am at zero int what was this int search cost better name of the variable is int max so far okay now look pay attention I said that I When will I stop? Look at the trace diagram here, when the index was out of bound, then it stopped. Okay, so if the ID is in, it means there are only so many elements, there will not be more than that, it is out of bound, so when do I have to tell that it is valid. Hey, when my search cos, which is exactly equal to two, then I will say that brother, I have found a way, then I will return one, from here it is ok, it is valid, you have made a valid one, and if it is not so. If it happens then return will be zero in else case S Simple S That is what is mine, this is my base case which is fine which you saw earlier in the tree diagram, now coming to father that for given index what are we what are the possibilities that we have in that In the index, should I keep inl tov or aa it, I can keep either aa len e a, I can keep any number aa plus ok, great, we will try all the possibilities, so now see if the number I am choosing now Let's say i = 1, if that number was bigger than my max so say i = 1, if that number was bigger than my max so say i = 1, if that number was bigger than my max so far, it is big, then it is obvious, what will I do, when I call the solve function, then I have to send the ID number there because I am going to the next index. Search cost plus and I will send search cost plow because it got bigger then search has been updated maximum value will be updated then and max value what will happen to me aa will happen then max so far what has happened now i is done here as simple Edge that and whatever result will come from there, I will keep adding the result here plus it is ok, it must be clearly visible till here and if it is not so then ok the element is not bigger than max so far, meaning what in the else case. I will do nothing, I will simply call id6 + 1, I had to send it anyway, the call id6 + 1, I had to send it anyway, the call id6 + 1, I had to send it anyway, the search cost will not increase, it is mine, the search cost will not increase, why because the current element that I have selected is not bigger than max so far, so max so far is also not updated. It will be max so far, it will be equal to max so far, it is okay because whatever I have is small, max so far is fine and the result that will come from here too, I will keep adding it to the result, we do not have to do anything in the result plus equal to last. The return result is a simple s that is fine and here we will take out the result equal to 0. Is it fine? The value of the result will come from every branch, after summing it we will return the result in the last. It was so simple, this is the code, ours is finished. You can memoize it, see that three variables are changing, so whatever DP is mine, will we take three variables in it? We will take three variables, we will see the value of the constant, accordingly we will take the value here. It is okay to take the value of as many dimensions as you want and since. We have memorized it, so let us assume that it is m + 1 n + 1 k + 1, so let us assume that it is m + 1 n + 1 k + 1, so let us assume that it is m + 1 n + 1 k + 1, whatever it is, it will be m * n * k, time complex will visit at max, so it is done that we will memorize it will also be solved. But remember in the question it was said that take out the module also, so we are equating the result here, we will take the module also there, the mode is ok, it is necessary, it is mentioned in the question because very big value can come and you know. This is how the mode value was defined. Mode = 1e to the power of 1e 9 + 7 defined. Mode = 1e to the power of 1e 9 + 7 defined. Mode = 1e to the power of 1e 9 + 7 i.e. 10 to the power of 9 + 7. Okay, so we have i.e. 10 to the power of 9 + 7. Okay, so we have i.e. 10 to the power of 9 + 7. Okay, so we have finished the code and also built it from the story. Let's code the intuition quickly and finish. So let's quickly code it, exactly as told, see what is important, how the solution is built, it remains to understand, now you can code it yourself, right, so what will I do, I take global variable int n to store m and k. So that we don't have to pass it again and again, let's make it n = n, let's make m = it again and again, let's make it n = n, let's make m = it again and again, let's make it n = n, let's make m = m and k = k, okay m and k = k, okay m and k = k, okay simple, I said that you write a simple solve function, okay and what else here. You will pass, starting index is starting from zero and after that, what is the search cost till now, it is zero and what is your max value till now, whether you saw mive or row, whatever you enter will work, ok int solve int id x int search. And what is the cost int, this is max so far, okay, this is the search cost. Now I said when to stop, when the adi becomes equal to one e a is greater than equal to either equal to equal then return us. But we have to find out what is the search cost of the array that I have created so far. Well, if its search cost is equal to Atlee's, then it means that we have found the correct array, then return one and if we are not able to do so, then we have to find the correct one. I made the return zero, ok after that if it is not so, if the index is not equal to A, then how many possibilities do I have for each index, either I will put one there, or two and so on, there is a possibility till M, I will try all the options. I plus Okay, so if the number I am choosing now turns out to be bigger than max so far, then it is obvious that there will be a comparison here which will become true, okay then what will I do as a result, I will call the solve function. ID search has to be done but the search cost will increase here right because aa which is max is so far bigger then a comparison will be true then the search cost will be plus aa na tha na see hey I am greater if the max value From so far, look at the search cost, it is getting plowed right, so look at the search cost here, I have done it by floating, okay and the max so far will be updated now because aa is bigger than that, so aa, I have sent it, okay and I said. Not in the last, meaning here we will keep a variable named result, we will store all the results in it, if result is equal to result plus, this is fine and if it is not so, then there is no problem, result is equal to result plus, simply solve. We will call the ID number, we have to do it, the search cost will not increase or right because it is not big, it is ok from max so far and if it is not big from max so far, then max so far will also not be updated, it will remain the same, ok. And it is said in the question that we have to return the result by taking its module, so I define the module here int mod = 1e to the power 9 + 7 i.e. 10 to the int mod = 1e to the power 9 + 7 i.e. 10 to the int mod = 1e to the power 9 + 7 i.e. 10 to the power 9 + 7. Okay, so here Let's also take the mode. power 9 + 7. Okay, so here Let's also take the mode. power 9 + 7. Okay, so here Let's also take the mode. If the answer is very big then we will do the mode. So it will not go out of bounds. Whatever value will come, we have taken the mode here and here also we have taken the mode in the last one too. also we have taken the mode and here also we have taken the mode in the last one too. I am fine, so we have submitted and cleared it. Let's give an example of how the test should be passed, after that we will memo it. Okay, because look, the exponential time complex is going to be T. In every index, you are trying M possibility. Okay, here it will be A. Okay, that means I am saying that. Without memorization, time complexity is very high. Its exponential is not. If you are trying A possibilities for every index, then anyway, what will be its time complexity? The power of n will be m. The time complexity is very high. Its exponential is so look at this. If you submit it then it will definitely give a time limit sheet. Let's see yes, look at the time limit sheet. It has given us a time limit sheet. What we have to do is to memoize it. So to memoize, let's see three variables are changing. Right, our joe will be deep. Int t will have three variables in it. Okay, look at the first variable. What is the index? The value of the index is n, so that is 50. Maximum number is taken, then 51 is taken. After that, search cost is right. So look at the search cost. The maximum value of search cost can be n. So the value of n is 50 so this also becomes 51 after that it is max so far so max so far you are looking at the value of m is given as 100 maximum so far I have put 101, I have increased one, okay by adding it here memset two t -1 size of t is ok and -1 size of t is ok and -1 size of t is ok and before doing everything we will check t of if t of id one comma search cost and max so far if I have ever solved this in the past then it will not be -1 There I will simply return be -1 There I will simply return be -1 There I will simply return this value, it is ok and if it has not been solved, then I will store it here before returning it. Now see, if you submit it, then hopefully it should be accepted. You can find the Java code in my Git Hub. You will find it in the link. If you have any doubt, raise it in the comment section. Try to help or see it out. Next video, thank you.
Build Array Where You Can Find The Maximum Exactly K Comparisons
find-the-start-and-end-number-of-continuous-ranges
You are given three integers `n`, `m` and `k`. Consider the following algorithm to find the maximum element of an array of positive integers: You should build the array arr which has the following properties: * `arr` has exactly `n` integers. * `1 <= arr[i] <= m` where `(0 <= i < n)`. * After applying the mentioned algorithm to `arr`, the value `search_cost` is equal to `k`. Return _the number of ways_ to build the array `arr` under the mentioned conditions. As the answer may grow large, the answer **must be** computed modulo `109 + 7`. **Example 1:** **Input:** n = 2, m = 3, k = 1 **Output:** 6 **Explanation:** The possible arrays are \[1, 1\], \[2, 1\], \[2, 2\], \[3, 1\], \[3, 2\] \[3, 3\] **Example 2:** **Input:** n = 5, m = 2, k = 3 **Output:** 0 **Explanation:** There are no possible arrays that satisify the mentioned conditions. **Example 3:** **Input:** n = 9, m = 1, k = 1 **Output:** 1 **Explanation:** The only possible array is \[1, 1, 1, 1, 1, 1, 1, 1, 1\] **Constraints:** * `1 <= n <= 50` * `1 <= m <= 100` * `0 <= k <= n`
null
Database
Medium
1357,1759
797
foreign Target first let's read the question given a directed acyclic graph of n nodes labeled from 0 to n minus 1 find all possible parts from node 0 to node n minus 1 and return them in any order the graph is given as fall of graph of I is a list of all nodes you can visit from node I so here you can see the example one the given A1 directed acyclic graph so we have to find possible Parts between from 0 to starting node to end of the node that means uh number of nodes first we have to count the number of nodes there are four nodes the first node and the last node we have to return the total number of possible products from first to last so first we will see how to count the possible parts then later we will see how to store the path values in the array so here you can see this is the given array of one comma 2 comma three comma 3 and empty so from 0 either we can go to one or whether we can go to two from two we can go to three and from one also we can go to 3 so we have reached to the end two threes so this is the one path and this is the another path so total two paths now let's see one more example so from zero I can go to one or we can go to four or we can go to three and again from one you can go to three or two so four is the end from one we can go to four also from four we are done from three we can go to four again here three then go to four two again three two four can save One path one possible path two three four five so five possible parts are there in the second graph now let's see how to store the paths how to uh like moving further how to store in the temporary array or any array that all paths we need to return back to the main function now we will see how to store auto save the paths so first we will see for the small graph so first we will take the first node zero so here we have 0 to 3. total four nodes are there in the first graph so from indeed so in this array take the last element so this is zero so check this zero in this array in this error so 0 is 1 comma 2 so what you have to do is take each element from this and put it in there one element in like created duplicate paths 0 comma 1 and 0 comma two so from 0 we went to zero first position as well as the second position now in this area the last element is 1 in this array last element is 2. so here 1 means three here two means 3. so now append that newly new node to the old path so 0 1 3 here also you have to append it 0 2 3 so now the last element is 3 here also last element is 3 so 3 is the final node so you don't need to move further can store these both areas Unwritten back now we will see for the big graph also so we start from 0 so the last element is zero so I write 0 4 is 431 from by we got that RF by the index so take out each element and append it to the original array 0 4 0 3 0 1. so here 4 is the last element here 3 is the last element here one is the last element no four here you don't need to move further you already reach to the end so from here three is four so 0 3 comma 4 so you're done you don't need to move further reach it to the end so now this one 0 1 so 1 have 3 2 4 so to create three separate parts zero one three zero one two zero one four so here the last element is 3 in here first element is three here two here four here you don't need to move further so this will become 0 1 3 4 done no zero one to last element is to go here the two index have the three only three so zero one two three last element is three so here three in the three index we have only four so zero one two three four you can see I can go to zero to one two three two four so finally how many parts we got one two three four five total five parts we got you can save one two three four five total five parts so let's write code in Python so first I'm going to capture the length of the graph minus one now creating on empty array to store all the required parts let's add them let's write the main function FS here I'm passing the on temporary RF um if that is the last element in the temp array is equal to n that means the last element in the path is equal to the final node in the graph in that case we need to store that path so I am appending that path to the result so let's keep it path it's easy to else we take out each element uh from the original given graph prefix that we got the array from this list from this information uh we look for the index of path of minus 1 in this graph and we take out each element and add it to the path and again we re again we recursively call this DFS method so for ien graph of path of minus one EFS of temp plus yeah add the new element to the existing path so not them path plus I store here we call the function so firstly we start with the zero node so passing the first path as a zero so finally return the result now let's write code in Java so first we need to create one empty uh empty result that we store all the parts like what we did earlier before so for that list integer so stop list integer result equal to new error list we created on empty result list of list now we have to create again path also list of integer path equal to new arraylist so here we first add the element to the path so 0 is added the first node in the graph now is supposed to create one DFS function which let's start writing the DFS function private y DFS so we will be taking the graph as well as the starting position of the node so let's list off list to store the result and finally path single list so if that node equal to graph Dot length of length minus 1 now we will store the existing path into the result dot add new arraylist teacher post path just return it else you need to take each element from the graph under append it to the current path so for int node top of current node element that we are having on next you need to add to the existing path dot add and you need to call the recursively call the DFS method to find all possible parts cross then the new node current node and the result and the path finally you need to remove the uh currently added element into the path make sure in Python we did it in different way in Java we did it in different way because there are some constraints that depends on the language so in Python also sometimes we remove the element of the DFS that we use to do a lot in the graph problems so just get to know why we are removing things because we don't want to recalculate again so that's why we remove already cross check to the current element so we move path dot size of minus one so here we call this function DFS graph so starting node is zero result on the path so finally return the result so that's it for this video guys we will see you in the next 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,589
hey everybody this is larry this is me going over q2 of the recent bi-weekly me going over q2 of the recent bi-weekly me going over q2 of the recent bi-weekly contest uh maximum sum obtained of any permutation hit the like button the subscribe button join me on discord and let me know what you think about this problem uh this seems like it feels like a pretty tricky one for me uh as in terms of implementation for a medium for a q2 anyway so basically the idea is greedy and i think people can think about how to do different ways of greeting but the way that i think about it was that given these requests um i would you know the naive solution would be maybe something like okay so given okay let's say given these requests you can see that you know you put them into buckets you know you can see that there's zero one two uh and then the second one is one two three uh and then the last one is just one uh and then you can you know maybe do something like you know add more whatever right and then if you sum them all up you could see that on the zero index there's one entry on the one there's four and on the sec uh on the third index with index two there's three there's two and then one and so forth right and the greedy happens because uh you can choose any permutation you basically want to assign the biggest number to as much as possible right for example given that this is the array uh we want to get the 10 to the fourth because 4 times 10 is going to be bigger than other numbers right so that's the idea that we're working with and that's the greedy um let me know if you have trouble seeing that in the questions below or in my discord um but that's the basis that we're gonna build on uh and for me that one has a bit of intuition so i don't know if i need to explain that one more but basically you're just greedy because um because you know you could think about it like if you have a 10 uh let's say this is sorted i guess this is actually sorted but let's say you just sort it given that given a 10 um giving it to the biggest number will always be bigger than giving it to a three for example right so that's the kind of greedy intuition because you just sum up the components right um okay so given that if you just do a naive you know maybe a way to think about it is like do a naive for start and in request um for x in range from start to end plus one of course it's inclusive uh count of x increment and then we just do them sorting afterwards right the problem is that in this loop uh start and n could go from zero to ten to the fifth uh or a hundred thousand right so that means that again because there are hundred thousand requests as well that means that this loop can take a hundred thousand can one up to a hundred thousand times and this loop can take a hundred thousand times and that means that these two for loops will take ten to the ten or way too long tl years but time limit exceed is what it uh what this is equal to right so you have to do some optimization uh there are a couple of things that you can do to optimize the way that i to get it down to linear time uh or sorry and like end time is the way that i did it but um but yeah um so the way that i did is i did uh a sweep line algorithm with my uh and sweet line is one of those things that actually comes up a lot of on interval intervals and stuff like that and um especially on lead code i mean it comes up in other places in real algorithm stuff but in terms of leak code competitive uh it comes up a lot of interval stuff so that's basically what we did here so we and um if you're interested in uh you know uh sweep line algorithm tutorial let me know i might do one up at some point but for now uh i'm gonna use that premise to you know so that's your prerequisite you have to do your homework to for me to explain the solution uh and for me for each request i just keep track of the start and the end uh by adding the delta um and basically what i'm doing is you know um and actually i think you could also do this with binary index tree i was thinking about doing it that way but i just didn't want to spend too much time on binary index tree so if you want to upsell it with binary index tree um you know because i was worried about off by once ironically because i spent too long on this one anyway so but yeah that was my intuition uh so you could solve this the way that i did or with binary index tree um but the idea is that say given zero two um you know at zero we're going to get a plus one in total and then at and then it's going to go to one and then at one it's going to be you know we open two new intervals so that one will have three intervals um i guess 10 if you count this one then it's four of it okay so you want to just do uh so now it's at plus four and then the next number process would be the two and it is a minus one so two would be my uh minus one so now it's plus three meaning that only three intervals in it uh and then three is the next one to get popped off so that's going to be plus two uh also oh yeah because basically uh these things are inclusive so we actually have to i did this incorrectly so you have to do it a little bit correctly but um but the popping off is on the uh n plus one as you can see right so then in this case this one we pop up this second one for the end of interval so that's actually at two so that's gonna be two plus three uh and then same thing you pop up the two so now on the three it's going to be plus two and that and what is the plus one plus four plus two right these are the number of um number of like we look at an integral the number of intervals that are within uh that number is in between uh and then here finally you go back to zero right uh so that's kind of the sweep line algorithm um and i just do this thing where so if you know i take it given n uh request we convert it to n uh we convert it to two n uh events for the sweep line and then we sort it which is n log n so this is going to be an n log n algorithm uh we just basically do the algorithm that we talked about here but the thing that you have to do well is that okay uh so this is not a good example of this but let's say uh this is one from one to ten right well now you're going to pop off at 11 so now what i did is that i just pre uh populate the numbers in between so that for example in this case this is what we're going to uh look at the interesting points quantum and then you know we just have to populate five six uh seven and dot all the way up until 11 right so that's basically what i do here in this code uh by using negative one as a flag of some sort and then just you know doing the prefix uh copying of the previous one and then after that as we said we just do the greedy by sorting uh by reversing the sort of you know by sorting it by the count that is most um in this case for example this would be four three two one and then we just go through the entire way um in a greedy way um to sum it all up uh remember that numbs in this case of course is sorted in reverse order um and i ate a five minute penalty because i forgot the mod usually i write it out i didn't notice this but i think i was just too deep in dark because this one was harder than i expected for a q2 um but yeah uh yeah that's all i have for this problem uh oh i have to go over complexity so this is n log n because we sort once here and we also saw it in defense but everything else is going to be oh and this for example this is all banned because this literally has an n in range uh this is also o n log n but this will only uh this is a little bit obfuscated but it only has n indexes right so it's also gonna be of n uh in terms of space it's gonna be also linear uh we just create defense and counts which is uh linear in the size of the input but yeah so linear uh space and log n time uh cool uh let me know what you think about this problem i think this was a bit hard for a q2 to be honest uh maybe this for this the way that i did it and binary index uh tree uh let me know what you think i think if the request link was much shorter then it would be a more reasonable problem for q2 but uh this was a five pointer so i guess they actually graded it in that way but yeah uh let me know what you think um and yeah i'm gonna and you can watch me solve it during the contest next thank you um um hmm hmm so hmm oh hmm um oh i've got to be really sick oh um so oh my god oh and you will have this one but i forgot it yeah thanks for watching everybody uh hit the like button hit the subscribe button join me during uh join me in discord and you know let me know what you think i'll see you next problem bye
Maximum Sum Obtained of Any Permutation
maximum-sum-obtained-of-any-permutation
We have an array of integers, `nums`, and an array of `requests` where `requests[i] = [starti, endi]`. The `ith` request asks for the sum of `nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]`. Both `starti` and `endi` are _0-indexed_. Return _the maximum total sum of all requests **among all permutations** of_ `nums`. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** nums = \[1,2,3,4,5\], requests = \[\[1,3\],\[0,1\]\] **Output:** 19 **Explanation:** One permutation of nums is \[2,1,3,4,5\] with the following result: requests\[0\] -> nums\[1\] + nums\[2\] + nums\[3\] = 1 + 3 + 4 = 8 requests\[1\] -> nums\[0\] + nums\[1\] = 2 + 1 = 3 Total sum: 8 + 3 = 11. A permutation with a higher total sum is \[3,5,4,2,1\] with the following result: requests\[0\] -> nums\[1\] + nums\[2\] + nums\[3\] = 5 + 4 + 2 = 11 requests\[1\] -> nums\[0\] + nums\[1\] = 3 + 5 = 8 Total sum: 11 + 8 = 19, which is the best that you can do. **Example 2:** **Input:** nums = \[1,2,3,4,5,6\], requests = \[\[0,1\]\] **Output:** 11 **Explanation:** A permutation with the max total sum is \[6,5,4,3,2,1\] with request sums \[11\]. **Example 3:** **Input:** nums = \[1,2,3,4,5,10\], requests = \[\[0,2\],\[1,3\],\[1,1\]\] **Output:** 47 **Explanation:** A permutation with the max total sum is \[4,10,5,3,2,1\] with request sums \[19,18,10\]. **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `0 <= nums[i] <= 105` * `1 <= requests.length <= 105` * `requests[i].length == 2` * `0 <= starti <= endi < n`
null
null
Medium
null
4
Hello Hi Guys Welcome to my YouTube channel, I am Sakshi Tiwari and the media talking in today's video, Not Too Short Dress, I have already made this in the video but I think I have mentioned some points there like same size is different. Due to the size, I did not hide the highlights inside, so a lot of comments came, so first of all, this is a ribbon video, the author is that you should watch the video, the complete package, here I will tell you all the things, but at what percentage, you must be seeing the eye button on Nehru. After going there you will complete the promise, you can cut it and senior, if you have any doubt then you can also comment, Magistrate can do SP, anything else important which you will get in the description of this video, then let's start this question. First of all, understand the promise statement, I have to give two addresses, whichever is the shot, okay, both the addresses written in increasing order are sorted in themselves, what should I do, I don't have to sign medium and media and Bigg, when I ever told you that are you in the media, there is a Beatles element for me, 100 test series tips for example, I wrote two, three, four, in this case it will be the media number, so what will you do, here I came in two, it did not become 3.5. There are three people, came in two, it did not become 3.5. There are three people, came in two, it did not become 3.5. There are three people, okay, so this becomes your medium, okay, so they are even length, so what do I have to do, lack of medical treatment, whatever, if you like me, subscribe, click here, then here now school accused, so you One to three do appointed - let me call it - let me call it - let me call it I want any1 211 decrees I want that and by 2 and by two minus one want the means of both of these okay now school subscribe in subscribe you get this absolutely little bit of different size I will tell you the difference here: Subscribe to my channel, like, comment, subscribe, appointed, so this is the second thing, it would be good if you gave me such a method, so if I tell you one such method, it will make it clear to some, then whatever small elements class you do, then this is my This Meghnad small-small 295 subscribe 31-12-12 small hole 31-12-12 small hole 31-12-12 small hole so like this in this way you can make it and second subscribe that so I know I will tell if I want this so this is posted here If it is there then I want it Non 250 Miles 443 in Third Induction Forces I want it here Saurabh so want it carefully Okay will appoint Ni 1234 1969 Subscribe Now make it work in easy way Subscribe Close the settings Okay Subscribe Refill Appointment of appointment here we have appointed fan 570 here from 4.5 when you will be country for, 570 here from 4.5 when you will be country for, 570 here from 4.5 when you will be country for, whatever element subscribe small element subscribe you want then subscribe can absolutely make it here. But you can search a little here, put your mind to the fact that the work we have done here, now you use this story and now here it is required, it can be of different size also, so here we said that these were the same. Do clear time travels. Okay, you do complete travels to IMG. If I say that I can solve time message in Log Earth, okay, you will get it, I can do it from where in the picture right here, so for that we have to Tell me a little back history to clarify this question. So let's talk about Steve Jobs. He is soon to be appointed. Till we divide this part into two parts, the numbers are correct from both the sides. So as I have told you here, I tell you that the total number is After subscribe and this side means subscribe this channel, like this, remove this, reduce the element, add one new element, move it back and forth, two means, what I want to say is, how did you know the cut is correct, okay, so the condition here. To me that this is a shot in itself Hey should see the element will always be small enter because hey it is sorted then all these limits all these romantic will be small okay let's meet here let's talk about this whatever is yours is smaller than eight 1968 If all these elements of the elements are small then this condition will be satisfied. According to me, these elements are bigger than these. In this way, the elements are appointed by noting the smallest ones. Okay, this means, look at this, the people of the house will do this among themselves. Now this small appointed I do not know that I am this small, this brother I am this big and small, what am I, okay, so the condition is, what are you seeing here, it is absolutely perfect, it remains difficult because If for it's small, understand this thing, this is sorted. 4854 It has become small according to this, Nishith, already it was small, understand this thing, okay. 6 is already small, if smaller than this, he has become small this whole week, okay means if I am calling it left right left calling it fat, this is mine, this is my condition, it is domestic, you have it is okay, because the albums are definitely going to be smaller than R1, the next day, equal to two, why brother, here, now, if you write here, then a little bit. Let's show the problem by writing it here. Okay, here is one, here is the add. Festival, you tell me, you have two elements, 838 problem. If you get appointed, then it will be very clear to you. Okay, I have to make a ticket to make the cut and make the cut from here. Album mid-2012 Now we will mid-2012 Now we will mid-2012 Now we will cut it, now it is going to be fine here, now I am going to tell you how to understand subscribe here, I can find it completely, I can put an element here and you will have to put gas in the other one. Subscribe I know how much is the total payment here four wash four here Enrique 1280 means end drop you need such media Zachary divide its length 1568 e left the mid day meal will be that will be Now what does this have to do with this thing okay now I tell you That's what I have taken this to you Total how much do you need Appointed that I have picked up three Okay hey do it With this condition will this cut Will have to you Melt tattoo My is smaller than thirteen This is your L1 This is aa one Okay Is this two this is this to do subscribe camera eight this one 24 no okay I have to make this point bigger than this point big how will you do this business set this line here by big limited second what if what would have happened Pattu now here But by supporting the second element, you will have to get the element for the second one here. Okay, my channel subscribe 966996. Talking about it [ 966996. Talking about it [ 966996. Talking about it I am I am subscribing on this side, here I am definitely coming to my subscribe. Iodine spider of the big element, I will need the small element. What is looking here from the side, here we subscribe, we have put the table, okay, now school appointments, subscribe here, lace for lace, okay, so we will put it here, remove it, we will keep doing the second quarter element, subscribe it, come here. That's it, now look at my first condition here - put m, define it initially, take your - put m, define it initially, take your - put m, define it initially, take your 0530 123, just do this plus minus b id 2.5, 2.5, 2.5, here I have put what you have to put on the third, okay, now we have made the border. I am understanding that four elements have become total. Now see is this cut velvet, how to is less, daily website in advance, wince in equal to how to, let's write here, what is your album, to is okay, Alto's is your eight. That's alto is your 841 is your fourth and r2 is your thirteen okay that album should also be less daily 1242 tattoo lesson 20 absolutely have a guy will daily 12818 40 be looking a little bit okay there night makes more sense I pin it up If you do, then this was yours, she is subscribing to 214. Okay, so here understand that I need a small number, I have to move towards Alto, hence Sainik Yagnik of 1281 is my first condition, if my L2 gets bigger at any time. If it is better than your R1 then what will you do on the big number i.e. take milk two what will you do on the big number i.e. take milk two what will you do on the big number i.e. take milk two plus one that now you will know that the second case has been done give advance to two then what should you do hi should be made minus one and in this case I will do it for cooperation on this thing, I need a number, okay, so I had subscribed the plug and now I have withdrawn three specials, two will be done, okay, the second feeling is 1202 places, two, then the first border will be placed here, okay. There is the remaining element for - two way okay. There is the remaining element for - two way okay. There is the remaining element for - two way into the remaining element has come to your place, now look at the border, there are four, so on this day people are doing condition to slip schedule and condition truth and both of the condition of this cycle write Baikunth se cut velvet hai ok so Your faces were in front of the element Fort 698 gap now look the length is my back China okay so here I have 8 - 134 2nd floor so here I have 8 - 134 2nd floor so here I have 8 - 134 2nd floor third and fourth ones elements of mind and here a little appointed this is my laptop give me this that war this Remedy small means maximum subscribe tours so here which is appointed here subscribe time of wounds I say maths of L1 L2 ok MOA plus according to this formula now next number forces incoming now this is the point this is this point subscribe to this point Let's do that media device Bittu is maths in forensics, what is there in subscribe 8860 subscribe has increased, okay, here it has become my size, here I have come to this and this has come, please check yours, now support. This one, this partition, now check the validity, it will remain LED, now it is velvet, which means again I want it, okay, in this way, now both of these would have been found, from here, we have said that youth subscribe here, problem, where is it appointed? But now we were talking that if it has become different, let's do the office, here I have seven Mehsoos, the size of the accused has been kept smaller, okay, this is a problem too, let's do the proof, my partition has been made here, how many limits are there in the past? These seven tours, now I have given you a limit here, this here, whenever you understand the different size, then school, this difference, come subscribe, I will subscribe here, space of quarters, create A B1 B2 B3, then okay, the above one. My everywhere below my favorite to this condition unseen element balance inquiry into to interest balance inquiry 241 Now I have talked here border comes this is my partition household subscribe this if nothing then what will I do I am subscribe for Sydney then school if My channel did not subscribe that should be big subscribe daughter next egg school value make me army larges second if mine which was this border now in school if equal first this is the sum of subscribe to subscribe button you are kind hearted sadul city max value What kind of constant is this? There will be no integer value bigger than this. Who is the one for interior dot minutes? There will be no value smaller than this. Now rest easy, what will you do in this case given here, what we have here, we end here and take an equal music. In this, now what you have to do here is what you are getting it, OK, so attitude also transaction record, that is, we will do Menon Ras, they will be done here also, main and similarly, here it is in the last, so N equal is your short. 2nd stage is fine then you border full length subscribe normal rich and engaged were going to be like this, if you are in that village then one thing to keep in mind while coding the dogs is that we will always put it on the short length ones, why is this because we want to avoid If you want index out of the box, then we both have it there, its length was taken as sim, hence we did not talk about this condition, so our everyone is Mishra, how can we install short message to SMS question, simple logic, if Rahman's length is yours. It is big in this, so here the clock is from length two, so what do you do, interchange these two, clean them, then I will call this function again and in this, number one is two, number one, pass three green chilli powder. So now whatever other number we have become, number one has become number two, the city is smaller than before so there is no problem, if we move ahead friend, if we had made utility pimples then what would we do in Indore in one hand toe, let us store its length okay. This work is done, now the next work was to make our low and high, how to make it, hello, okay, we have made it unwound on our Jio SIM, thanks to Hike - thanks to Hike - thanks to Hike - Rochelle was also in such a condition, transaction is equal to two, now we are going to stitch them or Shubhendu Party Sense and then we will check whether the partition is valid or not, how do people extract the cut bun, plus only - low white is fine, we plus only - low white is fine, we plus only - low white is fine, we saw the formula, we got the first cut, how to extract the second customer, whatever is his request - which is the first is his request - which is the first is his request - which is the first element. In the future, I will cut that many elements and will not be able to help but I will tell you that friend, I will also add a comment for whatever total required elements are required for our face, whatever we will do, who will understand that it is already present? I am worshiping them can I slide L1 L2 R1 r2 temple we will check this we will check whether we have blood or not feet if I use try operator here then whatever condition will be in it, there is a question mark here, what is alcohol here. What is a team of false condition, how to check Katwa Nagar, if you have zero, what will you do, Mian is busy in Institute of Mental School. Is it Mitthu's or again four condition, that is, we have to do something special, whatever it is our turn to cut, I heard that in the city, hmm. I am talking about nature and face, now left is always needed, now let's talk about belt, okay, so what is going to happen here we will see Kattu, cut to the front, so do it like this, whatever is number two, it is ahead. We have completed the appeal website. Similar Aryan depends on whom. If during my team time I had done that if my cut one is equal to N1 then the next piece is equal to N2 then make such a match whose number one number If it is okay respectively, then here we will remove the - number and then here we will remove the - number and then here we will remove the - number and mix all the remaining beans with the one who is there, now it is okay in its place, we have seen below, the garlic is ours, there is no problem here, now let's check - no problem here, now let's check - no problem here, now let's check - in such a condition. First of all thing is if my album has increased from my are to which we talked about the condition validate we what is the condition that our partition will be otherwise then what is this bol hai is advance grated hai natykala our partition valley near we have to type left Do this what will you do to the same people cut one minus one similarly if twice what was the second condition advance greater than R1 what will you do in this case whether to shift or not people what do you do one cut one plus one t camp now this condition i.e. That both satisfied with partition i.e. That both satisfied with partition i.e. That both satisfied with partition is our valid 2 events are declared that in one place and two mode on two equal to zero okay if my end benefit is there what thing is ready what did we have to see now I am two persons Mary Kom x minus one And we had discussed, okay, so what do we write about payment and max in m1 and M2, which is in Mexico plus R1 and r2, whatever I have written here as max is fine, I kept on writing above because I kept writing here because To Harman, my mother, you divide this second, this is the tower gate, this is our answer in double, see the return time, we have to write our www, ok or why is it written double, look at the curtain, take double here, I need the answer in the return time table, I am a balance now here. But after securing, a cute one because if the written statement above is executed then the question would have been printed otherwise what will we do below Retina interpret three tables. Whatever we get red handed is that these people prove our solution to the computer and the return is zero. Have you done this? To cross this, we are doing the above answer. This is what we have to do because we will not have to type the return of the function. Return is very angry. You will return it otherwise let's check it. You all should look here and write comments. It was left in the circle of 'It is white' Total left in the circle of 'It is white' Total left in the circle of 'It is white' Total requests Enters into a to take problems from youth Look at this This again till yesterday It has become the art of so many mistakes Let's move ahead There is no mistake here No mistake There is no mistake Look at this Katwa must have been missed a lot, I have a complaint, isn't it pessimistic 311, let's get it compiled and see, many people are submitting it. Oh, it's amazing, it will be a very fast solution. I don't care about you.
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays. The overall run time complexity should be `O(log (m+n))`. **Example 1:** **Input:** nums1 = \[1,3\], nums2 = \[2\] **Output:** 2.00000 **Explanation:** merged array = \[1,2,3\] and median is 2. **Example 2:** **Input:** nums1 = \[1,2\], nums2 = \[3,4\] **Output:** 2.50000 **Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5. **Constraints:** * `nums1.length == m` * `nums2.length == n` * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` * `-106 <= nums1[i], nums2[i] <= 106`
null
Array,Binary Search,Divide and Conquer
Hard
null
1,031
Hello Hi Guys to Ajay, in this video we will discuss 2 solutions of maximum sum of two 9 overlapping service, so before this you should remember the solution of Maximum Savere which I had danced in Maximum Savere, so that there should be unity in everything, maximum etc. had been extracted inside it. In this case, we have determined the maximum of Datun and Lighting savar, so we get two numbers inside it, letter Y, one savar should be excellent, the other should be balanced and the sub maximum of both of them should come, then tell us that maximum number. Love can play an example. At this very moment, we get this tex of activities and bike spent, so what was stored in the clans that let's follow this tex till the coolness, the maximum of the morning ending there, now the size that will have to be shared here is that After all, why should the size of the morning be this, how do I do that, I make it full, here the testing is of such a size as the original is important, 118 jhal and what will I support in this, now that the survey of two sizes is intact, of the morning of two sizes. Maximum how much is possible? In simple dance, we do not need to take size, so here I have to take the size. Hey which one, there are two sizes at once. Maximum, how much is possible and tell if coolness is what is going to happen here. See, here are two sizes. We will not be able to do it properly, from here it will be Allahabad, now we have to go a little till here, we have a torch light, what will we start or till the second, where is the macrame of survey of two sizes, where is the maximum of survey of excise, okay, then look at the factor. What will happen is that the answer to this point is a tractor and the other actor has not brought the current two sizes of support, so the answer to this point and the morning of print excise is that in my two sectors, they are getting jobs to make their own even. Friend, two means one index before me, I had understood the purpose of survey of two sizes till 11th that if we talk about current two sizes morning, then its time is 911 and 91 except here and village, then the answer came many that this index but intact maximum sum. If you light each other's torch, then this is the next process. To read this, first of all there is some basic in 3DX. Tell me what is the maximum of survey of two sizes till you, I have told all that but do good friends, share this video. Then news will do macrame episode of both now set if this next current 220 morning kasam five first 11 got reliance batter it will kasam hoga 30 minutes batter swear 911 under centimeter in here till now subscribe friends subscribe so I will get it here So let me tell him what mistake you have done inside it, what has been stored in DP-1 form, stored in DP-1 form, stored in DP-1 form, 200 maximum months that the excise was in the morning, the state is intact till this is intact, how difficult is the maximum of the time of excise, Ajay is fine. Now I do something completely different that I make another one and in it I will answer the survey of A and the same size Bachchan will have right toe left school at night will have toe right toe left Will have pictures 12345 783 Okay, so how much is the maximum possible of survey of three sizes Come let's think till the last, leaving this thing, if the torch light presses it then the right to left process will happen, here also it is done from the excise program, this is the same 12 size dharua on one side, okay, so from here we set. The first Indian literature that will be made in the morning is that I want to make it black from last year, start setting the element again till the last that you are leaving the light, I had to tell me how much is the maximum possible for Wise's survey from here till the last. This is to tell that they call care of plus one then give your answer that from your front to toe till the last how much earlier is Poison America Maximum. Okay then he said seventeen is possible and that I told a wise yesterday morning which is the current He is going to be dog container that 2017 factors, this current size is morning, so the team is finished, but we break the maximum of 1718, so let's move ahead, there is a sector-18 here, the so let's move ahead, there is a sector-18 here, the so let's move ahead, there is a sector-18 here, the second test is going to be held, this is you. Plus One Considers 11:00 You will make both of them go to office together Next go ahead Plus One Considers 11:00 You will make both of them go to office together Next go ahead Security in Mexico Let's go ahead now here we see the security [ __ ] Possible, we [ __ ] Possible, we [ __ ] Possible, we will factor in lighting and the second factor is the size of the current. It is time to swear that possible is now 12, so set both of them to the maximum, ok, and its sexual intercourse will be possible. 12, so my answer is not going to be added here too, ok. So here, if I had asked you if you got your test done in Deep into Five, then what was I going to do about it, this DP was not one shortcoming of deptt. From where to fast if from till last till then last updated on how many times it has been accepted and what is the maximum of survey of the website in it yes just now the gas word is fine now what am I going to do that I am till here Read the excise carefully. I have till the first rank but the maximum possible of excise in the morning is fine and the withdrawal from the skin is like poison till the second last. How much is the maximum possible for me, then a world tractor will be made for me that I am fine here. Till the maximum time label and right in the maximum wise beach America 89 I go now ok let's go one step further then I will ask the result till the second on the second step plate it what is the maximum time of survey of conductor excise that asked him the second question that Price till 3DX last, how much is the maximum possible for your face? Okay, so the second battery is 1118, the third vectors is 1118, max level meeting is next 1172, so from here I am going to get the answers from the maximum level, which is correct but which case have we seen till now. Has it been considered or why am I not considering which gas? We have only seen that the excise comes first and after that there is time for the wise. We have not considered the second possibility that it comes first in terms of size. Come and after that is the dawn of excise. Here the answer to the survey of excise is right from the left. Right as America is the answer. If you write its code then what change has to be done in the second one. You will have to remind us as how correct that change will be. Correct, finally, this is the answer to get a tractor from here, 1 inch from here, one side of both of them are made from the plan. Correct, bring this approach and complete it. I remember you first in the village, this is a DP. How many sizes will you make in it is of these sizes and I have prepared the dip * also and if I make it like this, then and I have prepared the dip * also and if I make it like this, then in 2017, let's make the torch light under pressure, now I will have them together in the name, first delete the recipe of 150 What cooked it intact till the morning of the excise maximum set up I loop it from the ends day waves were there so read carefully on the condition here that if you only stay less than one then I will do something else the doors are something else I make you time and flat and also on top of na tp profile I time only high and do i labs seem that right now you have not excise officer they consider 11 - you will cancer on them for the first time box 11 - you will cancer on them for the first time box 11 - you will cancer on them for the first time box adnan sami i saved Get it done means ask in this way, understand here, send me what thing I have broken here and here also I am going to get 0910 done but cancer will be done from here till here, now sorry from here till again let's go loot that If wise or other wise what should I do? What should be the president within this time? The morning of current excise should be cancer, it should be in the evening. Okay, within this time it will always be there. If it was the morning of current excise, then how to remove infidelity. Unmute the phone and remove the child with ad-apps from it. Unmute the phone and remove the child with ad-apps from it. Unmute the phone and remove the child with ad-apps from it. Excited toe was that you closed the next one once and strangulated from here. Okay excise key will remain torch light after that on top of DP-1 form of eye. torch light after that on top of DP-1 form of eye. torch light after that on top of DP-1 form of eye. You run and ask this Madam Acts of Tipu 15115 - That commission Tipu 15115 - That commission Tipu 15115 - That commission was given till before the match or how should we do the window that we have prepared the electrolyte that what will be the maximum of excise in the morning, now we have to go right to left or yagya deep into a yes Brother's value, I started - 1304 people yes Brother's value, I started - 1304 people yes Brother's value, I started - 1304 people came here - - If here the value of I Plus app or I Plus Y becomes big - 101 - 101 - 101 ok then I will do something else, I want to leave this place and make noise on the village and this condition. See the festival here on YouTube, they were only there, okay, right to left, that means nothing special was done here, or how about this, here you save 090. I will work on the computer like this for hours, so here I am not thinking about anything, I will keep adding time and making him busy, okay, and till what extent, I have to think about it, I will vary, their value is 900 I must. Be greater than A 110 - Voice 102 and you are like white bread, tight here, I will give you 8 plus three, leave the great end symbolism and come and emphasize with OnePlus 6, now it will not be here, 9th in fact here and 206 Plus Reel Is Note Debit Willing That Such Plus Sized Nickel You En Co Tight Member Condition What Will I Do In This Case Simply By Adding Mommy Go All The Solution And That Tarak Get This Amended So That If Wife Is I Will You From Time If you had to remove it, then you unmuted the affair of both of them and removed which i- removed which i- removed which i- plus vessel from the right Vrindavan pregnant side by taking the window, this was the brother, after this you said that one guy was removed from here whose size and amount were That TTP is two, I do Play Store over coffee, I come to give a tip, top five plus one man, from youth, brother, tell me, I will come back to you, morning 's maximum is sankirtan or do the current 's maximum is sankirtan or do the current 's maximum is sankirtan or do the current window container that it is to the first group from both sides. Do n't forget to do zero. Now J, from where to select the value for your answer, where to set the value of I, remember that you did not chart with the heroes here, it is very important that you did Act - 178. very important that you did Act - 178. very important that you did Act - 178. And then after coming here and stayed here, I am writing to you by speaking, so try to understand that I have started X minus one in Delhi, the answer to Nice Add Minus Plus was relief from team advection, constipation was removed in one witch, only pick up DP-1. Form and in one witch, only pick up DP-1. Form and in one witch, only pick up DP-1. Form and deep into five plus on that TP one of I to tips to that IPS and that your So which gas survey have you done now, the first of all of explain is in one Ireland subscribe on the left, its reverse is also possible that If the leg comes first, then after 1 hour it can be reduced, it is quite possible, so now we do not need to put much effort in it, support your copy, put brother in place of OLX, the pass will start coming in place of brother, whatever we want, then come - brother then come - brother then come - brother that And i plus We don't need to re-define here too, let's We don't need to re-define here too, let's We don't need to re-define here too, let's run yours tomorrow morning working fine he tried to submit jhal ok Justin now let's fry submit jhal chick to done submit main partner there is only so much Rao inside this cord that DP -1 What is going to start in the form, is only so much Rao inside this cord that DP -1 What is going to start in the form, is only so much Rao inside this cord that DP -1 What is going to start in the form, these facts are not taken here in the comment and DP One OA iPad, what are you going to store, which you can do maximum, I am Jai Ho in the morning, Om size Please tell me what you got stored on Deputy to High, Max all this morning that you are size by 26 and Intact where will you start the run from, come from, this ad and Ullas Tracks is a fact and then this is a complete copy paste of this. So which gas is it turning on, the answer to the first case will be first, then that is the length, how it happens, first you will get it, then you want excellent, correct, then copy paste, completely pure, healthy nails and that there should be pollution. Do you understand that one? Once you submit it yourself, try this, let's meet again, maximum sex scene in the election video and but correct in the morning, ok good night, thank you very much.
Maximum Sum of Two Non-Overlapping Subarrays
add-to-array-form-of-integer
Given an integer array `nums` and two integers `firstLen` and `secondLen`, return _the maximum sum of elements in two non-overlapping **subarrays** with lengths_ `firstLen` _and_ `secondLen`. The array with length `firstLen` could occur before or after the array with length `secondLen`, but they have to be non-overlapping. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[0,6,5,2,2,5,1,9,4\], firstLen = 1, secondLen = 2 **Output:** 20 **Explanation:** One choice of subarrays is \[9\] with length 1, and \[6,5\] with length 2. **Example 2:** **Input:** nums = \[3,8,1,3,2,1,8,9,0\], firstLen = 3, secondLen = 2 **Output:** 29 **Explanation:** One choice of subarrays is \[3,8,1\] with length 3, and \[8,9\] with length 2. **Example 3:** **Input:** nums = \[2,1,5,6,0,9,5,0,3,8\], firstLen = 4, secondLen = 3 **Output:** 31 **Explanation:** One choice of subarrays is \[5,6,0,9\] with length 4, and \[0,3,8\] with length 3. **Constraints:** * `1 <= firstLen, secondLen <= 1000` * `2 <= firstLen + secondLen <= 1000` * `firstLen + secondLen <= nums.length <= 1000` * `0 <= nums[i] <= 1000`
null
Array,Math
Easy
2,66,67,415
1,064
all so this question is fix point so you are giv the integer array in ascending order so return a small index I let's satisfy the array I equal to I so if there's no such index netive one so you know this is stra for enough so let's look it is uh this is uh the integer array so uh what we are doing you know traversing the uh integer rate based on the index right this is zero one two 3 and four so we just compare the index with the value are they equal no call equal no and three equal to three right so this is the first value which is considered the smallest value and so this is pretty straight for you now so return negative one if you cannot find starting z l i++ so if I isal to I starting z l i++ so if I isal to I starting z l i++ so if I isal to I return I so for example this one is actually zero 0al Z so OPP should be Zer so let's run it submit all right time and space is pretty straightforward this is time all of space is constant now allocate any space so this is solution yeah see you next time bye
Fixed Point
smallest-integer-divisible-by-k
Given an array of distinct integers `arr`, where `arr` is sorted in **ascending order**, return the smallest index `i` that satisfies `arr[i] == i`. If there is no such index, return `-1`. **Example 1:** **Input:** arr = \[-10,-5,0,3,7\] **Output:** 3 **Explanation:** For the given array, `arr[0] = -10, arr[1] = -5, arr[2] = 0, arr[3] = 3`, thus the output is 3. **Example 2:** **Input:** arr = \[0,2,5,8,17\] **Output:** 0 **Explanation:** `arr[0] = 0`, thus the output is 0. **Example 3:** **Input:** arr = \[-10,-5,3,4,7,9\] **Output:** -1 **Explanation:** There is no such `i` that `arr[i] == i`, thus the output is -1. **Constraints:** * `1 <= arr.length < 104` * `-109 <= arr[i] <= 109` **Follow up:** The `O(n)` solution is very straightforward. Can we do better?
11111 = 1111 * 10 + 1 We only need to store remainders modulo K. If we never get a remainder of 0, why would that happen, and how would we know that?
Hash Table,Math
Medium
null
334
Increasing Triple Sequence I J K Sach Date I &lt; Fauj Okay, so if I look at the first example in the morning, I did yesterday's 1 2 3 4 Okay, then if I take the three values ​​of starting, if I have these discounts, then I am take the three values ​​of starting, if I have these discounts, then I am take the three values ​​of starting, if I have these discounts, then I am satisfied I K Okay, okay and 3 &gt; 2 ≥ BP depends, right? If 5 is A B C, if I find one where the value of C is greater than the value of B, return the value greater than A. Okay, so if I Let me tell you the PSEUDO code first then I will samjhaunga try to run it okay then I will say if it is if I am driving it from zero to zero then I will say if I have any if the names of I give it a little capital okay Yes brother, meaning basically I am taking points, meaning whatever I am here, define DJ, okay, I am getting some value which is greater than B, which means I got my SIM, I am doing the driver, I got some value which is greater than C. It should be B, I am getting such a wait, do n't put it If I am getting any element which is bigger than A, basically the value which is on If it is smaller than A, update it. Complete the value of A. If it is fine than the value, then now I will try it from late. It is a simple code that if this part is understood, I can easily understand that late from A. The one that is is dependent so if I sim directly true done [ dependent so if I sim directly true done what will we keep ok in max ok so basically update me because of A and B change it like some like I got vector some like I got value There is inside it whose value is greater than 20, so I also got C, which means return it directly, we will put it in it, make it true, one more thing has happened that if my length is fine then it has become like this Okay, so I will check, you do it, okay, now I have to increase the next station from zero B. Okay, so what will happen here, I will check here, now I will get it in the next bar, so what will I do first, okay otherwise check, its big, its value is big. It means I got my B. Okay, let's take that equation, let's run it and see. Okay, submit it, let's see I think it's clear.
Increasing Triplet Subsequence
increasing-triplet-subsequence
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`. **Example 1:** **Input:** nums = \[1,2,3,4,5\] **Output:** true **Explanation:** Any triplet where i < j < k is valid. **Example 2:** **Input:** nums = \[5,4,3,2,1\] **Output:** false **Explanation:** No triplet exists. **Example 3:** **Input:** nums = \[2,1,5,0,4,6\] **Output:** true **Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6. **Constraints:** * `1 <= nums.length <= 5 * 105` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
null
Array,Greedy
Medium
300,2122,2280
1,035
hello guys welcome to deep codes and in today's video we will discuss liquid question 1035 that says unclose lines although this question looks hard at a first time but I am sure that after watching this video you will find this question is super simple Yes guys this question is not that hard it is very much a type of fundamental question that is uh already there or you might have already solved in the past right so this question is very much similar to one of the most famous question from the lead code and we will derive the approach and Link the question right so yeah guys watch till the end and make sure to like the video subscribe to our channel so guys here you are given to integer addendums one announce to and we need to write this integer array in order they are given into two horizontal lines two separate horizontal lines for an example if you have 140 nums one and one two forty nouns so like uh write this one four two in the first horizontal line and one two four in the next horizontal line now what we need to do is we can draw a connecting line a connecting straight line that connects two numbers that is number five nums of J only when nums of y equals to numbers of J that means the value are same and we cannot draw any intersecting line or any other connecting any other line okay also note that the connecting line cannot intersect even at the advance that means a number must belong to one connecting line only okay right so yeah we need to return the maximum number of such connected lines we can draw see guys connecting line is nothing but a line that connects two numbers that are same also that line doesn't intersect with any other lines so that is nothing but connecting line and we need to return the maximum number of such connecting lines we can draw okay so if you take a look at the first example now either so here you are given one four two and one two four so you can connect one and four two see guys you cannot connect two four because it will intersect so that is not possible to connect two four you cannot connect this as guys what you can do is you can connect this way also you can connect one and two so in both the cases you will get or two as the answer because there will be only two connecting lines right now if you take a look at the second example here you are given 2 5 1 2 5 and 10 5 2 1 5 2 okay so let's suppose you connect this to Phi you connect one and you connect these two five now none of the lines intersect so this is the correct combinations of connecting lines and at the end we have three lines as our output right and similarly here you will get to maximum connecting lines so guys this connecting lines concept is very much simple that we only connect if both the numbers are equal and no other lines intersect right the condition one that is very much easy to implement we just have to compare the ith index from the nums one and the JS index from the nouns too if they both are equal then yeah we can draw a connecting line but we have to make sure that it doesn't intersect with any another connecting line so how we will make sure of this so to make sure of this we will always move our pointers that is the I pointer n j pointer in One Direction Only We Won't reverse it for an example let's say uh initially both I and J pointer are at index 0 we check whether the ing numbers are equal yeah then we draw a line then we move I pointer to one J pointer to also one we check are they equal no now let's suppose we only increment ith pointer to two and we check if I and J values are same yeah draw a connecting line then we uh increment I pointer to connecting line now we again increment I pointer to 4 and J pointer to three are they say no then increment A J pointer to index 4 are the same control connecting so this is one we have to do this what if you might have done something like this so this is uh this second approach is also a valid approach although you won't get best possible answer but this is also valid approach so here in this approach what you will do you will check I and J both are same raw connecting like now I pointer comes here J pointer comes you are they same no so at that point here what we decided to increment I pointer but let's say you decide to increment shape pointer then again increment the J pointer to four are the same yeah draw a line again increment to here and I2 here they are say no then increment I to here as I say no then again increment two here are the same yeah so this is a slight mistake this with index one two three and four but I hope you guys understood that we only moved our inj pointer to One Direction or we always incremented it see what if we do decrement so let's I and J are here this initially at zeroth index we draw a line then let's say I becomes 2 here J comes to here are they equal no then move j towards the right and I to here now check four and three are the same no one this is index two this is index three move j to index 3 check they both are same yeah draw this connecting line okay now guys afterwards let's say we move our I to here J to index 4 they are saying no not same then again I index ith index comes becomes three now you will find that was n 3 in the past but at that point we won't decrement J we cannot decrement the J pointer if we would do that then this will always be a conflict there will be always be a conflict right and we don't want that we don't want intersecting lines so guys one idea you can get from here is if you move the ith in J pointer in One Direction only that is I always increment and never decrement right either the same or increment but never decrement you can all always create me or make I rather than greater than equal to I plus 1 either increment or make keep it the same but never decrement so yeah if you do this then we don't have to check for this intersecting condition as we only move in One Direction either that is always increment or stay wherever we are we don't move reverse right so yeah in that case there is no need to check for intersecting lines right we don't have to check so here if we keep track of I and J by only incrementing the pointer that means we keep track of order of elements the order of elements is maintained right see if you Traverse in One Direction only then the order would be like something if you see here it would be like one for Norms one is where the as we did it will be one two three right it was one two three five and for Norms 2 it was one two three five but if you don't uh if you decrement let's say you decrement then the order becomes what is order changes right one four uh let's say three is your answer and your answer is one this and this so here from here to here and then the year so this order is not maintained in the nums two error right so whenever you decrement the pointer the order is not maintained but that is wrong so we will always maintain the uh sequence of our inj point of view always more than in One Direction so that means the sequence or the order of elements in the nums one as well as number will always be maintained correct the sequence of element or the order of elements will always be maintained now that is nothing but what that is nothing but a subsequence is nothing but a sequence in Adam by removing some numbers a subsequence is nothing but a sequence of an array sequence of elements of an array by removing some of the intermediate numbers right the sequence is made like a one two three and five if we can remove some of the intermediate numbers but we cannot change the order you cannot write one three two and five the sequence has to be same one two three and five right so yeah whenever you maintain the sequence by ignoring some of the numbers that is nothing but call subsequence right and here what we have to do we have to match the numbers as well as we have to maintain the subsequence right we have to maintain the order as well as the numbers that are same so that is nothing but worse that is nothing but longest common subsequence right in LCS given two strings S1 let's say S1 is ACC D and S2 is let's say a c e d so here what we do we match the characters right we match the characters and we also maintain the sequence that is a that is nothing but longest common subsequence right we find the longest length of subsequence that can be matched from string 1 and string two and here also we have to match that we need to find longest subsequence only that will be matched so uh the longest is the subsequence that many connecting lines we can get right we need to find maximum connecting lines right we need to find maximum number of connecting lines we will only get that if we find the longest common subsequence between nums 1 and numstore right let's say if the longest common subsequence between N1 and N2 that is nums 1 and number two is five then we can ah draw Phi connected lines it is simple right so ah if you try to find LCS of this array in this area you will get character or numbers one two three and five this is the LCS right of the numbers two so its size is 4 and that's why four connecting lines we can draw so overall you can say that if you find the LCS or the longest common subsequence for the nums one and Norms to get him the length or the answer of the LCS is nothing but the number of lines or connecting lines you can draw right so this question is now nothing but to finding the LCS between Norms 1 and nums two now guys if you have idea of how to calculate else or how LCS works then I recommend you to try out the question from yourself right afterwards the question is very much simple from this point right we instead of drawing the lines we have boiled down this equation to nothing but finding the LCS between Norms one and Norms two clear tilio now how we find the LCS is nothing but a dynamic programming equation where we have choices so what type of choices we have so let me take the same example right one four two three five and above one four two three five and one two three four five okay now suppose our ith index is here and jth index is here they both are pointing to zeroth index and the number matches so if the number matches of both the index we connect the line and increment I pointer to the next engine pointer 2 also to the next okay now we check if the number matches no the number doesn't matches so from here we have two choices either we can increment the I this is Choice One or we can increment the J this is Choice 2 right either we can increment the I or we can increment the J and see we have already covered these two choices if you increment the I pointer to the next now from 1 to 2 then you will get four different connecting lines right if you go uh process with this approach but if you proceed by this approach of incrementing the J pointer you will only get three so that's why we have to take care of both the choices and figure out which will give the best possible answer right which will give the best possible answer so this for this we can write a recursive code where we will take care that if nums of unums one of I equals to nums two of J if this is the condition if both are same then nothing but return one plus solve I plus 1 and J plus 1 that means increment both the pointers and in the else condition what we will do will be return maximum of solve nums one nums two I plus 1 and JJ remains as it is and comma solve nums 1 Norms two I remains as it is and increment the J pointer see these are the only two choices we have if the number doesn't match either increment the eye point or increment the J pointer because we cannot decrement we can increment one of them right but we cannot decrement if we will decrement then the airlines will intersect at some point right and that we don't want so the only choice that we have remaining is to increment and whenever the numbers doesn't match then at that moment we can either increment the eye pointer or we can increment the J Point all right the same thing we do in the LCS the longest common subsequence between two strings the same choices that we have in the same code we write over so guys I hope this the approach and the intuition Parts is very much cleared now moving on to the coding part so the coding part is also very much simple now we took the memorization to DDP Adam and call this all function then we check now for this base condition that is if I is greater than numbers one dot size or J is greater than I'm still that size then written 0 that is out of bound then we check if the sub problem is already computed or not before this our problem we have already checked then return the answer directly now we will check for this condition that if nums 1 of I equals to nums 2 of J that means both the characters or the numbers matches then in this situation simply add one because we can draw one line right if the number matches we can draw one line and call for I plus 1 and J plus 1 right call for next two indices and in the as condition take the maximum of either incrementing the J pointer or incrementing the eye pointer we are two choices we can either increment the J pointer or the eye pointer we can never decrement this right so yeah take the maximum of both of them and at the end return the current answer right so yeah guys this way we can solve this equation not talking about the complexities the time complexities here is nothing but big of n into m and similar is the space complexity and here n is nothing but the size of norms 1 and M is the size of norms 200 mm so this many times this solve function will be called because here we are using this memorization 2dp and this has this 2D DP has this many number of cells okay and space complexity would also uh we have to also take for this saw recursive function so we have to take recursive stack um we have to consider the recursive stack for our space complexity so yeah guys that's all for this video I hope you guys understood the intuition as well as the approach part right if you guys are still any doubts then do let me know in the comment section make sure to like the video and subscribe to our Channel thank you
Uncrossed Lines
cousins-in-binary-tree
You are given two integer arrays `nums1` and `nums2`. We write the integers of `nums1` and `nums2` (in the order they are given) on two separate horizontal lines. We may draw connecting lines: a straight line connecting two numbers `nums1[i]` and `nums2[j]` such that: * `nums1[i] == nums2[j]`, and * the line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line). Return _the maximum number of connecting lines we can draw in this way_. **Example 1:** **Input:** nums1 = \[1,4,2\], nums2 = \[1,2,4\] **Output:** 2 **Explanation:** We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from nums1\[1\] = 4 to nums2\[2\] = 4 will intersect the line from nums1\[2\]=2 to nums2\[1\]=2. **Example 2:** **Input:** nums1 = \[2,5,1,2,5\], nums2 = \[10,5,2,1,5,2\] **Output:** 3 **Example 3:** **Input:** nums1 = \[1,3,7,1,7,5\], nums2 = \[1,9,2,5,1\] **Output:** 2 **Constraints:** * `1 <= nums1.length, nums2.length <= 500` * `1 <= nums1[i], nums2[j] <= 2000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
102
1,466
let's solve leak code 1466 reorder routes to make all paths lead to the city zero so this is obviously a graph problem we're given n nodes or cities numbered from 0 to n minus 1 and we're given n minus 1 roads which are the edges in this case so the first thing to do is understand what the problem is telling us so the problem tells us that there's only one way to travel between two cities so basically what that means is that there's no loop inside of the graph so for example if I had three nodes 1 2 3 I had one edge going this way where can I put the second edge because we have three nodes so we have to have two edges can I put the edge over here no because that violates the condition can I put the edge over here no because then that's a duplicate edge so I have to put the edge over here or put the edge over here so the two things that this tells us about the graph is that there's no loops first of all right so there's no loops in this graph it also tells us that the graph is connected because we have n minus 1 edges and if we can't put them and if we can't create a loop with the edges then that means we have to connect all of the nodes together once you can recognize this the problem becomes a lot easier so the next thing you want to do is draw a picture because that makes it a lot easier for you to visualize it I've already done that over here so let's start looking at the problem so we want every node to be able to reach 0 so the first logical thing to do is look at 0 right oh and just look at its neighbors right just let's first see if its neighbors can at least reach 0 let's first look at 4 can obviously reach 0 we have a direct edge going from 4 to 0 so we don't have to do anything there but what about 1 there's only one edge between them and that edge is going from 0 to 1 so we have to change this node right we have to go back to 0 from 1 so now we at least know that all of the neighbors of 0 can reach 0 right so we've checked one and we've checked 4 but what about all of the neighbors of four for example right can all of fours neighbors reach for because if we know all of fours neighbors can reach four then all of those neighbors can reach zero because we know four can reach zero so let's check if fours neighbors can reach it only has one neighbor five and five can't reach four so we also have to change this edge now we know that five can reach four and four can reach zero so these nodes can reach zero what about fives neighbors well it doesn't have any so let now let's go back to one we know one can reach zero but can one's neighbors reach zero it has one neighbor three and it looks like the edge is going from 1 to 3 so we have to change this edge as well so now we know that one can reach zero and 3 can reach one so therefore 3 can also reach zero but what about threes neighbors can they reach 3 only has one neighbor 2 &amp; they reach 3 only has one neighbor 2 &amp; they reach 3 only has one neighbor 2 &amp; 2 can reach 3 so we don't have to change any edges but what about all of twos neighbors too doesn't have any neighbors so we don't have any more notes to visit now we've determined that every node can reach 0 we did this sort of recursively or propagating changes right first we wanted to check for starting at 0 can zeros neighbors reach 0 ok if zeros neighbors can reach it can their neighbors reach it that next layer we're checking right we're checking 3 and 5 and then if those nodes can also reach 0 can their neighbors reach 0 we check the next layer and there's only one node there only 2 right so it's kind of like a breadth-first search a breadth-first search a breadth-first search we're just propagating outward to seek to change all outgoing edges right we want every edge to be pointing back in the direction of 0 with this traversal we only have to visit each node once so we can say that the time complexity of this is Big O of n so now let's get to the code before I start I like to write some comments just from self what to do so remember we're going to start at city zero and we're gonna recursively check its neighbors and we're gonna check that the edges are if the edges are outgoing we're going to count them we don't actually have to change them in this problem that's not a requirement we just have to check the number of outgoing edges that exist so this problem gives us a list of connections but we want to instantly be able to check if node a or city a can reach city B instantly right so let's make a set to do that instead of an array right I'm going to use set comprehension and Python to do that so I'm basically getting each connection adding it to a hash set next we want to know each nodes and neighbors not if we can reach that note itself we want to know any adjacent neighbors of a node so we're going to use a hash map for that again we're gonna use comprehension to do that so a dictionary comprehension for each city we're gonna have an empty list initially we also only want to visit each node once so that we have the most optimal solution so we're going to use a hash set to keep track of visited nodes also we just want to count the number of edges that we have to change so we'll just use an integer to do that next we're going to fill up our neighbors hash map so in this case the neighbors of a includes city B and the neighbors of City B include City a now we want to write our function to actually traverse the graph you can do this a bunch of ways iteratively a recursively depth first search breadth first search but I'm going to do this step first search recursively to make it most convenient I'm going to use a non local variable so I don't have to pass them into every function call so for each city we want to iterate through each of its neighbors right so we can do that pretty easily if the neighbor itself has already been visited we don't want to traverse it again so we'll just continue to the next iteration to the next neighbor so next we want to check if this neighbor can reach city zero so the way we can check if this neighbor can reach city zero is simply by checking if the tuple neighbor city exists in our set edges if it exists that means the neighbor can directly reach the city that we're currently at if it's not in this set that means that the edge is outward so we have to change this edge so we have to increment our count once we visit a neighbor of course we have to mark that it's been visited so we don't visit it again lastly we have to recursively run depth-first search on this node because we know that this neighbor can now reach city zero but we want to check that this neighbors can also reach city zero or basically propagating the changes lastly we want to actually run our depth-first search function on run our depth-first search function on run our depth-first search function on city zero of course because that's our starting point but we also have to remember that we have to add this city as well to our set to mark that it's been visited lastly all we have to do is return the total number of changes that we made we don't actually have to make the changes themselves oops I had a couple typos I use the plural of neighbors instead of neighbor you want to make sure that you don't have typos like me and then let's resubmit it and make sure it works this time yep beautifully so these are the steps you can take our time complexity was Big O of n because we're visiting each node at most once our memory complexity was also Big O of n because we have a bunch of data structures we're using edges neighbors visit but we're only going to have each node or each edge in these data structures at most once so it's going to be proportional to n
Reorder Routes to Make All Paths Lead to the City Zero
jump-game-v
There are `n` cities numbered from `0` to `n - 1` and `n - 1` roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by `connections` where `connections[i] = [ai, bi]` represents a road from city `ai` to city `bi`. This year, there will be a big event in the capital (city `0`), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city `0`. Return the **minimum** number of edges changed. It's **guaranteed** that each city can reach city `0` after reorder. **Example 1:** **Input:** n = 6, connections = \[\[0,1\],\[1,3\],\[2,3\],\[4,0\],\[4,5\]\] **Output:** 3 **Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital). **Example 2:** **Input:** n = 5, connections = \[\[1,0\],\[1,2\],\[3,2\],\[3,4\]\] **Output:** 2 **Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital). **Example 3:** **Input:** n = 3, connections = \[\[1,0\],\[2,0\]\] **Output:** 0 **Constraints:** * `2 <= n <= 5 * 104` * `connections.length == n - 1` * `connections[i].length == 2` * `0 <= ai, bi <= n - 1` * `ai != bi`
Use dynamic programming. dp[i] is max jumps you can do starting from index i. Answer is max(dp[i]). dp[i] = 1 + max (dp[j]) where j is all indices you can reach from i.
Array,Dynamic Programming,Sorting
Hard
2001
1,040
10:40 moving stones until consecutive - 10:40 moving stones until consecutive - 10:40 moving stones until consecutive - on an infinity spare time and finish an infinity of number line the position of IV stone is given by stone survived for stomach and stone endpoint stolen - stomach and stone endpoint stolen - stomach and stone endpoint stolen - there's smallest or largest position each turn you pick up a endpoints to move it to an unoccupied so that it's no longer an endpoint stone in particularly over still misses that one two and five can now move to M points at position 5 since moving into any position will keep time stone as an endpoint stone the game ends when you cannot move any economic any moves I eat the stones and Canseco positions when the game ends when is the minimum and maximum the moves you could have made we turn it over the answer is and away just returned the engine somewhere okay we have to use what is honored I've stone okay as to smallest and largest precision so isn't before end point stone can now move down stone at position 5 okay maybe there's a time suture understanding the problem but just one it's enjoyable okay well 125 can now move five because it doesn't change it and unoccupied its position why can't you move to five to zero or something like that oh well actually tells you okay so the one and two are done no God does this matter that don't put down the weird way still trying to figure that out like why would you just not sort it hey we're just sorted right okay well yeah I speaking about giving Proctor to prom yeah okay yeah first of all I would just sort to input it's kinda cheap so like now you can think of things for about kind of worrying about I don't know weird edge cases in general and n is ten to the fourth which is ten thousand I suppose 100 now is ten out of it a big banner that well max move is me from tears a weird one please end point okay I mean right now my head is just thinking it still is there a pattern that I can kind of abuse and clearly the answer is if all the answers like or everything is already good and that it's zero so three to some food okay five to nine they said you always want a result to be or consecutive that's when the game ends well I guess it tells you that so points for me for reading but so what's the minimum I guess that's two problems one is the first wants to minimal I feel like minimum is a little easier it's no see like my pen so I check if I just visualize this a little bit I could destroy more ascii i p-- so three four destroy more ascii i p-- so three four destroy more ascii i p-- so three four five six ten the shortest will be so just ten to the four five H that's too much to do anything given n square so and this is a little bit of a metal kind of thing but well and again will probably be okay I mean an organ is definitely okay it's just I don't know how many albums is are there will be requiring and like and that something so it's probably gonna be something than the ish after the n log n so it's poised some sort of greedy ish there's a tricky case to get the minimum even because you normally you were just like moved to ten to the seven but I got that's fun but in this case you actually cannot move ten strong so it's to middle why don't you have to set up essentially like Islands three to the seven this is also quite like it give you like a way to make sense but it might not be the way that you need to construct I think so given these I think the way that I would actually move it minimally it's actually moved to sex to accommodate the number is that I needed so in this case you only need a ten so you create one space with two six it's not a six anymore but it's six tier and then you put ten into old sex this is ten and then this is now sorted kind of or these are now consecutive right and you could and my conjecture is die if you have the longest island of consecutive stones so let's say you have you sent rate this for that to say eighteen sixteen seventeen you still well in this case maybe that so you would move six and then create three spots say and then just move fifteen sixteen seventeen and obviously even if you have more numbers then you just do that way like create more space so then it always going to be essentially your minimum move may just be a function of your longest consecutive thing that's my guess for the greedy minimal yeah there may be a real edge case that may be the same where like I don't know like eight nine ten cuz then in this case you want to make space for three things six seven eight nine so you move your six here but it's technically on a ninth position so you can't what would you do then for the minimal well I guess in that case if the nine already exists then we don't even have to move that for the minimal because then we're and the nine already exist and we already will use the nine as the end point and now we don't have six and then eight is ticking and then ten is here so actually I just I don't bring one move so okay so I think for minimum you would create that number of space and then the number of movements will just be the stuff that's after that and I move it into that slide I would say and now and we have to also consider the case of yes it could be negative technically I'm into somebody matter and then you have to consider a case where there's numbers on both sides I appeal five six say there's a lot of things to consider I think actually though what ends up happening is there some kind of growing window characteristic maybe so you let's say you want to keep the core together right so but maybe that's not sufficient but oh actually that makes sense now that I think about it okay I think I have a better formation of what I want to do now that I'm kind of analyzing this farm way too much they say you have with ten numbers now that's nine numbers so you're just to a rolling window starting and then just count and then it's usually math to do the rowing window on those numbers to calculate how many things are already in place and then you move out of it for them something like that and then just do the math maybe something like that I'm gonna really hand wavey to be honest because I know they say like for example this has seven so you know that let's say you're in this show thing you have to be really smart on this rowing window so you can't just like your dad naively or like you can't just have like a pool you know wait while you type thing they tricky for medium maybe I shaft on moving stones until consecutive one first but and I didn't even to the maximal move yet but some in this case we know that we want three numbers two consecutive so them first we check five six seven when we know that we're going to set this one number so that means we have to move to and in this case can it even be done so current window actually two disordered so actually no I've ever said it that way start the first window that so then now we have two or three four tried that on your corner window can this even be done cuz yeah we have to go to seven two endpoints to God oh no oh whoops we can only move an endpoint stone so you some so actually maybe that actually that pie mix to form a large easier and I'm just terrible at reading because 10 yeah okay well let me think this for a second I think I just saw or tried to solve a different file for some reason I didn't move any stone and I just know this that you could only pick up a point stone that probably changes things easier but panocha I stand out for okay I start over let's say yeah four seven nine okay so now you're gonna move to for the nine so if you move to for the only place you can move to is to eight I guess that's finishes the game and you move to nine you could do it to six or seven I guess it doesn't really matter doesn't pretend then because if you move it to human sixth and like you keep on like fogging so I think you're okay maybe that's maybe I mean it's still good query so that pop the narcissist viagra me right but since we can only move to Ken's tongue man I misread that okay but then I could move to three to the seven it's the first biggest number that's not uh nothing and then four or so and then so the smallest number move is just what is the most or minimum moves because you can built it in this case you can move after three and the thing so you can you know could only moved it away I mean and you could still do that thing where you create space like I was saying but then I'll take two moves that seemed like that would have to so many edge cases that I'm kind of scared I think the consecutive pieces ride away one I feel like the maximal one now it makes sense you just keep on watching things down you look at the next number and then you just yeah can i define this mmm it's query what is to maybe that I could think about in terms of their uh suppose I mean instead of just strategy and improving it query we have these twists turns this is also like a special unique case when you're making space can I still use the rolling window concept because hmm let's say you're three to seven well this is not possible to get to from three to ten but now when we try this as your window well and now you see that we can move to three to the a and then ten to seven it's not given a reason and that's just two moves then to know now you move to 3 to the 9 and then 4 to the 8 and 10 to the 7 hmm yes that's a possible thing no I window is 10 well then it's not possible but right you have to move to Tweety - I guess you have to move to Tweety - I guess you have to move to Tweety - I guess it's possible you just move 2/3 to the it's possible you just move 2/3 to the it's possible you just move 2/3 to the 14 and then throw it in but that is so weird is it weird you moved 20 to the 13 now you went to six to the nine and then you owe it I guess my question is can you always do this in a is it always just a death like I think that's the feeling like given this yeah clearly the answer will be to is to death but and like here obviously the doofus actually impossible this is the first one that's awesome possible so maybe one before never be because you can this is the case where one move is good right 9 7 8 9 so the difference is 1 and he just kind of movements in wow I all right I think I'm a little bit lost on this one huh let me just use a hint n real quick cows and even though they're cows this might not even be the right hint today means tongues anyway this end is very hard to read then they copy this off like usako or something where they always use cows as a thing yeah don't like choose hmm man I'm doing stump a medium agreed I didn't happen in contest fit okay I mean two numbers already in place and you can move one and dump on the outside so I mean obviously this is one but I'm trying to figure out how to do the two thing - well - is YouTube four five six thing - well - is YouTube four five six thing - well - is YouTube four five six I guess hmm okay I think we may be this is Tom the edge case having that's to me where you have to do the math on and on you know you have to do the math on what Yumiko it you have to do the math on just moving one and then time protecting endpoints but the tan will not go to - endpoints but the tan will not go to - endpoints but the tan will not go to - all right you have to move you have to check dad - porn you're moving it's not check dad - porn you're moving it's not check dad - porn you're moving it's not on it okay it's that's for the lower belly Russian I mean maybe that hand was the century and print okay that's two min well first when it was my window I had I guess I should count it's ten to the fourth so you really cannot do some n square Franklin that's like ten to the eighth it's bad news okay they say which had to keep track yeah I guess actually I'm going when there should be symbol just keep track of number things that are in it okay let's just try to just do the math so then there should be so at four we want to check so we need to check all the numbers around you because then I could get to n square I guess all the numbers that are around it will always won't have one number okay so we do it that way then just keep track of the rolling window that wasn't doing it no way Oh doing it and press it away yeah well kind of this is nothing to say that is it the head of the fence is less than index of hell - stone the is less than index of hell - stone the is less than index of hell - stone the difference is bigger than n so the cost now is minimal as you go to the number of things that are not in so the number things that are in is still - the number things that are in is still - the number things that are in is still - head and then n - this may be minus one head and then n - this may be minus one head and then n - this may be minus one as well but it's a big vehicle ten okay I didn't handle that edge case but maybe now give me something to play around with I knew this is not right because I don't we turn half the answer so smoke this oh yeah because we did not handle time which we know beliefs the maximum matching part should be right I think okay so I'm school I think this thing so how do you define the case where this is not a relative or that it takes to matter what's here you could actually move I guess it's just one idea and it doesn't really matter which way it is here then clearly moved to 300 so anymore - so after anymore - so after anymore - so after and it just like the tree if it's cause the other one how do you define this corner case like just actually oops not this one mr. chilly thanks for the follow go deluxe hopefully I find to just fight response for this problem so school is you go to one I guess this only happens when square is 1 which means down there's only one thing to move way because you would have given more numbers I say this let's say we are one to it given though we are through something like this or they're not always be two anyway it's their way to get this to one hmm so this only happens the stones if this just you go to well justice you go to okay let's just put it up oh no I thought you would point out a little bit what is the state of the world okay so stands up here is seven that make sense it's at the white one no that's not the right one whoops okay so I play which makes sense and the stone your turn is six okay so that means everything else is consecutive so yes you go to a - impossible then score is you go to - impossible then score is you go to - impossible then score is you go to - because you have to do this thing six minus two years we went for four which is not a nice - fine okay I mean so I think that survey touch is very tricky with but uh okay now I do figure how to do the two max which I think isn't you know we used to handsome eyes but I put a max map to lose either the gap a - so basically either the last the gap a - so basically either the last the gap a - so basically either the last two elements or the first two elements right okay I'm that's the hint but I have to figure out why that is the case so like some always okay well let's think about it first two caps of ten and a six but that's the biggest gap and then we have three moves because people could just move to three into the gap in between so that because every other so then I guess the greediest move is to or the maximum move is to move this don't I warmed endpoints into one of the into that gap I suppose in between the first two numbers or so or the other way around and then can I keep doing it because otherwise because if we don't do anything in that gap okay it's always true yeah because then you otherwise you peel off out of the stuff and then you still need to fill it but what if you have like someone like 125 then when you've just do the nine to the six one two well this is maybe a bad example but still good too is it just like the number of gaps because so basically what you would want to do I imagine it's just actually to move a stone you either put it in one of the two places which is an endpoint and move it to the place immediately to the right of the laughs or the other way we just put it and just keep on throwing it up really there's those yeah in this promise so I know I like well I've been gettin variant Morenstein wearing tan Marion is diet given a boost all the facts so invariant is that for the maximum move well we just throw up in this case is that is it just a number of spaces because in this case we're just two one you know we'll keep on moving and then we pull the spaces and then you know take one move to we remove a space except in that case where if it's like this then you would have to move one of them first to the other side in this case yeah to here and then get rid of this edge right maybe that's what they say about a gap and then now you will finish one by one to fill up all the gaps so okay and the number of gaps is just and will not end but the smallest number my - the biggest number smallest number my - the biggest number smallest number my - the biggest number - to them and you subtract from - to them and you subtract from - to them and you subtract from that to the smaller of the gaps between to the left and the right end point that pie makes sense okay well what a crap okay that's a max most much worth what we say so - so that's the worth what we say so - so that's the worth what we say so - so that's the number space - number space - number space - and with gaps man - to us I'm like that and with gaps man - to us I'm like that and with gaps man - to us I'm like that and then now that's them of gaps and then we subtract from the number of usable gap to minimal that's always tweet whoa - one - that's why ish Simon over animal oh what a well let's see I'm just a little tired you should have made me actually question it and test him or but let's just get a test case okay never had an issue there wasn't this one two examples nope I like it silver down like this well quitting it should not be zero ready move to five to the nine how am i rolling window maybe one no but still should not put cereal Oh life is evil maybe the North by one it's paying off I want to be honest like with tests maybe if we wanted to be one distri maybe tests just before just because I'm off by one it was inclusive yeah okay maybe alright let's try again sorry friends very similar no energy this prom was just a lot of thinking I mean the coding is way stand straight for it I think some of that is just like you have to prove to yourself so much because once again a lot of this is like greedy ish and greedy for me is always a little tricky to understand with greedy live like that one case of what this case took me a long time to come instead this is don't you look a edge case like I drew it all out to kind of figure it out oh yes let me go over this problem a little bit for and I think basically just in a meta sense and sometimes you cannot use them and do because you can tell them like what size you're trying to fix but then you could talk about you know your thought process through it I mean for me saying that n is ten thousand means well n square albums out away so you could only do and login or something like that and sorting is n log n but even after that you want to keep your constant slow and I and this doesn't feel like a divide-and-conquer-type equation uh divide-and-conquer-type equation uh divide-and-conquer-type equation uh problem for me so yeah in the sense that like yeah I don't know it for me it's just a little bit of intuition but it didn't seem like a divine conquer because there's no easy way to like divide the apartment into subproblems that you know you can merge later right that's the way you would think about it and Alvin n log n L will so damaged that means it must be off and which means that is some sort of greedy and maybe even born Windows which was what I was you ain't got in a little bit early but well yeah but you know just say he won't window doesn't mean you know how to solve it using woman no and that took me a long time to convince myself that this Estonia or not well this is the only edge case where it's one and they show you that in there are examples and yeah and it's basically a version of working backwards so you can only pick up and point stone so yeah so that was an issue that I was facing and after that the minimum is easy - off and after that the minimum is easy - off and after that the minimum is easy - off by one I should double-check that now by one I should double-check that now by one I should double-check that now which is a little tired near the end but well yeah and I also like that the hint still refers to cow so I almost willing to bet that this is a you circle problem which is what sadly high school students used to practice and I'm sure girl a bit of course spinner but yeah and then back symbol I think it's much easier I just didn't think about it until like near the end because I was worried about down half and yeah and basically just a symbol map of like okay here's not a gap doesn't matter how you having I focus a little bit on this case a little bit too much I should I think the more kind of typical case is something like this where well how you know how many was the maximum moves to someone like this and having this visualization help me a little bit I was just focusing on the numbers and kind of like one layers we moved a little bit too much probably but this allows you to be like okay and I'd kind of true this little bit where you move these fringes one by one from the endpoint and it doesn't really matter which way you go after this right because you know because you can easily move this to whatever but and it and we can't that way that the answer is obvious that you know the number of gaps is your maximum moves because you can always make a justification with that and then the only educates as well because that you have to then you could like to that stagger thing like that dumb they'll move to get a full life together a super pony or whatever and then just keep going away but you have one that's why I was mentioning then well you lose the first gap before you know close this gap and then move one by one and to fill in the remaining gaps may so that's kind of and then you because of that of greedy ish you always wanted or you only have one decision which is to choose to shorter one and everything else follows anyway so yeah that's kind of the problem oh this is way 23 maybe a little bit there's a lot just like really understand what it means to kind of follow the problem which looks the fun problem to solve was a brain teaser evening but now we're and this is probably a problem that's way typical of like you like I was saying years ago and other competitive programming things so definitely someone died enjoy practicing it's a little fun but respect but when do we always go oh it's gonna be a little iffy and always a little bit tricky and it and you're always not gonna feel great because you feel like you know there are million questions and you got one time requires like just level of mental dexterity which maybe is fine yeah especially reading well we're not but you know I always have a thing against greedy algorithms in general it's just my personal nemesis that so yeah but yeah I don't know how much you can learn from this problem in the sense of you know something that you can extend to your further learning so I would definitely recommend learning or like practicing on a farm people working on this one in terms of coding complex a mean this is n log n plus of n so n log n algorithm I don't use any extra space other than of 1/2 hole where we move so other than of 1/2 hole where we move so other than of 1/2 hole where we move so yeah but of course sorting is in place so you can make some argument there but well yeah that's what I have for this problem I think so yeah I hope either you really understand this problem or you don't get this on your interview you have an interview
Moving Stones Until Consecutive II
maximum-binary-tree-ii
There are some stones in different positions on the X-axis. You are given an integer array `stones`, the positions of the stones. Call a stone an **endpoint stone** if it has the smallest or largest position. In one move, you pick up an **endpoint stone** and move it to an unoccupied position so that it is no longer an **endpoint stone**. * In particular, if the stones are at say, `stones = [1,2,5]`, you cannot move the endpoint stone at position `5`, since moving it to any position (such as `0`, or `3`) will still keep that stone as an endpoint stone. The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return _an integer array_ `answer` _of length_ `2` _where_: * `answer[0]` _is the minimum number of moves you can play, and_ * `answer[1]` _is the maximum number of moves you can play_. **Example 1:** **Input:** stones = \[7,4,9\] **Output:** \[1,2\] **Explanation:** We can move 4 -> 8 for one move to finish the game. Or, we can move 9 -> 5, 4 -> 6 for two moves to finish the game. **Example 2:** **Input:** stones = \[6,5,4,3,10\] **Output:** \[2,3\] **Explanation:** We can move 3 -> 8 then 10 -> 7 to finish the game. Or, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game. Notice we cannot move 10 -> 2 to finish the game, because that would be an illegal move. **Constraints:** * `3 <= stones.length <= 104` * `1 <= stones[i] <= 109` * All the values of `stones` are **unique**.
null
Tree,Binary Tree
Medium
654
111
Jhal Hello Hi Guys Welcome To Koteshwar Today's Question Is Minimum Death Of Binary Tree In This Question Given By Ministry And Where To Find A Minimum Date And What Is The Minimum Date Eminem Death Easy Number Of Nodal Officer Test 500mb Root Not Want To Be Nearest Lymph Node Notice Not With No Children For Example See This Of Binary Tree And Where To Find Them In Depth Of The Country And Shadow Fight 3 Minute Number Note Lungi Shots Pass Us Roots Note Bismil That Deep File Path From Root Not Listen And After Doing All this will decide between ODI and test series Vanaspati 98100 less 15 3000 less 15 to 307 Sudhir 500 rout not least not considered to be a part of this day Chanakya 329 famous Kansal Bittu Notes39 that Sudhir Kaushik example2 null teen anal fun and fight And Known For Its Visualization Something Like This See Alarm Set All The Shining Trees Of Your Dear All The Note And Your Life History Sheet To Three Four ₹ 500 MP In The Morning Candidate Will Only To Three Four ₹ 500 MP In The Morning Candidate Will Only To Three Four ₹ 500 MP In The Morning Candidate Will Only One Pat Mist 5 From Root Note Police Nod For Not Due To Find The Answer Will Be 500 Answer For This Can Try Only Five Minutes I Will Be Doing This Question Is The Difference Between The Best This Ka Updation Subha Duty World Channel Radhe-Radhe Gyan Simply 0995 Fruitfully Radhe-Radhe Gyan Simply 0995 Fruitfully Radhe-Radhe Gyan Simply 0995 Fruitfully Same Chord Final Answer 112 Initial Winter Max No I Will Find answer in recursive function by reference date means during the course of the function of value final answer candidate can be updated and later on c and designing helper is my recursive function hull nearby root from hair oil pass every final answer italia 5s reference hand is Another Available Will Be Good Toe Count Now We Sew Them To Law 2016 A Tank Account From Italy Wash Not By This Account Has Been Taken Cc Tree Not Be Investigated Is Not Minute Man Totally Free Pass Baking Dish Frequency Dare Total 35 Witch Encounter For Mon route to lip election wear to find all the past and later on find 2205 minimal decorative minimal swan side 3 accounts from zero not contributed by one day test 98100 deposit 09 2008 and when will move ahead of not less than two-fold Acid Action Tweet 222 two-fold Acid Action Tweet 222 two-fold Acid Action Tweet 222 Hai Additional Porn Sites Ki Not Installed Singh Titu Notes Domingarh Account With Sudhir Vishisht Ek Din Author Budhi Note Scene Till Nau On Ki At Bana Diya 9 Ko MP3 Caller Tune Even Till Nau Sudesh Bhosle Approach And After Devi Hai Par Function Now you husband help them the school will simply vitamin and final answer a small it's right the me help function and white helper a tree note 4 root is enter departure sunday final answer and int account between store the number and node biopsy will know so digit Of Dysfunctions World Solid Basically Roots 112 Null What Will Happen Shadow Nothing Just Simply Written On That Noida Based Inside Press The Best Instead They Powder Listen Or See Vendor Lift Root Left I Jabalpur Internal And Root Right Is All Should 112 And Null Nowhere Recorded In The least not in the left see in the least not determine its benefits from root to back flip notes and just to minimize the interest to minimize the north and the east and north delhi end format of notes number 9430880409 to that note subah doob will update Kar final answer is equal to minimum final answer till now the final answer a hand account will be storing pin number of notes33 9 2009 200 countries to any value to build of account plus one way do it back to take this leaf mode on Son To Front Police Uniform Criteria Of Countless Avoid Simply Return From Near The Best Wishes Question Considered Only Country Subscribe Now To Receive New Updates From To That Go Into Neither Side View To Avoid Because You Will Not Given Any Good Answer Sweater Do Fruit Left Not Equal To A And Then Roots Let's Not Equal Dinner Date Means It Means That We Can Find Which Can Find A Path Which Can Lead To Minimum Lymph Node Minimum Patoli Is Not Fruit Lt Col When Will Do Absolutely Helper Will Pass Roots Left And Will Increment Account Plus World Records And Go Into Word Favorite Remedy Account Method Current Notes Words And Will Final Answer A That Similarly This Will Be With Roots Right Back To Go To Roots Right Only Exit Sum Value Will Have To Go Through This Right In The Original Pointer Sisters Helper The Root Right And Wonder Is So The Final Answer Pure He Will Find Answer And Held Accountable For Andar Hospital In The Final Answer Co And Account Plus One U Ko Define Or So And After 10 Call With Written From Where E The Police Was And Tired Now Let's Submit Decode A's Settings Accepted This Morning When The Commission Dedicated To Sitaji Liked This Video Thank You A
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
55
hey guys it's offline one here and today we're going to be solving Jump game in this problem we're given an integer array nums and we're told that we're initially positioned at the array's first index so for example we're going to have to always start at this first index and they tell us that each element in the array represents the max jump length at that position so if we start at two that means we can either jump to this next index or we can jump two indexes and the problem was to return true if we can reach the last index or false otherwise so for this example here we only have to reach this four and we can see that if we start from this three because we already made it from two then we can make it to four because this would be one two and three so we return true here for this example though let's say we started this first index because we have to start there we can jump to the next index so there's one here or to the zero and from here if we can go to the next index and see if we can reach the four but as you can see we cannot we end up at the zero again and same thing if we started this one we can also only make it to zero so because we can't reach this last index we return false so here I've written the example from the problem and I've also put the indexes on top of the numbers so it's easier to understand what I'm doing and now we're going to start so we're always going to start at index 0 and the max jumps you can do here is two so let's write that down start at index 0 and we can either do one jump or we can do two jumps if we do one jump we're going to end up at index one and at one we have a value of three so that means we can do up to three jumps so we're going to have one two and three and now we see where we end up now so if you need one jump we end up at index two if we do two jumps we end up at index three and if we do three jumps we end up at index four which is what we want to do but now let's just continue the tree to see what happens so at index two we can only do one jump and same thing for three we can only do one jump as well so here we would end up at index three and here we end up at index four and same thing here we can only do one jump so we end up at four and now we go to this other part of the tree if we do two jumps we end up at index two and from index two we can only do one jump and then that puts us at index three and then index three same thing we can only do one jump and that will take us to four so as you can see here we're doing a lot of repeated work for example we went to this three multiple times and instead of having a calculator each and every time to see if it gives us to the end we can just store it in our DP array and also same thing for two here we went to it multiple times to get rid of the repeated work we could just store this in for example a DP at the index two and DP at index three so that way we know in the future that we already went there and don't need to recalculate it but the problem is that this solution takes up something like o of n Square time I believe since we have to go through every single index and then for every index we have to iterate this many times to be able to update our array so for example for 2 be waiting to update index 1 and index two and for three we do the same thing update this Index this index and that index and you can see that's a lot of work there's actually a much simpler solution that is also more intuitive in my opinion so what we're going to do is start by putting a pointer here at index four and we're going to start by looking at index three so can we get to 4 from index three yes because we can make one hop and that would get us to four so now we can just move this pointer to the left one so now we can see that we don't care if we can reach this last part because now we only care if we can reach this number since we have already verified that we could go to the last one so now we checked the previous index so can we go from here to here well yes because we only have one hop available but that's enough to get us to index three so now we move this pointer over here and now we do the same thing we don't care if we can reach this number anymore because we already verified that we could and now we checked the previous indexes number so can we reach index 2 with this number well yes all we need is one hop now that we verified that we can move to pointer to the left again so now we do the same thing we don't care if we can reach this number anymore we only care about reaching this number and if we check this index here we see if we have a 2 and we only need one hop to get there so we can move this pointer to the left again now at this point we're at index 0. so again we don't care if we can reach this point and we verified that we could reach every single point so we could return true because our pointer is pointing to index 0. so again if our pointer points to index 0 we return true if it ended up over here then we know we couldn't reach the beginning which means there's no way to get to the end either so we would return false over here so our pseudo code could look something like this so if the current index we're at plus the current number we're looking at is greater than or equal to the pointer and this pointer is going to be an index so just remember that then we want to update our pointer to point to our current index and then at the end we return true if our pointer is zero and that's basically it for our pseudo code so as far as the type complexity goes the time is going to be o of n because we're only iterating through the array once and we're actually going to do it backwards in our code so still all of N and for space we're only using a pointer variable here to keep track of where we're at so it's constant space because we don't need a DP array so now we can get into the code to start we're going to initialize our pointer variable and it's going to be pointing to the very end of the nums array so it's going to be length nums minus one and from here we just want to iterate through our numbers array so for I in range of length of nums minus one and then we're iterating backwards we want to do our check so if I the current index plus the current number we're looking at is greater than or equal to our pointer then we update our pointer to be our current index and that's the whole code after that we just return if our pointer is equal to zero then this is going to return true otherwise it's going to be false and now we can just submit the code so as you can see this code is pretty efficient and now I'll go through the code manually so to start we want to initialize our pointer and it's going to be at length of nums -1 so this would be five minus 1 of nums -1 so this would be five minus 1 of nums -1 so this would be five minus 1 which is equal to four and you can see that it's pointing to index four so that's checked off and now we just do for I and range of length of nums backwards and let's say we're starting here now we check if I Plus numbers of I is greater than or equal to our pointer then we update our pointer so let's see I is currently 3 and the current number at I is one so three plus one equals four so that does mean our condition so now we just want to update our pointer to I so now our pointer is pointing to three and we can do this condition again I plus nums of I is greater than or equal to our pointer so we're looking at index two and the index two number is one so two plus one does equal three so that's just barely enough to move our pointer so now we update it again and now we do this again so I is currently one because we're looking at this index and our Norms at I is 3 and we can see that one plus three is greater than or equal to two because that's where a pointer is currently so now we can move it to the left again and now we're at our last iteration so we're looking at this index here and now we check zero plus two that is greater than or equal to one so we're going to move our pointer to the left again so now at the end here we can see that our pointer is at zero so we're going to return true here and that's correct in this video helped me in any way please leave a like And subscribe thanks for watching and I'll see you in the next video
Jump Game
jump-game
You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position. Return `true` _if you can reach the last index, or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[2,3,1,1,4\] **Output:** true **Explanation:** Jump 1 step from index 0 to 1, then 3 steps to the last index. **Example 2:** **Input:** nums = \[3,2,1,0,4\] **Output:** false **Explanation:** You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 105`
null
Array,Dynamic Programming,Greedy
Medium
45,1428,2001
150
hey guys welcome to a new video in today's video we're going to look at lead code problem and the problem's name is evaluate reverse polish notation so in this question we given an array of strings called tokens and that represents an arthamatic expression in a reverse polish notation so a reverse polish notation can also be called as a postfix operation and by definition a postfix operation is that first the operants will be present and then the operator will be present so this is the operator which can be addition subtraction multiplication or division symbol and these are the operant which are integers so generally you write 2 + are integers so generally you write 2 + are integers so generally you write 2 + 3 right but in Reverse polish notation you write 2 3+ so this is a postfix you write 2 3+ so this is a postfix you write 2 3+ so this is a postfix operation and we are given few notes and these are the only operators which will be present each operant may be an integer or another expression for example this is so this is one operant and this is the second operant and initially if you start this is one operant and this is the operator and the division between any two numbers always truncates towards zero there will not be any division by zero so we can assume that there is always going to be a valid arithmetic expression in Reverse polish notation so for example there won't be any test cases where until you get two opponents there won't be any operator so the input won't be invalid like 2 + 3 the input won't be invalid like 2 + 3 the input won't be invalid like 2 + 3 will be invalid but such test cases won't be present and the answer and all the intermediate calculations can be presented in a 32-bit integer so it will presented in a 32-bit integer so it will presented in a 32-bit integer so it will all inside the range of an integer now let's take a look at these examples and see how we can form the logic so let's take the first example so these two are the operant and this is the operator so this sequence can be written as 2 + 3 this sequence can be written as 2 + 3 this sequence can be written as 2 + 3 but in Reverse polish it is written as 2 3+ so we know we have to add these two 3+ so we know we have to add these two 3+ so we know we have to add these two because the operator is addition so we have to store these two somewhere and apply this operator on these two stored variables so a good data structure to use will be a stack where we are going to store the operant and whenever you encounter a operator that is plus minus multiplication or division we will pop these operants from the stack and perform the operation so let's take an example and see how the stack operation will be performed on this example so we start iterating from left to right as soon as you find a operator we pop the elements if you find a integer you directly add them into the stack it's a two so add it into the stack from the top the next character we access is one which is also an integer so if it is an integer directly add it into the stack the next character is a operator plus so pop the first element out of the stack and store it inside a variable so this is important we store it inside a variable num two so one will be stored inside num2 and now we pop another integer once we encounter operator it means we have at least two integers inside the stack now we pop the second one so once you pop it the element will be returned and the The Returned element I'm storing inside a variable and it will be removed from this tack now perform the plus operation on these two so if you add these two you get three so this is an integer right so add this into the stack so three will be added into the stack now the next character is a integer so add it into the stack so the result which was initially three will be reseted back to zero and now the next character is a multiplication operator once you encounter a operator pop the element from the Stop and store it inside num two pop the next element and store it inside nums one now perform the multiplication operation so the result is num 1 into num two 3 into 3 is 9 so add this element into the stack because that is the result and in the next iteration we reach the end of the stack so we end our iteration and now whatever is present inside the stack that will be returned as the output so the output is nine which is returned here now let's implement the same steps in a Java program and then we'll debug the code for this test case so this is the function given to us and this is the input tokens so like I said we need to declare a stack which will contain strings because this is a string array now let's iterate through the input so this is the array right so I'll use a for each Loop which will Access One String at a time so for so we have to access tokens which is a string array so I create a string called token which will access all the tokens and this is the variable name which will iterate through the tokens now we have to identify if the character is a oper or not right so this is an operator and this is an operator so I'll use a helper function which will return a Boolean value true or false based on the input given to it so I'll name it his operator and this will be a string now I have to check if the string is one of the four operators so s Str do equals so first I have to check if it is a plus sign or I'll copy this and paste it three times for the remaining three operators so second operator is minus third operator is multiplication and fourth operator is division so if it is an operator I have to return true and outside the if statement if it is not an operator it will return false and now I have to call this function inside the main function so I'll call the function is operator so if this input token which we are iterating through the input array is an operator this will return true so once this is an operator like I said I have to access the two characters so let's do a dry run simultaneously for the second example so first four will be added into the stack since it is an integer next 13 will be added five will be added next the operator is division so if it is a Division I have to pop the first element out and store it inside num 2 so num 2 is equal to 5 I have to pop the second operand and num1 is equal to 13 so let's write the code until here so we encountered a division operator and top of the stack has five and second element has 13 so int num2 is equal to stack. pop will give you five but stack contains in strings but we are storing it inside an integer so I have to convert the string into an integer so I'll use the integer. parent method so this will give me num two I'll copy this so first we popped five and stored it inside num two next we popped 13 and stored it inside num one so num one will be 133 now we have to check what type of operator it is so I'll write four if statements so if this token is a operator only it will come inside so I have to check if this token do equals plus operator I have to add num one and num two inside a variable result so I'll create a variable in result and initially it will be zero and inside the if statements if it is a plus so result is equal to num 1 plus num2 and now we have to repeat for minus multiplication and division so I'll copy this and place it inside LF block if this operator is a minus then we have to do num 1 minus num2 and I'll copy this again and do multiplication so if the operator is a multiplication operator it will be num one into num two and finally again I'll copy this once if it is a division then it will be num 1 by num2 and the result is calculated now we have to calculate the result so result is equal to num one and the operator is division so num 1 by num 2 so we have to do 13x 5 and this is a integer right so we'll get 2.3 and it will take only two we'll get 2.3 and it will take only two we'll get 2.3 and it will take only two as the integer now this is a two now this is the result and we have to add this result back into the stack so two will be added here so instead of adding stack. push of result for every if statement we can do it outside the if statements in order to reduce the Redundant line of code we'll push this result outside the statements so stack. push of result but this result is a integer variable and stack contains strings so we have to convert this integer into a string so I'll use the integer. two string method and place this result inside as parameter so this result which was integer will be converted into a string and it will be pushed into the stack and now the else block so now the else block states that the opposite of this statement so if the input string is not a operator so if there are integers this statement will be executed so what did we do if there were integers we just push them into the stack directly so stack. push and push the token which is already a string so push it directly into the stack so we add the token directly into the stack and now this will happen for all the tokens present inside and let's complete our operation now we have and now in the next iteration it is a plus right so the operator is a plus so we have to pop the element and add it inside num two so num two will now have two and pop the second op add it inside number and since the operator is plus you have to add the two operant so 4 + 2 is equal to 6 now we operant so 4 + 2 is equal to 6 now we operant so 4 + 2 is equal to 6 now we have to add this result back into the stack so six will be added back into the stack and we reach the end of the iteration so whatever is present inside stack will be returned as the output so six is returned as the output so let's return whatever is present inside stack so here before ending we have to return whatever is inside stack so the return type is an integer but stack contains strings right so we have to convert the string into a integer so I'll use the integer. parcent and the topmost element is stack. Peak so stack. Peak will give you the topmost element now let's try to run the code the test case are being accepted let's submit the code and a solution has been accepted so the time complexity of this approach is of n where n is the length of the string AR tokens the space complexity is also often because we're using a stack to compute the output that's it guys thank you for watching and I'll see you in the next video
Evaluate Reverse Polish Notation
evaluate-reverse-polish-notation
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). Evaluate the expression. Return _an integer that represents the value of the expression_. **Note** that: * The valid operators are `'+'`, `'-'`, `'*'`, and `'/'`. * Each operand may be an integer or another expression. * The division between two integers always **truncates toward zero**. * There will not be any division by zero. * The input represents a valid arithmetic expression in a reverse polish notation. * The answer and all the intermediate calculations can be represented in a **32-bit** integer. **Example 1:** **Input:** tokens = \[ "2 ", "1 ", "+ ", "3 ", "\* "\] **Output:** 9 **Explanation:** ((2 + 1) \* 3) = 9 **Example 2:** **Input:** tokens = \[ "4 ", "13 ", "5 ", "/ ", "+ "\] **Output:** 6 **Explanation:** (4 + (13 / 5)) = 6 **Example 3:** **Input:** tokens = \[ "10 ", "6 ", "9 ", "3 ", "+ ", "-11 ", "\* ", "/ ", "\* ", "17 ", "+ ", "5 ", "+ "\] **Output:** 22 **Explanation:** ((10 \* (6 / ((9 + 3) \* -11))) + 17) + 5 = ((10 \* (6 / (12 \* -11))) + 17) + 5 = ((10 \* (6 / -132)) + 17) + 5 = ((10 \* 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22 **Constraints:** * `1 <= tokens.length <= 104` * `tokens[i]` is either an operator: `"+ "`, `"- "`, `"* "`, or `"/ "`, or an integer in the range `[-200, 200]`.
null
Array,Math,Stack
Medium
224,282
342
hello everyone how you doing welcome back to my video series on solving lead code problems so now we're going to the power of four I'm just going to so power of four given an integer n return true it's a power of four otherwise return false an integr N is a power of four if there exists an integer X such that n = 4 to ^ of X so 16 is true five is n = 4 to ^ of X so 16 is true five is n = 4 to ^ of X so 16 is true five is false one is true so what can we do I think n = 1 do I think n = 1 do I think n = 1 is the like the base case or Edge case and well we can just simply divide by four this is like the dumb approach um return if n = 1 if the rest of the return if n = 1 if the rest of the return if n = 1 if the rest of the division of n by 4 if there's a rest so if this is not zero return false so let's say if n in one no let's keep this let's be simple and then we return self dot is power of four of n integrated division four let's just submit maximum recursion depth isce compar Arison uh let's not use recursion then well what I actually want to do with recursion let me run locally maybe I just made a small mistake directory 342 power of four code1 oh wa made remove directory 3412 code 342 was the previous thing solution. so let's go C solution is power 4 16 run true cool and what about this one it's false so last executed input zero okay yeah F1 is that if Zer I think Zer should be false and equal Z then turn false okay was accepted well there one way to do it another way to do it is check if we can with bit shift operations so what we can do is I'm just going to run locally uh 16 so we can do something like um is power of four and uh bit equals n N1 uh if bit return B and then we can say n equal n and then we bit shift one and then we do the same thing if it bit equals this and if it's bit return false then we bit shift again so for range in range two for I we don't even need to have like a iterator like value so we just do this and then return um now what we're saying is that if we can divide by two yeah return false uh um if n = um if n = um if n = 1 turn true we also keep yeah I think this is it and then return is power of four or actually let's do it differ way let's return true in the end so while n is different than one yeah true 16 17 false four is true and zero n = zero n = zero n = z return false let's submit this it got accepted but it did slower but yeah this is one way of doing things with bit ship operations hope you guys enjoyed it see you later
Power of Four
power-of-four
Given an integer `n`, return _`true` if it is a power of four. Otherwise, return `false`_. An integer `n` is a power of four, if there exists an integer `x` such that `n == 4x`. **Example 1:** **Input:** n = 16 **Output:** true **Example 2:** **Input:** n = 5 **Output:** false **Example 3:** **Input:** n = 1 **Output:** true **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Bit Manipulation,Recursion
Easy
231,326
117
hey what's up guys this is chung here so let's take a look at today's daily challenge problem number 117 populating next right pointers in each node number two i believe i have done videos uh for this not for the number one problem you know and so this problem is exactly the same except for uh except for the uh the three is not a complete tree which means that you know a node could only has could only have uh only left child one or right child so for the uh for the problem number one right i think the tree is guaranteed to be a complete tree so that's why that one is a little bit easier than this one right so let's take a look at the description you basically you're given like a binary tree here and you need to populate the next pointer basically you know the as you guys can see here so the next pointer is um from the on the same levels right so you need to create the next pointer from the left point from the left node to the right node and so on and so forth right and here there is like a follow-up question right you may only a follow-up question right you may only a follow-up question right you may only use constant extra space right so i'm gonna basically i'm gonna i'll be talking about two solutions today so the first one is of course the level other traverse right so for the level other traders is the most straightforward one basically but for the level traverse one you have to use some extra space right to store the notes on each levels that's why that's when where this follow-up comes from can you solve this follow-up comes from can you solve this follow-up comes from can you solve this problem without using the level of the triggers right so for that one we're gonna need the uh a little bit of the handling for on the current level and next levels but you know first thing first you know let's try to uh quickly implement the level other triggers right so that we can have a starting point here so basically for level auto traverse this thing works for both the number two for this problem and also the number one i mean so the level auto travers is pretty straightforward right i mean let's use the uh the queue right we use a queue and then we just populate the route and then we have a while q and then we have a four right in this length of the queue so we have a current right the current is the queue dot pop left right and we also need the pre because since we're going to establish a pointer from the previous from this one to the next one that's why we're gonna need a pre right and basically if the pre and then every time when we have a current one we update the pre to the current one right so and if the pre is not empty right then we do a pre dot next equals to current one right so that's that and then we just need to finish the other level other traverse that we're where it's going to be at the out raise the left the current left is not empty right we add it into the queue right append current.labs right append current.labs right append current.labs right and then same thing for the right one q dot append current.right q dot append current.right q dot append current.right so yep i think that's pretty much it so in the end we simply return the route and this should just work yeah okay submit yeah so this one passed right and yeah as you guys can see here right so we're using extra space to store the nodes for each of the levels right that's why uh it has asked us to come up to think about if we can solve this problem without using an extra space so right how do we solve this one without using the actual space similar idea for the with for the first one prefer for the comparing with the first uh the number one problem right basically you know we are on the current levels right so assuming we are on the current levels we are going to populate the next levels on the current level because you know we're assuming that you know let's say we're at the at this level here you know we already have the next pointer for the current levels here right so that's why you know for the current levels here we can use the current level plus the next pointers for the current levels and we can traverse from the left to right and while we're traversing the current levels from left to right we're also going to populate the uh the next levels basically we're populating the next pointers from the current level to the next level but the only difference is here like the you know since then on the next levels right there could be a uh like let's say for example here after the right one after the right after this point uh note here we don't have a left node on the next level on the next uh on three here we only have seven here that's why we have basically we also need to use like the similar idea as this level other traverse you know every time we're at the current levels we after processing the uh a node here right we're updating the pre cursor here of the pre variables here and then every time we add three here we check if there's a left level if there's a left node here if there is and then of course we need to establish a pointer from the uh from the previous one to the next one else if there's a note there's not the left one of course we're going to go to the right one and if the right one's there and we'll we are also going to establish the pointer from the previous one to the right one right and then uh and then we're gonna do the traverse same thing by level right and at the beginning we're at this level and the next we're at two here and second where and then we add four here so and then we also that's why we need to basically maintain our left most uh variable here you know that's going to be our starting point for each levels and every time we're when we're at the current levels we're trying to find the left most for the next level until we couldn't find enough another levels then that's when we're going to stop our while loop i know it's a little bit confusing maybe but i will try to explain more uh while i'm calling here so what i mean is that like this at the beginning i'm going to have like left most equals to root right so that's the uh that's our starting point and let me try to fin write the main structure here and while left most while the left mode is not emptied it means that okay we need to process the uh a next level right otherwise you know we in the end we simply return the root okay so and okay so now we're at a level right so we're at a level here and we need to process the i mean the node from left to right so that's going to be our current levels and we'll because we're going to uh establish the node the next pointer from current level to the next level right so that's why you know since we're going to be using the left pointers to uh to start the next level process i'm going to create a current one going to be the left most right so and then here we have a wild current right we have our current one and then in the end there's a current dot equals to the current dot next so here we're processing the current level right and how are we going to jump to the next level here right we need to update this uh left most so to i mean before doing that we need to clear this left most to be none because otherwise you know we have to if there's nothing on this current level if the current level doesn't have a next levels then we won't have we then the left most should be empty but if we don't clear it here i mean this uh the while loop will never be finished right so we process current level right so that's how we process the current levels here and of course we uh we also need a pre here right so that's the uh the three variables we're going to need here and the first thing first is that you know um let's try to find the so since either left or right couldn't it might be not might not be exists that's why we need a if the left is not empty and if the right is not empty right so we have to process them separately right that's going to be the two uh branch here and on in each branch so first we have to make sure the left most will be updated so that if there is a next levels the while loop can continue on the next level so which means that you know we have to first thing first we have to try to find the uh update the latin the left most for the next level which means that if not left most right we find the left most equals to the current left same thing for the right pointer right so this okay so these two lines i think it's kind of obvious right i mean basically you know we try to find the left most node for the next levels right which means that you know if there's like a node something like this right if there you if you're at the current levels as two three right if we're at this uh this level here and let's say we have some let's see the next level is something like this one and this one right so for that one we have for this to find the starting point for the next levels we have to find this node how do we find it so that's how we find it as long as this one is not empty we find the first basically we find the first node that is not empty right and as long as this one is not empty this one it will never be updated that's why since the left is not empty it's empty then we find the right one okay so the right ones it's not empty that's why we will find this one and how about another case right let's say there's nothing on the first note on the current levels and the only the first one is this one right then how are we going to find this one same thing right because as you guys can see so we are looking through from left from the current one to the net to the next one that's why the uh so there's nothing here and then when we're at the next one the next level which is three here we found okay so the left one is not empty right and then we'll set up the uh this one to be the first the la on the left most for the next level and that's how we got calculate the first the starting point for the next level right and that's that okay so and besides to get the besides to initiate the starting point for the next levels we also need to process the uh this one right so the pre gonna be the current dot left right same thing for the right one that's how we update the uh the pre the precursor right so basically every time there's a if this is if we're processing a current node we're gonna update the pre and the rest is just pretty straightforward right if the pre is not empty similar like the row levels right we do a pre dot next equals to the current dot left which is going to be the next level right same thing for the right side if the play is not empty then pre dot next will be the current dot right so and i mean it's pretty i think so to go through of the one of the examples here let's say we're at a number two here right and we're assuming that so we already have a pointers pointing from two to three now we're at two here we're at two so first we find four is going to be the next level that left most uh node here and okay so we find the four here and then okay so the left most will be four but the priest uh priest is not at this at the moment that's why we're not gonna do this so and that's why the uh so now after this if the if check here so the pre will be equal to or equal to four here right and then we check the right one so um when on the right one is five and we already have the leftmost that's why we're going to skip this part and now the pre is already populated which is four then we establish a pointer from four to five right that's how we are going to be the four two to five the current right is five now the pre becomes to five right so now this appraise is five and then we move the current cursor from two to three right and then again we'll be checking okay so it's three that's three has a left no it doesn't this that does not have a left that's why we're going to skip this part and then we'll come to the right part so three ha three has a right note has a right trial that's why the uh the pre so at this moment the pre is five right so that's gonna that's why we're gonna that's gonna how we pre establish the pointer from five to seven yeah so and that okay then it's done right so now the uh the left most will be four right so on the four here so we'll go through this again right so which means the uh the four but you know at the current level there's nothing on the next levels that's why we're gonna we're still going to go through this while loop here because you know the uh the card will the cardinal will be four right the present t and then we from four because none of them there's not nothing to be here right we which means that we're going to loop just loop through from four to five from five to seven and we're never going to uh populate this left most the new left most that's why uh after finishing finish processing the current levels the leftmost will becomes to empty the nut and then will the whole while loop will stop right and then yep and then that's it right so in the end we return the root here so okay let's run the code yeah so accept it all right so that yeah there you go i mean the uh as you guys can see here right i mean so for this one we don't use any of the extra space here all we have is like the you can call the level traverse right while uh maintaining like a pre of precursors plus the uh the leftmost cursor right that's the only two uh additional variables we are creating here and other than that there you have it's one space complexity right cool i think that's it for this problem and thank you so much uh to watch this video and stay tuned see you guys soon bye
Populating Next Right Pointers in Each Node II
populating-next-right-pointers-in-each-node-ii
Given a binary tree struct Node { int val; Node \*left; Node \*right; Node \*next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`. Initially, all next pointers are set to `NULL`. **Example 1:** **Input:** root = \[1,2,3,4,5,null,7\] **Output:** \[1,#,2,3,#,4,5,7,#\] **Explanation:** Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 6000]`. * `-100 <= Node.val <= 100` **Follow-up:** * You may only use constant extra space. * The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
null
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
116
1,776
so hello everyone welcome to my channel and in this video i will be explaining the problem car fleet too so this is a pretty difficult problem and it's like one of those inception kind of mind-bending problems inception kind of mind-bending problems inception kind of mind-bending problems like a lot of collisions are happening and all that in fact i also struggled with this problem but anyway uh in this video i will be first discussing the idea how to solve this problem and then i will be coding it so let's get straight into the problem so what the problem is says that i have been given a car their positions and their speeds and i have to tell that when a current car is going to collide at what time like is have going to have its first collision okay so i will be explaining the idea of this problem through this example so let's see this example so this is the example basically uh position of cars is given three five six nine and their speed are giving four three one okay so what is the intuition to solve this problem is that i have to look at the right most car and then i will go back because i have to find that which when the right car is going to collide with a car that is ahead of it so okay so i just go at this car okay i find out okay uh is there any car that is slower than me with which i can collide i will get an answer no there is no car ahead of you so i will written mine right minus one because this car is never going to collide with any other car that is ahead of it okay so now what i am going to do i am going to be a go at this car and i am going to say hey is there any other car that is ahead of you and slower than you and i will get an answer yes there is a car with which i can collide so i will get an answer okay yes so i will calculate what time is it is going to collide so the answer will be like 2 seconds 9 minus 6 that is what 9 minus six sorry one point five seconds my bad one point five seconds nine minus six is three by two one point five seconds okay now i will come at this car okay now i will see that okay is there any other car slower than me so i will get an answer yes there is a car that is slower than you and this is this car okay so i see that okay this car is slower than me and how much time will i take to collide with it is what will be the time will be six minus five one by one that is one seconds okay uh after i have calculated this time one second i will just check that how much time is this car going to collide with some other car so i will obviously if there is some time mentioned here it means that yes it is going to collide with some other car and now i see that time is 1.5 seconds and now i see that time is 1.5 seconds and now i see that time is 1.5 seconds okay and my time of collision with this car is one second so it means that before this car collides with some other car and it becomes a part of that other car i will collide with it okay so it's safe to write one here okay you will understand this more when i tell this example so now i commit this car okay i see that is there any other car that is in front of you slower than you i will get that answer that yes there is a car like this and but it is not slower than me so i will just ignore this now i will go to this and this car is slower than me so what i do is that i calculate the time of collision so the time of collision is going to be like what three by one that is three seconds okay three seconds but now after writing three i realize that okay this car is going to be going to collide with some another car in 1.5 seconds it means that by the time in 1.5 seconds it means that by the time in 1.5 seconds it means that by the time i reach this car would already have become a part of some another card ahead of it okay so i see say that okay i won't stop here i will go ahead so now i go ahead i see this car and see that oh it's speed is less than my speed so it means that i will collide with it and the collision time will be two seconds that is nine minus three six by three that is two seconds so it means and then what i do is that i check the collision time with this car that okay is there any other car with which it is colliding suppose it was colliding with another car in say one seconds that means that i have to go ahead because it will already have become a part of some other car so you know it's a little bit confusing but i suggest you can draw this and you will it will be super clear to you so now right now i see that minus one that means it is not going to collide with any other car so it means that now it is safe to update this answer with what two seconds so i will write 2 here and that is the answer so now i have since i have grabbed the idea how to solve this problem now how to solve this problem so this problem it can easily be solved by using n square that i will uh in n square time by like just doing a loop and all that because i will just check every car and see that which car has the lowest collision time with my current car but since like you know there is a pattern in stack problems that like suppose you're observing here that i may need to go ahead or i may be satisfied at some point only okay in this case i was satisfied at this point but if the time was something else i should have uh needed to go further so you know if there is this kind of dependency like there are two loops and one loop is dependent on like another like the current i is j is dependent on i so this time these kind of problems we have to think about stack data structure so let's code it once i code it will become more clear to you so let's increase the font and code it to 16 pixels okay so what i'm going to do first is that i will just write n 10 is equal to cars dot size because why not and then i will make a vector double res and comma minus one so this basically is going to store my uh like collision timings the result that i have to return now what i will do is that i will make a stack int s so this stack will store the uh what indexes of these cars so just let me clean this thing up so that i can explain while coding i have to go a little more back okay this is the maximum extent okay so now what i will do is that i will start from my end from into n i is equal to n minus 1 i greater than equal to 0 i minus okay so the first thing that i do is that i will check my stack while stack is not empty s dot emperor t empty and the if the stack is empty then you would you won't go into this while loop and if the stack is not empty what i will do is that i will check if cars i 1 is less than or equal to cars s dot top 1 so i will just explain in a minute that what this means so i will do s dot pop here so this means that to check if the car ahead is slower okay so basically i have to check you know that if there is some going to be some collision or not if there is not going to be any collision for example in this case if there is not going to be any collision with the car just ahead of me i will just like pop this out of the uh pop this out of existence and i will go further to see so that's what i am doing here and after doing here uh this step what i will do is that just a second oh so why uh now i know that if the stack is not empty if the stack has some items then what it means that there is going to be a collision s dot empty okay so now for example in this case just take this case back because i like this case so in this case i came here and i popped this out of existence now i go further okay i am going to see this case okay so now what i did while explaining was that i calculated yes they are going to collide so i just calculated their time so that is what i am going to do so i will calculate the time double collision time is going to be double so this is just type casting here so cars car sorry uh yes cars s dot top that is the position of the car that is on the top of stack minus cos i zero and i also had to write zero here because s dot top is the index okay divided by the relative speed so that is going to be cars i 1 minus cars s dot top sorry s dot top 1 so this is uh by this i am going to get the collision time okay now what i will do is that i will check okay so while explaining what i did was that i will check okay i come at this speed uh this car and i check okay the collision time between this and this car is what three seconds as i told earlier now i will check that okay is this car colliding with some other car before i collide with this car and if i get the answer as yes that means that i have to go further and if i get that answer as no it means that my hunt is over and okay let's get out of the while loop so that's what i'm going to write here so if collision time is less than or equal to res uh what s dot top okay so for so this means that what does this mean so this is what this basically mean this res dot top is 1.5 res dot top is 1.5 res dot top is 1.5 okay and either this can be the case or for example if this car was not going to collide so with any another car it was it would have been -1 okay car it was it would have been -1 okay car it was it would have been -1 okay so if this is the condition or if res s dot top is equal to minus 1 so if these are the two cases then what i will do is that i will just update my res i with collision time and i will break out of the loop that my hunt is over okay but what happens in this case is that in this case my hunt is not over i have to continue so what i will do is that i will just pop this pop out this element out of existence and i will just continue so s dot pop so now what i will do is i will be at this car okay and now i will be checking if this car there is a collision happening and i will get yes the collision is happening and the collision time is what -1 so it means that i will what -1 so it means that i will what -1 so it means that i will calculate new collision time that will be 2 and since this time is minus 1 it means that yes i have found the car with which i am colliding so that's the case and in the end what i have to do is that s dot push what i so what this means is that okay for example if i was at this position in the end what i would have done i would have put this the index of this car into my stack now in the beginning so that i can use the stack actually so that's what i have done and that's the problem for you res return i will return okay my computer is hanging return rest so now hope i hope the code is correct syntactically okay it is accepted and now i will run submit this code please guys subscribe to this channel so okay it is accepted not the fastest solution though but it gets the job done in big o of end time so you know you can have a look at this code and please subscribe to this channel a lot of you guys don't subscribe so it really motivates me to make these videos more enthusiastically so just have a look at this code there is nothing much okay i just made a vector and stack and all that i ran my first while loop to check if the head car is slower and check and like pop out all the cars that are faster than me and this while loop means that update it is all about updating the result and the collision time so this is the main logic here so if you have understood the problem please consider subscribing this channel so thank you and have a nice day
Car Fleet II
minimum-operations-to-reduce-x-to-zero
There are `n` cars traveling at different speeds in the same direction along a one-lane road. You are given an array `cars` of length `n`, where `cars[i] = [positioni, speedi]` represents: * `positioni` is the distance between the `ith` car and the beginning of the road in meters. It is guaranteed that `positioni < positioni+1`. * `speedi` is the initial speed of the `ith` car in meters per second. For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the **slowest** car in the fleet. Return an array `answer`, where `answer[i]` is the time, in seconds, at which the `ith` car collides with the next car, or `-1` if the car does not collide with the next car. Answers within `10-5` of the actual answers are accepted. **Example 1:** **Input:** cars = \[\[1,2\],\[2,1\],\[4,3\],\[7,2\]\] **Output:** \[1.00000,-1.00000,3.00000,-1.00000\] **Explanation:** After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s. **Example 2:** **Input:** cars = \[\[3,4\],\[5,4\],\[6,3\],\[9,1\]\] **Output:** \[2.00000,1.00000,1.50000,-1.00000\] **Constraints:** * `1 <= cars.length <= 105` * `1 <= positioni, speedi <= 106` * `positioni < positioni+1`
Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily.
Array,Hash Table,Binary Search,Sliding Window,Prefix Sum
Medium
209,560,2183,2290
1,710
so guys consistency is the key you have heard this we all know this but yeah when we start with lip code after maybe two or three days we stop solving problems after two or three days after maybe 10 or 15 questions we stopped doing that but let's just commit for this daily lit code challenge series and from whichever day you are watching this series i would request you to follow along and solve the daily lit code challenge and i'll be discussing about the solution i'll be discussing about the approach that i am taking the complexity space complexity time complexity i'll also be discussing about how i'm going to write the code in javascript what are the alternative methods to solve the problem and you can also see a blog which will be linked with each solution each video and you can check the blog in the description and with all this i would also request you to subscribe to the channel and hit that like button so now let's jump into today's code challenge so we have this quotient maximum unit on a truck so this is the easy level question and let's just go through the problem statement you are assigned to put some amount of boxes on one truck you are given a 2d array box type where box type i is basically number of boxes and the number of units per box so this for each box how many units will be there so simple number of boxes is the number of boxes of type i and number of units is the number of units in each box of type i clear you are given an integer truck size which is the maximum number of boxes that can be put on the truck you are you can choose the boxes to put on the truck as long as the number of boxes does not exceed truck size so we have to occupy the truck size in such a way that the boxes that we are taking will have maximum number of units and the total accumulated value of all the boxes that we have taken all the four boxes considering this example will give us the maximum cumulative number of units that we can acquire from the list of boxes so for this we can see it is eight because uh one box with three units is taken and then two box with two units are taken and then one box of one unit is still taken the explanation is given over here and you can see 1 into 3 plus 2 into 2 plus 1 into 1 and it gets us 8. so let's jump into the solution now so now this is our second example that we have got from the question we have the list of uh boxes and this second index so basically the first index and the zeroth index in the first element is the number of boxes and this is number of units in each box so now we have to maximize we have we already know that the truck sizes okay the truck size is 10 over here so yeah we already know the truck size is 10 so maximum boxes that we can take is going to be not more than 10 or 10 so it will be 10 so for this example you can see this is the number of boxes and this is the number of boxes but first now you have to see which box have maximum number of units inside that so you can see over here you have a 10 with maximum number of units and then we have 9 then we have 7 then we have 5 so it's better to fill up the boxes first which are filled with more units so i will first take 5 units of 5 boxes of 10 units now when i take 5 boxes of this will be the boxes and this will be the units and we will calculate the total so when i am taking 5 boxes of 10 units i am getting 50 as our total unit next we have out of the 10 now we have 5 remaining so i am doing 10 minus 5 over here so we have now five remaining i will take three boxes from here because that's the second largest number so three boxes we can take all the three so three boxes and now we have 3 boxes of unit 9 so we have 27 units out of those boxes and now i will subtract 3 also from my 10. now we just have 2 remaining so i can take two boxes and over here among these two we have taken all these boxes so we are left with these two now over here seven has a higher value so each each box have seven units over here and each box have five units over here so obviously we are going to take seven similarly so when it is going to be seven in that particular scenario we will put seven over here and number of maximum boxes we are left with so seven has four boxes you can see but we can only take two more boxes in the truck so we will take the next two boxes over here in the truck so two boxes in the truck and now we are left with 14 out of uh out of these combination so 14 plus 27 plus 50 here we get our 91 so that's the output so you understood that to solve this with to get the maximum out of all these boxes what we have to do we have to basically first short the array so our array will need to be shorted and over here the shorting will happen based on the second value so our shorting will be 5 10 after that it will be 3 9 after that it will be 4 7 and next it will be 2 5 so when we are doing this when we are shorting the array based on the second value it becomes very easy if we have like 5 total 5 units are remaining to be taken out of ten we can directly take five next we have three so obviously uh we still have more space uh so we will take all of the three units from here next we just are left with two units now when we are left with just two units we will take the rest of the two units from here so yeah that's how we are going to solve the problem so the complexity for solving this shorting is going to be enough login and we are not doing any we are not taking any extra space so it's uh so our space complexity is going to be o of 1 now there while we are iterating through this array the complexity is going to be o of n but the overall complexity becomes n log n so this is our time complexity and this is our space complexity so let's jump into solving the quotient as we have already discussed first we will be shorting the box type array so we have our box type we will short it so we want to arrange the whole thing into descending order so the first value is going to be the largest and the last value is going to be the smallest but the largest value will be based on the second index of the so basically the first index the second value of the inner array so i'll just go ahead and create i'll just go ahead and short the thing using that sequence now you can see this short this shot is happening in the in as a in place operation so the box type itself is getting shorted now i will create a new var which will be able to calculate my total so max total equals to zero and now that i equals to zero so this i equals to zero over here signifies that so total number of uh it's going to help us it in iterating from all the boxes from first box to the next box so because we are going to use a while loop over here so our truck size is something that we know so we can it we can break our solution irrespective of going through all the values we can break our solution uh break our while loop when the truck size becomes zero so we will be basically subtracting one and after another value from the truck size so once we are making the truck size zero then we will be basically stopping the while loop so while loop will x will get executed if truck size is greater than 0 and i is greater than the box type dot length now let's see what will be happening inside this so i can just to create two values to maintain the number of boxes so number of boxes equals to box type so our box type and box types and now so over here we are taking the number of boxes so this is the ith box from the first from the outer array we are selecting the ith box and for that either box we are taking the first value similarly for the ith box we want to take the number of units in each box so number of units will be so we are taking just the second uh the first index of that inner array now we already got to know the number of units attached to each box over here now what we will be doing is if proc size is less than equals to number of boxes sorry number of boxes here number of boxes we will be updating the max total with size into number of units so what we are doing over here for us example where for example where the number of boxes is we have in the truck size suppose like the truck size is two but in the first box itself we got five elements and uh after shorting whatever we are getting in the first box we have five number of boxes in that itself and the truck size is two in that scenario we can just simply take the truck size because that's the maximum possible value we can take we cannot take the number of boxes because the number of boxes is going to be five and the truck size is going to be two in that scenario we should directly take the number of uh number of truck size that we have so whatever is the remaining truck size similarly while we are iterating there are going to be boxes there are going to be maybe for one example we have already seen while we are iterating over here four and seven so we had to just take two boxes out of here so as we have taken two boxes we will not be so we are reducing the truck size in the loop itself so the truck size is going to be of two boxes in this particular scenario so we will be calculating the max total based on the truck size not the number of boxes and else if the value is less than that so else obviously if the value is less than that then we will be taking the number of boxes we will not be taking so we'll take all the possible boxes that can be part of that loop now what we have to do over here in this but in this particular loop itself we will be reducing the truck size in the loop so our truck size will be zero over here because we are taking all of the truck size and over here the truck size becomes number of boxes so on the first iteration our truck size was five we have taken five boxes as five was less over here we have taken five boxes uh of 10 units so our number of units increase based on the number of boxes that we have so we have 50 max total becomes 50 in the first iteration and next truck size becomes 5 because we are subtracting the number of boxes so we have subtracted 5 over here so because of this whole reduction of truck size we have to upgrade the tox size over here and at a certain point our truck size may be smaller than or equals to number of boxes for that specific scenario we are going to make the truck size as zero so this is how our truck size and max total will increase and for i we are just going to write i plus and after all this is done we will just return max total because at the end of the day we i have to get the total number of units that can be accommodated in the truck size let's run the code perfect let's submit the solution and it is running so i would suggest you can just go and check the similar question there is another similar question you can click on that question and solve that question also so thank you you
Maximum Units on a Truck
find-servers-that-handled-most-number-of-requests
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`. Return _the **maximum** total number of **units** that can be put on the truck._ **Example 1:** **Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4 **Output:** 8 **Explanation:** There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8. **Example 2:** **Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10 **Output:** 91 **Constraints:** * `1 <= boxTypes.length <= 1000` * `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000` * `1 <= truckSize <= 106`
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
Array,Greedy,Heap (Priority Queue),Ordered Set
Hard
null
828
hey everybody this is larry this is august 9 of 2022 um and again i'm going to try to do another thing um try to do another bonus question let me know what you think hit the like button hit the subscribe button drop me on discord let me know what you think um and i earlier today i did do a problem already but it was an sql problem so i'm going to try to do one more uh uno mas and one that i haven't done before and it's in premium because i don't know i don't have premium if you want me to do premium forms uh let me know and maybe you could sponsor it because i'm too cheap to pay for it uh yeah let's see no this is kind of i wish we could uh filter these out can you still wait to protect this out i guess not i feel like i look for it every other time but um yeah i mean otherwise this has just been a really slow coin oh there we go okay so today problem is count unique characters of all soft string of a given string let's define kind of for example okay this returns five because okay given the string s return the sum of k where t is okay um this is a hard problem but some substring can be repeated okay uh so there can be only n choose two um thing and each one can be a 26 so given that this is 10 to the fifth it's going to be 10 to the 10 times 26. so it should be so it doesn't ask you for mod but i think that this should fit in long so i think oh huh it's an oh i just read this i missed this i was good because i was wondering about overflows immediately that's why i kind of did that uh but seems like it fits in three two bit insert we don't have to worry about it okay um let's see right so the way to think about this problem in general is just about you know uh the way that i would think about it's just about the contribution of this particular uh thing how do i do it though um and obviously n is 10 to the fifth so you can't really do any like crazy things but you're trying to do it a character at a time uh maybe it takes log n time or whatever but um maybe one way that we can think about is that for each character it is the right side of the substring when this is the right side of the substring what is the answer right or like how many uh what is the sum of all total answer and then here the idea is that okay maybe we have something like maybe this is uh let's just use the word lead code then fine um then here maybe we're up to t or let's say we're up to o right and then here we're trying to find the sum of o c tco uh etco and then ee tco and then this way how do we build this i'm thinking of i'm right now i'm thinking aloud i'm not really an explanation mode per se just because i'm still trying to figure out how to solve this and as you may know i am summing this live so yeah um let's see right well the thing is that okay oh it's not necessarily a great example of this at least in this case let's say we have only code right lead code spelled in a weird way so we would try to solve for oops solve for these things right and then the idea here is that we only know the sum of all the previous numbers from you know the c because all the prefix is going to be c so this o is just the number of so this o is just a prefix of all these other numbers so it's going to be until you find the last instance of o right it's going to be that we only we there's no change in these numbers and then um plus one on all the numbers before the last o right so then in that way um i hope that the explainer way but because this o now contributes because of the uh o in the left there's no contribution in changes right so that's basically the idea and everything to the right is gonna add one so here maybe we'll now construct everything more um from the left so let's say we have l and then l because by itself we have one right and there's no nothing to the left um and then the second one is e so what's l uh so l e we go um yeah so there are two cases where one is e by itself so that's one and then l e that's also another one and this l e is just the sum of the previous one so then here um also sorry this is two right um and this two is just one times odd l and then now the second year right and i think i have the idea now even though i have to be a little bit careful to make or not make mistakes but then here we go okay what happens right well ye is this the third g is gonna be one um and then now because ye the last thing is over here then we just you know almost copy and paste kind of way um you know we just but here we use the two and the one because the last year is you know right next to it so that's a little bit weird um the next one is o of course always one and then you just almost like i said copy and paste again all these numbers um we add an o and because always a new thing for each of them this is gonna be three two and then we just keep track like this and i think we're okay we just have to figure out what is the last element and then do some maps based on that um yeah uh and then like i said and then yeah i think this is okay um like i said the actual implementation we just have to be careful about but it should be good we just have to do the math right so maybe we have something like okay counts is equal to zero times n where n is the length of s and then now we have for i in range of n or maybe yeah maybe that's fine and then we maybe keep a variable name of like last is equal to some lookup table and this just keeps last instance of this character um our last sub c is the previous instance of c or something like this right and then we can go like s of i is the last character if this is in last or if this is not in last maybe doesn't matter let's just do this one case because i know how to do it uh this is not last then this is literally just um counts of i minus one um so for because if it doesn't exist that means that for each of these previous word it's just times uh you know you add one character for each of them so it is the previous case um plus i suppose i'm my i plus one yeah i think it's i plus one uh and i plus one is basically from uh includes the case where you know you're in the life index if you're in the second index for example here um you uh well maybe not this particular case because it has the same prefix but you're in the second index you that means that you there are two previous one and then the current one with one character i think this is it um yeah so counts of i is equal to this um if i minus one you could maybe also create a sample here but it's fine else you go i plus one which means that if this is one yeah this is just one otherwise um and then we said last of s sub i is equal to i right and then else if this is in last then we just have to split it into two right so here um how do we split into two so last sub s of i is to go to the previous index saying right um and we could probably take this outside because we want to reuse this later anyway um let's say this is the previous index so that inclusive of the previous index we do not add one right so that means that counts of i is to go to counts of previous plus um so then how do we so here it's almost like a prefix sum and that let's say there's a zero you want to get to the previous so then you um add one on the stuff here right so that means that you add i mean you could do i think the formula actually is a little bit funky because you would do in a prefix some kind of way it counts up i minus one plus this you know i plus one um or you know this is but this is not a prefix sum so this is this minus counts of previous um so and if you can you know and this is like a prefix some kind of way meaning that this is the sum of all these numbers minus the sum of the prefix like i said prefix sum but as you can see and as i was kind of working out in my head if you kind of saw that for a second that these two cancels out so that means that we can actually just to um so this is actually exactly the same huh is that right that just feels so funky well maybe i'm off by one oh no okay uh this is exciting that part is the same but i kind of skipped ahead this is an i plus one because now you only add one contribution to this stuff that's before so it's something like i minus previous plus one okay that's why but here these two cancels out uh because i was like that doesn't make sense uh maybe i'm off by one but i think that's roughly the idea is that given i've index and then you subtract the previous and i think that's good and then now at the rate and you return some of the counts and i think either we're off by one or we're very close so i think that's pretty much the idea though um maybe a very wrong idea but um i think this is off by one because the unique one is okay and maybe we can even try some other unique things just to kind of show that it's okay but it's just uh it's just this thing so this is probably off by one this is too much i guess huh that didn't solve it huh um okay this is just me being lazy so give me a second um so this plus one uh okay so i minus one is the number of counts in uh let's see let's say i is one two zero one two three four five six yeah so the index is six and then this will be six minus the previous index which is zero one two three but that includes that four number so this is this minus this plus one which is for this minus one um yeah and then i huh is this sweat am i just being lazy and funky and yeah uh okay let's see let's print out counts huh this is very weird but well this three is weird right because they should at least have one extra oh no i mean yeah this should have this have one extra thing so maybe this one is wrong because i think i thought that was wrong and that there's minus one and plus one for itself but why is that wrong so okay so this is one for aba oh did i miss read this problem why is count of this equals to one oh i did misread this well now you saw uh i thought this is the count of unique characters as in okay so i okay so this formula is right it's just that we solved the one or different problem and that this is the count of unique characters that i didn't read this uh example i counted the number of unique characters so that aba would return two but not the number of characters that are unique um i think the idea is the same but we have to make some modification meaning that now when you get to the last um so yes i think this is still right um because if you don't see anything that's just the previous cam plus the current account which is unique right um but if you do see one then you just cut it off so that means that this is actually very prefix summary of this minus times the previous or something like this and here the idea behind here is that once you go to the left of it right um now it still should be right so that means that once you no wait let me think about this i mean the idea is going to be the same though we clearly did it incorrectly but um so this is 2 this is oh this is going to be this minus um well this is just 0 and this is 1 right so then here and this is also one so here we take this minus okay so i think the formula is roughly the same so okay so we didn't really i mean we did obviously solve the wrong problem but it is something that we can fix right so then that means that this is you know now this is 101 and then we added the zero this is now two one two right so then here the idea is that once you pass the previous you have to uncount this number so then now let's figure it out a little bit um let's remove this um so the stuff that is to the right oh i say to the right but all the stuff of none before or after uh yeah after the duping it is going to be this amount yeah so this is the amount to the not dupe and then the duke element is going to be counts of previous minus uh previous something like this right it may be off by one but the idea here is that um to everything to the left of it because this character now you have to do some inclusion exclusion thing actually so that's what makes it tough i can't do this quite like that um but that you have to basically um adds in the previous instance of this because for example if you have like led let's just say threes um in this case you know this as you go to we can't just be like okay this is you go to um you know one year which is what we have here on top but then you have to subtract it from you know l e an extra e and this is before we can just subtract this uh minus one from here because here we already have double e so it doesn't um so we don't subtract right so uh wow this is a hard part i mean i think that's fine but i don't think that um yeah i think this that's fine because we just ha it's not a full uh exclusion um inclusive uh exclusion inclusion principle because i think now after going to previous ones we can uh we're good yeah so then we do this and then we maybe um so how do i say this in a good way so this is the pre uh or no do part there's the do part and then we want to subtract out the part right so it will be something like this minus counts of previous um well we added back in um and this is not the count this is just that for stuff before that is that true give me a second huh maybe this is the wrong way let me think uh because here we this assumes that we subtract all the stuff until the last one but that only assumes that we haven't had a dupe no i think that's fine i think this past the second dupe um i think yeah adding back in the second dupe means that we add in the values before that because here we subtracted too much i think this is okay but we have to keep track of the previous so yeah maybe last has something like this and then here and this is fine i think keeping in mind that this could be none but and i will just one hang on something like this let's see let's give it a spin uh oh yeah this is not whatever point i guess i don't need this uh oh man why that bite is so weird uh okay so this is still the wrong answer but hopefully this is slightly better we can or i mean i weight potentially it's off by one so um yeah let's see right so we're still operating too much uh but aba what is aba um let's we can do this manually and check this answer uh that we are yeah okay apa let me erase this so aba we have a as you go to one and then now we do the b uh we have b uh a b and b so we have uh two and one and then now we have aba which um yeah for this a we have ba which is two and then a is equal to one and then this is also equal to one right and the way that we kind of look at this then will be that um we don't subtract correctly maybe so this is previous i was a little bit lazy on this formula to be honest um so yeah so previous is going to be zero so this is minus zero which is not right it should be this is this plus one because we want to it be inclusive of the previous um okay so this fixes this part but it's still wrong for this part um and that is possibly what num the code oh yeah the third yi is probably why um yeah oops i maybe i shouldn't have done this or like the ways to leave because then now we can check real quickly uh and there's another way that we can actually check pretty directly um as well but um but yeah but this is previous so i think we have to add in one maybe now because we have to get rid of yeah because pre previous is one so we added one but it should be two because of its led prefix um yeah this looks okay for now but let's try a number uh thing where we have multiple even more use so that we don't uh d check that okay so that looks good uh let's see okay hmm okay so i mean now i'm confident just because if it works for that thing it probably is okay unless i missed something like really obvious um that's when it one last time without the print statement so yeah uh let's give a submit but this is a pretty tricky problem to get right wow um i mean this is gonna be linear time linear space um lin uh linear space is unavoidable well at least the way that we did it um but just three things of linear oh i guess not this is linear space for sure um but these two are actually of alpha where our first and number of alphabet um and this is going to be linear time just you know but everything in here is o of one so you know so linear time linear space and that's pretty much all i have for this one uh even though it's kind of solved the wrong problem um and you kind of could see it but hopefully that you see that i work it out by just you know because here um i think this is what i kind of maybe was a little bit skimming on in on explanation um but this part is everything that we talked about with that this is the dew part but this is the duke do part and what i mean by that is that you know uh let's say i have i don't know uh bananas say bananas has a lot of a's right um the idea here is that we have a and we want to subtract um you know we go to n a for this part just the no dew point right and then here we this part is the dew part which will contain b a and a but then here and so the counts are previous is the count that's out here um but we want to subtract out this because you know when we add an a um this a cancels out this a right cancels out all the prefixes on here but the problem is that we want to put back in the ba because when we subtract from the prefix then we sub this number subtracted too much because we also subtracted from a but that means that this a already subtracted from this a before right because you don't want this a to subtract from um yeah so that's basically almost like a inclusion exclusion but not quite hopefully that makes sense um let me know what you think let me know you know your questions and comments and whatever um that's all i have so stay good stay healthy to good mental health i'll see y'all later and take care bye fun plow me
Count Unique Characters of All Substrings of a Given String
chalkboard-xor-game
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`. * For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`. Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer. Notice that some substrings can be repeated so in this case you have to count the repeated ones too. **Example 1:** **Input:** s = "ABC " **Output:** 10 **Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ". Every substring is composed with only unique letters. Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 **Example 2:** **Input:** s = "ABA " **Output:** 8 **Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1. **Example 3:** **Input:** s = "LEETCODE " **Output:** 92 **Constraints:** * `1 <= s.length <= 105` * `s` consists of uppercase English letters only.
null
Array,Math,Bit Manipulation,Brainteaser,Game Theory
Hard
null
426
this is little called pasture for 26 combat binary search tree two-storied combat binary search tree two-storied combat binary search tree two-storied don't linker list this is medium question let's get into combat binary search tree to a surah doctrinal totally link released in place you can think of the left and right for cleaner etcher monuments to the producer and successive trainers in a doubly linked list for socrata berlin released the procedure albert 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 phrase after trance transformation the left point of three nodes should point it procedure and right pointer ship it should appoint a successor predestined is the left trend right and successor is light red you should return the pointer to smallest element of the linked list let's check Radhika jumper want yes she is after child is always small and equal than the loot value and rice child or race are bigger and equal to loot so when if you are travels in order meaning slapped loot right in this case we can get solid value list so we will use the in order and then when it travels in order first stuck here and it going left because clutter and right and then it go in there and then after moving here we able to do from here yeah left to this one year so first and that after getting it going to here and then this one and the first and last check first and last and then this one is current say note this time is not an last load make the new relationship like this and then update rust is this one ba-bing this one is not so make big ba-bing this one is not so make big ba-bing this one is not so make big relation with last with North and the optative last is here and mobile to Otis here then make relationship and same a last here not here make relationship then after finished Travers plus teenies we make relationship first with last and then our in the convent the transformation is done at this time complexities and is a cart mode of three it travels just one time so time complexity is an space and then space complexity also end because even it is in phrase but we use tremors a silly question so the continuous system step and worst case that sub 3 is the same as countable load of tree when the left when Duty is a left buyer so I screwed right screwed this is the same as length of load so that is legion y space complexity and implement here first how we do first long and then last long now make two pointer pointing Lord and I will make I gonna make helper the Christian function argument is long and because it has two part base case and any creature relationship base case is it not a small the minister with traverse the late Lord out of licked Lord I will return and that he noticed left not right so we need to go left side forest go to play and then we do something and in this case we update you the first and last winner and when we cut last pointer we will make do Elijah with last pointer with current Lord so last noticed indicate here that Pam daughter must be here so that is the time we needed to make relationship both of them so in this time last right next is right is Lord PPS is left is last otherwise mean is it lasts till gone 10:00 be nice notice lasts till gone 10:00 be nice notice lasts till gone 10:00 be nice notice first notice the first so frosty indicate to all and after finish their after make relationship I will update last is Lord for next step if you make sense and then I recall helper and finally I will make relationship first and last first to left is last to make superior last next is right is first and return first but there is one edge case if root is none is there any work while or output is valid odorless check first last is okay helper would even dishonest notice okay because when note is not it just return but problems here first is turn on because it had processed no chance cap to load because it cannot go in inside of this module so it occurred a long time era so we needed to prevent edge case okay let's check okay oxy first last to use robot very awkward here thank you
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,748
hey everybody this is larry this is me going with q1 of the bi-weekly me going with q1 of the bi-weekly me going with q1 of the bi-weekly contest 45 sum of unique elements so in this problem you're given an array of nums and you have to just keep track of uh the number of elements that or the sum of the elements that only appear once so there's definitely a lot of ways to do it and depends on your uh language and therefore your library and stuff like that notice that n is less than 100 um and also each number is less than 100 so you could put it in an array if you like but the way that i did it is using python magic i just put everything in the calendar which basically maps uh it became it becomes a frequency map of basically each number and the frequency and then i went for each item and if it only appears once i add it to the total you can actually reduce these five lines in one line but um as i was trying to speed one through it during the contest um i just kind of did not because i wanted to make sure that i was right and you know getting it um having a typo would kind of suck but you could but i'm going to try to maybe do some up solving here so you could probably do something like this um you know uh if y is equal to one um x and then some so this would be your one liner i think uh give or take um let me one run the code real quick yeah so if you really want to reduce this to one line and this would be it um but again this is i think this is straightforward um if not let me know if you're having issues with that then definitely um definitely practice your libraries and just hash tables and stuff like that i think these are very fundamental so you really need to uh you really need to be very good at it maybe not as good as well not as fast as i did it during the contest which you could watch afterwards but definitely um you know would say within eight minutes or something like that um if you take longer than that um you know make sure you get your fundamentals um okay that's all i have for this problem um yeah and you can watch me sub it live next thanks okay let's focus let's go um okay this would have been a very quick thing too but oh well four zero fifteen let's go but um computers hey uh thanks for checking out the video uh let me know what you think about this problem any anything at all i hope you had a great contest and you know as i always say stay safe stay healthy um you know to good mental health and take care of yourself i'll see you next time bye
Sum of Unique Elements
best-team-with-no-conflicts
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Output:** 4 **Explanation:** The unique elements are \[1,3\], and the sum is 4. **Example 2:** **Input:** nums = \[1,1,1,1,1\] **Output:** 0 **Explanation:** There are no unique elements, and the sum is 0. **Example 3:** **Input:** nums = \[1,2,3,4,5\] **Output:** 15 **Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
Array,Dynamic Programming,Sorting
Medium
null
509
hey folks what's up in this video we're going to see about how to approach a Fibonacci problem in the lead code will start by actually discussing the recursive solution and its time complexity and then we'll further move to the better approach and then finally we'll end this video with the most optimal approach so till then if you're new to our channel do hit like share and subscribe till then enjoy the video so now let's understand the problem statement as of late code now in the late core it says that the Fibonacci number denoted with f of n will form a sequence called Fibonacci sequence plus that each number is the sum of the two preceding ones that means I want to find the value of the third number I'll need the first two that is one first number and the second number right that means we need at least first two values you know to find any other values right that is why by default it is already mentioned that F of 0 is equal to 0 and F of 1 is equal to 1. now as you have discussed here it is the sum of the two preceding ones so if you want to calculate the value for f of n in a general way origin in a generic manner we can write that it is a sum of f of n minus 1 and F of n minus 2 that is basically the sum of the two previous elements for the numbers right so let's now consider this example n is equal to 2 that means if we want to find the value for n equal to 2 what we need 0 and 1 right so F of 0 is 0 f of 1 is 1 what is the sum it's one right so n for f of n equal to 2 we get the value of 1 and the explanation also States the same that F of 2 is equal to F of 1 and F of 0 that is 1 plus 0 which is equal to 1. now let's consider the example number two that says n equal to three now you can see like for 3 we need the value of f of 2 and F of 1 right now for understanding this example we can consider this previous example like for f of n equal to 2 we have already defined upon the value that is equal to 1 right and now for f of 1 we already have the value of 1 right so what is the sum of them that is 2 right so that is why F of 2 plus F of 1 that is 1 plus 1 is equal to 2. similarly if I am going to find the value of for n equal to 4 I will need F of 3 and F of 2 so F of 3 is equal to 2 and F of 2 is equal to 1 so 2 plus 1 will give us 3 that is what it is stated right here as of now we have already had a problem walk through in the lead code and now let's understand this recursive tree approach how to solve this problem using recursion and then we'll be considering different ways in order to optimize our recursion so let's get started with this recursor tree imagine we want to find the value for f of 4 right so as you have discussed earlier what are the values that you need to find F of 4 we need F of 3 and F of 2 right similarly for finding F of 3 we need F of 2 and F of 1 so I can say that for each of these node right I'll have two branches because these two branches will ultimately have an impact on the solution of this current cell right so the number of branches it is getting divided into are the number of things that are it is dependent on right so I can say this like if at all I need to find F of 4 I'll need F of 3 and F of 2 so for every node I have here I'll need its following or previous two numbers so at each level it is getting divided into two in this case F4 is again divided or broke down into different branches that is f of 3 and F of 2 similarly F of 2 is broken down into a 1 and F of zero and now we already know the according to the base condition what is the value of f of one and F of 0 it is 0 and it is 1 so I need to find the value of 2 we need the sum of the previous two elements that is one plus zero and the value is returned here so F of 2 is 1 right similarly F of one value we already know from the base condition it is 1 so 1 plus 1 will give us two right similarly if I go for f of one and F of 0 we know that these values have a value of 0 and 1 as per the base conditions this will be summed up and it will be transferred here so F of 2 will have the value of one similarly F of 3 is 2 F of 2 is 1 so we'll combine them and we'll get the value of 3 because we are summing up the values of two nodes in order to find the next node so this is how the recursion works here now let's understand what is the time complexity now to understand the time complexity let's analyze a very simple approach uh to analyze the recursion time complexity It is Well found or determined that it is a simple trick like to know how the time complexity will work in the request entry it's basically the number of branches number of branch raised to the power the height okay so this is what the time complexity of any recursion would look like see in this case the how what is the height it will be maximum four because at last 4 will be get divided into like it will get divided into 3 and 2 N again 3 will be divided into two and one similarly if we find like this is the height is 4 for this 3 right the height is 4. okay I hope you know how to calculate the height uh if not you can always watch my previous video generator video you're always going to get an insight about how to calculate the height so what we do basically we take the maximum of left and right and add one to it and return to its parent to know the height right so if I do that we will find that the height is 4 here similarly that means like the height is n in this case so if I want to find the value for 4 F of 4 the height of the tree is 4 similarly if I need to find the value for Min height is 4 so if I want to find the value for f of n the height of the tree will be n right so we have already discussed like now to find the time complexity we need the height and the number of branches that is each node is getting divided into so we have already found the value of height that is n with respect to the value that we are going to find and now the number of branches here is 2 because each time we are dependent upon the previous two we are dividing each cell into its uh recursively into its two subsequent previous cells and further it is getting recursively called again and again so each time we are actually dividing each of these nodes into two different branches so the number of branches at each node is 2. right so as of now what I've discussed is like to find the number of branches and the height and once we have those we can always have the time complexity now according to the formula we have discussed above that is the number of branches raised to the power height we have this time complexity of this recursion tree as 2 raised to the power and this is what the time complexity of this solution is now let's go over to the recursive solution in the lead code and try to implement this approach and solve them now we have already discussed like how the recursive calls are being made and how we can draw the recursive tree and how I can also estimate the time complexity of this recursive approach so let's now head over to Fibonacci number in the lead code problem and let's do the code okay so now uh we have already discussed like what would be the best condition as we have already mentioned with the best conditions that for f of 0 and F of 1 will be having the value of zero and one so in short I can write like if n is less than equal to 1 return and so what the statement means like if n is less than equal to 1 that means if n is either 0 or 1 in that case if n is 0 then it will return 0 if n is 1 then it will return one that is what it is and that means like if n is less than 1 and it will return the value of n Only so whether it is 0 and 1 it will return according to that okay so now let's uh go over to our uh recursive calls that we have discussed now how this recursive calls are dependent so I'll say like for n I'll need n minus 1 and N minus 2 right how why we need because uh we have already seen that it is the sum of the two pressure two preceding ones right now we need the value of 2 and we'll sum that out and return it so that we get the value of Fibonacci of n right so let's write that value now I'll write return fib of n minus 2 plus above n minus 1 and this is what will give me the value of f of n right because the sum of the wave of last two numbers will give out the value for f of n so let's give our run go and hit run now you can see all the three cases are passed now if I'll hit on submit let's see what happens it has taken it is accepted now but this isn't the optimized way right we are only doing the recursive approach calls and we are only writing the recursive solution but as you have already discussed the time complexity of this is 2 raised to power n because the branches each time we are getting two and the height may go up to n rate so this is what the time complexity of this solution is so it isn't enough and it isn't optimized yet so now let's look into the optimized more optimized version of this and then later on we'll see the most optimal one now in the previous video I had already made a video on the three-step approach to video on the three-step approach to video on the three-step approach to store solve any dynamic programming problem in that approach I have already discussed like how to convert a recursive solution into an optimized manner using a data structure depending upon the number of variables that are getting changed so if you haven't watched that video I highly recommend you to please watch that now let's uh Implement that approach here and let's optimize the solution now we have discussed like what are the number of values that are getting changed right so now we can see like only n is getting changed in the recursive calls we are making n to n minus 2 and N minus 1. so we need only a 1D one dimensional array or a one-dimensional data structure right so one-dimensional data structure right so one-dimensional data structure right so if at all I am going to declare it here right so let's not do like this uh let me copy it here uh let me declare a vector of let's name it as DP and let's uh give a size of n plus 1 and initialize it y to minus 1. and Y have I initialized it with minus 1 because we already know and we have already discussed in the previous of the three-step approach video as well like three-step approach video as well like three-step approach video as well like we need to initialize the data structure in such a value in which the that initialized value wouldn't appear in the recursive calls that means for any of the recursive calls this minus 1 or any value I have initialized here should not come as a result right we already know like the minimum value that you are going to have is around 1 and anything bigger than this will always be positive so we can take minus 1 here right okay so now I have initialized this uh DP array uh with minus one okay now uh let me make another function here let's call it as solve okay let me pass it as n let me pass this Vector as well I am passing it as a reference okay now let's uh paste the recursive code we have done now we need to change this FIB to solve here because we are doing a recursive call in this solve function and so we need to change the name of this functions as well right now it assign everything is good and also we need to pass here the second parameter as DP here as well okay so far so good it looks good to me now we can actually you know what we can actually now call this uh solve function here let's call this solve function here we pass this DP value and now we'll just return the DP off n here okay because we need the value of above n and the Fib of n value will be stored in DP of n right okay now we know the base condition is this and this is the uh recursive call that we're making now we have already discussed like we need to check right like if at all for that cell of that data structure that array if the value is not minus 1 that means that recursive call or that value of n is already being calculated we don't need to recursively call it again and again we can just return it from the data structure we are using to optimize it right so we'll do the same thing here I will write it here as DP of fdp of uh n is not equal to minus 1 right that means the value has already been calculated and the recursive call has already been made and it has already been stored in that DP array right so we don't need to call it again and again we'll just return that value from here only right if at all it is not getting calculated we'll just do this recursive coordinator to find that DP of n value all of above n value and we'll store that in the TP so that next time we are going to call for DP of n we don't need to call this recursive function again next time it will just check here and you'll find that it is not equal to minus one so it will directly return from here so now let's give it a shot here and see how it works okay all the three cases are getting accepted now let's click on submit okay so we can see like for n is equal to 0 output is -1 and why it is the case to 0 output is -1 and why it is the case to 0 output is -1 and why it is the case because we haven't updated the DP here for the base conditions so I'll now write here for DP of n just store it in DP of N and then return it similar to this so we are basically we are previously not basically storing the value of 0 and 1 in the DP array but now I have updated it to this one so that every time even if in the base condition it will check and once it gets it will update in the dprm okay so let's now run it okay let's now submit it I think they should work yeah it does yeah you can see bits 100 because it is all optimized now we have already you know like did a great optimization here but uh the problem is it is not still the optimal way now here the time complexity is n why it is n because previously in the recursive solution we were calculating for each cell two times like there were two branches so you are recursively calling for each of its predecessors like for n while calculating for n minus 1 n minus 2 and recursively it is getting calculated for every cell even if it was calculated earlier but now in this case you can see like the value of any of this n value is only calculated once not twice so there is no two branches that is forming for each recursive cause that means if at all I have a value for f of n to uh calculate I'll only have to call F of n minus 1 and F of n minus 2 once in the entire recursive call or recursive tree right we don't need to calculate that particular recursion function again and again that means for each value like let's set for DP of 0 or dpf1 or dpf2 or let's say up to DP of n we are calculating only one function the whole entire recursive function call that means the time complexity is n and as the branching is not there so there is no exponential form here in the time probability thus we have a more optimized way of the previous solution and now we have the time complexity of n now this isn't enough why because it is using an extra space of n right because of n now we need to reduce that and we need to take it back to Big of one so as to have the most optimal way so now let's see into the solution where we can have actually the time complexity as big of N and extra space as a constant that is bigger of one now before directly going into the coding of the solution let's understand the previous optimal approach we have used array only array where we store the value now let's think do we actually need this entire array for every value we are calculating let's say I am calculating the value for n I only need these two cells right I don't need the remaining ones but even if our value is let's say 100 we are storing or making an array of 100 even we if we don't need the previous 97th one what I mean by that is like for calculating n we only need n minus 1. and N minus 2 right we are just ignoring all the values from 0 up till n minus 2. right we do need that now the previous approach that we have did just imagine the case if the value of n would have been 100 we would have made an array let's say of size 100 right but we actually need a size of 100 because we are only needing the value of the last two elements in the eighth step we are just ignoring the rest right so do we actually need that no right we can also do it with the help of two values two variables right let's say I have a previous value of let's say P1 and the previous to previous value as P2 that is this one is denoting to n minus 2 and this one is generating to n minus 1. just imagine can we do it with these two valuable variables yeah we could because every time we are going to find the value of n we only need the last two values and each time we are proceeding we need to update these values actually right each time we are proceeding with the next value we need to change the value of n minus 2 that is P2 with this one and the value of P1 should be updated with the new value that you have calculated now that means oppose for now n we are using n minus 1 or that is let's say uh what let's say or let's say for calculating n we need the value of P of 1 and P of 2. right once we have calculated the value of a of 1 and P of 2 let's say now we also want to calculate the value for n Plus 1. Now using these two variables how can you do that now see for calculating n plus 1 we need a net value and the previous month value so the previous month value is P1 right now how to use these two values you need to get this value now what you can do is we can store the value of n minus 1 in the N minus 2 Earth variable that is P2 like p1's value will be stored in P2 and ends value will be stored in P1 so in this by doing this we can ensure that the value of n is stored in P1 and the value of n minus 1 it's stored in P2 and see we need n and n minus 1 in order to get the value for n Plus 1. right because these are the most recent consecutive number previous to n plus one the numbers that we need and the sum of the numbers that we need in order to get the value for n plus 1 right this way we can just transfer the value of P1 to P2 and the value of newly calculated n to P1 in order to ensure so to get the value for the next value right okay now let's go over to uh it code and let's update our solution with the latest ones okay let me just remove this function as well um okay like we have discussed right so let's make two variables div of one and pre let's initialize it the values are 0 and 1. because these are the two basic values that you need right let's also write a condition here like if n is less than equal to 1 you can return just n here first to just uh you know just to manage the initial conditions for zero and one now we have the value of preview 1 as 0 and pref2 as 1 right so now it's uh you know like let's have the value of I is equal to zero Let's uh let's think like what should we start from right if at all I am starting from okay let's make another valuable the I don't need that variable actually okay so let's uh start it from here uh let's have int I is equal to um com 2 right there's an n then equal to n because yeah like we also need value for Android let's understand this now if at all the value is 1 or 0 we are returning from here right but if at all we are having a value greater than 1 that is from 2 until n we are considering this for Loop now let's understand this now say take if at all eyes value is true what we'll do is um value that is the result for the current I that means the result will have the value of I right I hope you get it and for getting the fibof I will need the previous two values of one plus three of two right now we have the result or the FIB of i as this right now in the next part what we need to do make sure that okay the naming conventions are a bit tricky here so let's hit previous to that is previous to previous of this one as zero and previous just previous one as previous one right what I mean by that is I am calculating the another value so just the previous one will be denoted by previous one and previous to previous will be denoted as previous two right I hope you get it now Let's uh make the changes and update the values pref2 and pre 1. so now let's review one let's make one updated with the result why because we need the last reason to values right so every time we are updating we are just going in this Loop and we are each time we are calculating the result of the wave of I and we are just returning it now imagine if at all we have reached the I value of n the same case will be calculating the value of these two right we'll be updating pref2 with brave 1 and pre 1 with the address result now let's imagine and say you know why because at the end of n we are storing the final result in Pre one and after that this Loop will get a uh you know like uh get completed and this the code flow will get out of this block this for loop block it will come here so here when it will just return wave of one right so run it here I hope you have understood it and it is saying it is accepted let's go for submit let's see whether it works or not I think it should yeah it does okay yeah it worked fine don't go for this uh beat 65 percent it's just so randomly because this is the most optimal one because this is indirectly or directly address taking the value I'm completely as n because we are only iterating once that is up to n right so it is taking a Time complexity of n and the space complexity is constant because we are not using any array or any other data structure we are only using the variables and restore the most recent value and calculate the next value so in that case the space complexity is Big of one I hope you enjoyed the content this was it for this video I'll see you in the next video till then stay safe stay tuned
Fibonacci Number
inorder-successor-in-bst-ii
The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given `n`, calculate `F(n)`. **Example 1:** **Input:** n = 2 **Output:** 1 **Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1. **Example 2:** **Input:** n = 3 **Output:** 2 **Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2. **Example 3:** **Input:** n = 4 **Output:** 3 **Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3. **Constraints:** * `0 <= n <= 30`
null
Tree,Binary Search Tree,Binary Tree
Medium
285
20
welcome to january's leeco challenge today's problem is valid parentheses given a string s containing just the characters uh open close parentheses brackets whatever determine if the input string is valid an input string is valid if open brackets must be closed by the same type of brackets okay and open brackets must be closed in the correct order now what does that mean well if we had a open parenthesis the next character should be a closed parenthesis of the same type so all of these are going to equal true this one's going to equal false and this one's also going to be false even though technically we could count up all the characters and see and open and close one we can map each one but it's not in the correct order so if order matters what's the approach that we should take well um basically as soon as you see this problem it's a classic problem you should think of a stack approach relatively quickly the reason we want to go with the stack is we want to check the last in and check to see if we could pop that off with a closed parenthesis so what i mean by that is there's two types of parenthesis here right there's an open and there's a close now there's three types of those and when we see an open one what we're going to do is add that to some sort of stack so say that we have this one we're going to add that to our stack here and the next one should be a closed parenthesis for it just to be valid so if the next one is this what we'll do is pop this off our stack so we had like open cl open parentheses and the next one is a closed parenthesis then we can just pop this one off and that's going to have this one left and the next one is another closed parenthesis we can pop that one off at the very end our stack should be empty meaning we've accounted for all the parentheses so the trick here then is to differentiate between open and close and return to false when we find that there's a mismatch or if we have a closed parenthesis and our stack is empty because if we um have a closed parenthesis but our stack says there's nothing in there that means there's no way we could ever account for that close parentheses right that's going to be an instant false so to make this a little cleaner what i'm going to do is first create a mapper and i'm going to map each closed parenthesis with the open parenthesis and i'll show you the reason why i do that in a little bit so let's take our closed parenthesis which are going to be this one this bracket and this squiggly bracket and we want to map that to the open one right here now we don't actually need to do this but this makes it a lot cleaner basically we want to start with our stack and that's just going to be an empty list now for each parentheses in s what do we want to do well we want to first check to see if it's open or close and i think we'll start off with a close because that's what's going to be able to tell us if we should return a false pretty quickly so if the parenthesis is a closed parenthesis so if p in let's say mapper because that's going to check to see all the keys we want to see do we have something on the stack at the very end that we could pop off so if not stack that's just an instant false right because like i said we can't ever account for a closed parenthesis afterward otherwise if the p or i should say mapper p if this closed parenthesis is equal to whatever is last on the stack then we could pop it off right here pop off whatever's on the stack and that accounts for the open parenthesis and the closed parentheses otherwise we can't do that so that's actually going to return a false and we can actually clean this statement here up a little uh what we can do is instead take this up here and make this an or and say if it doesn't equal what's on the end of the stack then return to false otherwise we know that we could account for it so we'll pop it off now we need to take care of the open parentheses and what do we do with open parentheses well literally we just always append them we just append our open parentheses on there because we want to check to see if we can account for it later and we don't know that until we check the next parenthesis afterwards we want to check to see if our stack is empty and if our stack is empty that means we could account for every parentheses so this is going to equal a true now let's make sure this works looks like i made some syntax errors there and it looks like it's going to work but let's go and submit that see if it does and there we go accepted now time complexity wise this is o n and it's constant space because the only memory that we well actually it's not constant space i guess it would be of n space because of the stack but unfortunately i don't think that's something we can avoid even if we do this recursively which isn't advisable could do it um even if you do some sort of recursive approach you would still need memory right to record the previous stack or the previous pregnancy all right i think that's it thanks for watching my channel and remember do not trust me i know nothing
Valid Parentheses
valid-parentheses
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. 3. Every close bracket has a corresponding open bracket of the same type. **Example 1:** **Input:** s = "() " **Output:** true **Example 2:** **Input:** s = "()\[\]{} " **Output:** true **Example 3:** **Input:** s = "(\] " **Output:** false **Constraints:** * `1 <= s.length <= 104` * `s` consists of parentheses only `'()[]{}'`.
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
String,Stack
Easy
22,32,301,1045,2221
35
hey everybody this is Larry this is day 10 of the litko daily challenge I'm back in New York just to give you a cube heads up I don't know if you care if it's fine but I hit the like button hit the subscribe button let me know what you think let me know your thoughts and all that stuff in general let's get bite to it search insert position given are sorted away in the target value we turn to index if the target is found if not return the index player would be if it were inserted in order you may assume those duplicates in their way okay cool so this is another way of just saying given a number of given a target find the and there's no duplicate away so there's no duplicates in their way so find a number in which it is bigger than all the numbers smaller than it right so in this case it is 2 is smaller than or zeis to it all right so in this case it's 5 so the 2 means that 4 index 2 or the numbers to the left of that is smaller so we just have to do that and given that the array is sorted you can do binary searches you could probably predict and if you practice and that's good and for me I always have issues about buy one and some like that so let's go for it together let's practice it together I also want to point out though that in a lot of languages and C++ in Python and probably even Java I'm C++ in Python and probably even Java I'm C++ in Python and probably even Java I'm not sure about that one I think there's always that binary sort of search but any case my point is that in a lot of languages there is a built-in library languages there is a built-in library languages there is a built-in library for this but of course if you're practicing for interview if you're practicing binary search in general it's good to kind of do it because for competitive programming you're gonna have to binary search for something that you cannot just plug it into the library sometimes so it's good to get that practice on it's good to practice kind of where your edge cases are and stuff like that so I'm gonna do that here cuz I sometimes still make them those mistakes sometimes so yeah ok so now so let's just so there's a lot of dependent so there are variations I wanna say which is done it depends on and that determines how you white the coat so that's just white a tile here for me target find the smallest index in which target is greater than ordinal numbers to the left or the smaller index is that true because I would make sure that I'm okay so that I just wanted to see what happens if like for example five and five so technically if it's just you code then you can just do it yep yeah then I always find my stuff the same you have to figure out how would you like to write it and what I mean here is that usually the head will be zero I guess because it's always it's usually way inclusive you may come out of cases where it isn't better that's just my reaction and my tail which is my second half it is exclusive meaning that this element is not going to be ever be a real element right now and I make that distinction slowly and deliberately because I think some a lot of where I make mistakes but binary search is these off by ones right these are by one so you have to define exactly what your things are in this case it's just inclusive meaning sales in our range and then here this is just N and in our case and it's not in our range because it's because n minus 1 is the last index so that's exclusive that's what I mean let's do and a couple ways to write this getting the midpoint I just write a standard a I know this is an overflow issue and stuff like that so it's about in your language you might be okay you may have to think about it and Python is okay and in this case and it's not going to be bigger than overflowing way range anyway and here sometimes I see people do this thing where they do with MIT is you get a target we turn MIT and that's fine but think I depend on what you're doing it but for me it just kind of it helps to be just do it keeping your binary so that I keep it stupid simple for myself you know your marriage way where we so do it for yourself and here I'm just trying to help myself visualize so let's say you're given their way and then they say I'm it is five right what does that mean well and the mitt is five we that means that the search is over so maybe this is not a great example but it's such fun to first to let's say this is MIT well if this is MIT then we know that it is gonna be to the left of me so we can do that okay if nums of me is greater than target then we want to move the tail to make so that it just keep track of the left point right so taro is here to MIT I always head is equal to me well otherwise if what's the other case dedicates this one every search here and then we want to keep the entire thing maybe this is a bad example but that's a jump one and Jeff five well in this case you get away around six right and where we do it three well in this case we want their head to be exclusive of three because my doing now we won't head to be exclusive of today yeah because if it's smaller then it still is gonna be true right because in theory like that's a good numbers for then you still want to keep to wait because well that number is that girl be the case for five okay so those are our two cases what about the equal case as we said now that we have a better parent I guess it doesn't really matter because of its equal then the stories were consistent well we want the mid still to be in it so in this case because our head is inclusive we will just put on the head so with Chico is should be going through the head and that should be okay so that's our cases and we also because this will never converge because they're both one MIT then I just wanted to make this so that it goes to the plus one site okay so now we just have to return hey I think that's it and that's put on the other test cases well we like time limit exceeded so maybe I do have still an issue that's okay well that's now let's take let me tell him exceed it so why is the time limit exceeded well because head and tell would never merge because we always take them in so we just have to do it first one yeah that's a little bit off so I think that looks okay having the tricky fingers did you quote case in this case we cannot do you co anymore or we cannot assumed equal to being met so we just have to do this way because then now we want tail to now that we redefined it head and tails are a little bit different okay then now we do head plus one well as I said that's why these things are little tricky okay I think even though I said earlier that I wouldn't do this but I think for me to kind of help me to point this I will do if you go to Target let's just return men and then now this should simplify the case a little better no guy hmm okay so let's go through first principles again like I said binary search that kind of tricky sometimes even on where your obvious once okay so we want the head to be inclusive so now we don't have to worry about it so let's just say this is our case let's say we're searching for four well four and we're pointing at five well we're pointing at the five that we want to continue well the mid is bigger than thousand in the tail will go to here so that's right okay and then let's say we've got it to wait then actually want to move to head to admit so okay so this seems okay but yeah maybe I just did two plus one hmm looks like I need a more practice but why doesn't this converge oh because the head is zero and Tara zero to one I would never converge no that's not yeah for science let's print it out so we could my excuse is that I'm just waking up from oh and now waking up I just got back to New York so is my jet lag but ok so zero m14 this is the second case I guess that's what we expect and with 0 &amp; guess that's what we expect and with 0 &amp; guess that's what we expect and with 0 &amp; 1 the min is 1 so it's gonna want to tell to be 1 so ok so yeah we definitely need this what a way to do it is I do this I'm gonna convert designer the reason why so the reason why I say stuff like that is because you need to figure out a way such that it always moves by one in each step and in this case we don't really have that so hmmm I think in desc I think that's why so this has to be negative one and then this will be plus one but that's a little bit awkward I think what I usually do in this case and that's why I have been trying to avoid doing this it's just shift everything by one to make it a little bit more explicit because basically the reason why is you end up with a number that's before the earliest number well--don't earliest number well--don't earliest number well--don't where our definition makes it so that it always happens after the first number so because of the way we structured it we never checked the first element and this allow us to do it but this is not that clean I think what I would actually like instead is to shift everything by one so then you don't get this negative one which is a little bit harder to read and plus 1 everywhere but ok well I hope you had a good better time good idea let's submit this just for ya ok so that works yeah a little bit rusty I just got off 33 hours of flying and traveling so that's my excuse but uh but that's why I always say and that's why I always give myself the opportunity to practice binary search there's little things like this that makes you really think about it and why they like why does it happen that you haven't off by one on binary search way but as you do them more and more the next time you do it over like REI I remember the last time I did this because I didn't search for the first element so they have to do you know negative one or just pressed or the indexes plus one or something like that way so or another way to do it maybe it's just two and other numbs like numbs as you go to negative infinity post numbs so that your invariant holds that you don't you always be behind one number then it would be true but so there a couple of ways to handle these and the ways I do you want to get to it's gonna be there you know it's gonna come from practice and just going for these cases even as you see how I go for my cases when you go for those cases you're like okay so this is why and then you allow yourself to kind of already talk about it next time so when you see it next time you're like oh yeah I did this before right so there's no secret there's no tricky I mean it's you thought about it just not during the contest right or during the interview you thought about it a long time that's what practice gets you cool so this is binary search this is query log in space is also of one let leave me in the comments if you think I need to describe that more but I am a little bit tired I am a little bit jet-lagged so hit the am a little bit jet-lagged so hit the am a little bit jet-lagged so hit the like button hit the subscribe button let me know what you think let me know how you did it let me know how did you handle that you're off by one edge case because there couple ways hand oh and I did it this way it feels a little icky but as long as you able to keep a consistent model in your hand it's okay anyway hope everyone's having a good time and I will see y'all tomorrow bye
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
7
210 Videos Can See How They Can Do With Sophia Not Seen More Revenue and 100g Tube School Will Take a Simpler Than Adhir What We Can Do the Result long and subscribe the Channel Please subscribe and subscribe this Video not Who is the President of Superhit 100 Ventral Access Medical 204 Ki And What Will Be Doing Hair Oil Updater Result Every Time I Saw 200 Oil Multiple Red Button And The Right Master Digit Amazing Models Had Good Relax Acid And What I Can Do You Can Update A Large Divide In button hai hua tha ashok ne center log to indra and rate so what they can do to sacrifice of you have caused soil obscene result sauce grated ginger dot max value is 200 spontaneous and problem valid and related entries a dot which determine impatient 108 subscribe now To receive new updates time to you a text message kal aa jo akh or whatsapp number hai hua tha to kab hua tha
Reverse Integer
reverse-integer
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`. **Assume the environment does not allow you to store 64-bit integers (signed or unsigned).** **Example 1:** **Input:** x = 123 **Output:** 321 **Example 2:** **Input:** x = -123 **Output:** -321 **Example 3:** **Input:** x = 120 **Output:** 21 **Constraints:** * `-231 <= x <= 231 - 1`
null
Math
Medium
8,190,2238
1,038
hello friends so today in this video we're gonna discuss another problem from lead code a problem on trees problem name binary search tree to create a summary so as you can see in this problem statement you are given a binary search tree and you have to actually convert this tree into binary sum tree what this binary sum tree means that i like every node so like you have to follow up this following condition the binary search tree is actually a tree which follows this condition which means that every node on the right side is greater than the every node on the left side uh and that's the whole uh binary search tree but you have to convert it to a greater tree such that the every key of the original bst is changed to original key plus sum of all the keys greater than the original k in the base it actually means that every tree is now replaced or every node is now replaced with the summation of all the nodes or like all the node values which are greater than that so as you can see then six plus seven plus eight because these nodes values are greater than this so the values at this point is now six percent budget now value at this point is five plus six plus seven that eight value at this point is 5 6 7 8 4. i hope you get the point so every node is replaced with a new value which is the summation of all the values which is greater than that value so it actually means that you have to first go to the right most node which is like the node value of that will not change because there is no node which is on the more right which is can be like even more greater because you have to ensure that in a binary search tree every node or every node value on the right side is greater than the node the root value or the current value on which you are and every value on the left side is smaller so if you go to the right till the right most node then that's the maximum value then you have to somehow transfer this value to the previous node so it's like a recursive way then transfer this value to this node okay so it means that now for this total summation you have to transfer to this node then take out this total summation transfer to this node so it means that you have to first go to the till the right node then you have to first when you have processed all the right nodes like then take the summation of all the right nodes value add it to the current node value and then send it to the right let the left node value okay so i'll tell you with the example or like with this example only uh so what you can do like it's just a recursive function you don't have to worry about much but if you know like the basic recursion entries most of the questions can be solved using equations in binary search type of trees and what you can see in this problem is uh like i can show you with the code part also but we will also draw some example to make it more clear but see this is the like this is the calling function of this dfs this is the root because you have to change the node values and then you have to return the same vst so that's why i'm just saying changing out the values and then returning out the same tree so that then this is the global sum because we have to transfer these some value what is the current sum till now because we are transferring from right till left it's like transferring from this point till this point transiting first all the right nodes and then going to the left nodes and then storing out all the summation for all the right nodes so that we can add it to the left nodes so that we are just adding all the sum in this so if the current node is null we just retreat or not because that's the base condition but now we have to go till the dfs we then we just again call this dfs function again and again till that we reach a node which is not having any right node and when we reach that node what we'll do we will add that node value to this sum because that node value will be transferred back to the left node so that's what we are going to do we will add now this summation value because see if we just take this example only we will go to the fourth node we'll start from the fourth node go to the right node okay go to the right and again go to right now then again go to the right one then there is no right node so take this node value and there is again the summation value which is initialized to zero then what we'll do because there is no some value we'll just add eight plus zero which is like adding out what is the node value greater than 8 0 there is no nodes so we will add 0 this node will remain the same which is 8 and then we will update our sum value because what is the total sum we have seen till now because which we have to transfer back 8 because now we have to transfer this 8 back so now we have updated my sum to the root value which is 8. okay now we'll go back because this is a like and then we'll call the same function for the left side because now this node is storing out the new value and then we'll transfer this new value to the left side okay so as you can see there is no node in the left side so we will just recursive back recurs back now we are on this value now for this value we have transferred all the right values now we have to go to the left part before going to the ref part we will update this current node value the current node value will be updated with the current node value plus the sum of all the nodes on the right side and all the nodes right side values stored in sum so what we'll do our updation of root sum root value current root value with sum it will become 15 and then we will update my total sum what is my new total sum a total sum will become 15 so i will update my sum with 15 which is the root value and then we will transfer this to the left hand side but there is no left hand side so we will recurse back if when we reverse back now i am on this node now this node is like at this point so what will what we'll do for this node value is actually now the summation of this node plus all the nodes value on the right side the on the road right side is 15 plus 6 which is now become 21 so now my total sum on the right side will be 21 and i will send this 21 to the left side so we will again call this on the left side and then from the right side i will also go to the bottom to all the right sides val on the right side recursively again because for this value i have also have to like find out all the node values is greater than that but because of the binary system all the node values which is greater than that are on the right side so we'll also find out the sum of all of those values and then add it to this node so the node value of this will be summation of all of the right values and the node value coming from above also because those values is also greater i hope you get the point and then we'll go to the left side and so on because that's just like simple recursion function you the recursive function is not too difficult but the logic is you have to understand and like uh dive deep to understand what is going on in the tree you just have to in all the recursive problem just boil down this tree into one out like two three nodes don't look over this whole node just draw one node one two nodes there and one node here just four nodes one two three four and then check that what like whether your code is working on that like whether you can understand what is going on you have to take the summation of all the right nodes which are greater than that because that's it's a binary search tree and then do the summation of all of those nodes values then add those like though that node value to the current node value in which we are and then transfer that sum to the left side so that we can do the same thing again okay so that's the whole logic for this problem if you still haven't noticed you can mention on coin box as an excel until then keep quoting and bye
Binary Search Tree to Greater Sum Tree
number-of-squareful-arrays
Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST. As a reminder, a _binary search tree_ is a tree that satisfies these constraints: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains only nodes with keys **greater than** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8\] **Output:** \[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8\] **Example 2:** **Input:** root = \[0,null,1\] **Output:** \[1,null,1\] **Constraints:** * The number of nodes in the tree is in the range `[1, 100]`. * `0 <= Node.val <= 100` * All the values in the tree are **unique**. **Note:** This question is the same as 538: [https://leetcode.com/problems/convert-bst-to-greater-tree/](https://leetcode.com/problems/convert-bst-to-greater-tree/)
null
Array,Math,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Hard
47
131
hey everybody this is larry this is day 14 of the leeco daily challenge hit the like button subscribe button join me on discord let me know what you think about today's problem palindrome partitioning so i do self and look at these problems live so if it goes a little bit slow just watch it on 2x or something like that and you know my dog usually i try to go through my thought process and not just give you the solution because well frankly you can do a lot of places on the internets to just to get the solution so okay that's it given in string s partition s such that every substring is a palindrome okay um okay well the first thing i would notice is that n is less than 16. um to be honest i don't know if there's a better algorithm in general but given that s is equal to 16 we can definitely do something recursively um and exhaustively and why do i say that this do thing that um because then the worst case is that okay let's say you have a string of 16 characters i have to count this all right let me just use numbers though i know that this is a an alphabet you know yeah alphabet um input but the reason why i know that um giving n i know it immediately that i'm gonna do exhaustively in some way is because that how many ways are there to partition it well the math is a pretty um trying to find a mathematical word for it but i can't but basically we can reconceptualize these as uh the for each digit or each character uh we conceptualize the space between the buckets as well uh yeah we could visualize the space in between as a bucket there you go so i'm just you know these recordings are done at 3 a.m so if i'm a little bit tired at 3 a.m so if i'm a little bit tired at 3 a.m so if i'm a little bit tired let you know that's my excuse i'm sticking to it but it's okay and i actually expanded out you know 10 11 12 13 14 15. i know that technically i had just zero one to five but yeah now you can see the spaces in between right and what this means is that in between well for each of these um with each of these spaces well you could either choose you have two decisions to make right one is okay let's put a partition there meaning that you know we could partition this as a power drum let's assume that they're all paradromic because well let's ignore the power drum part for now but yeah you could given this bucket we could choose to put in a partition or we could not choose to not put in a partition right so that means that there are two possibilities for this and then now we go to the second underscore or the second bucket again there are two possibilities for this we either draw a partition or we don't so you could if you're uh well-versed in so you could if you're uh well-versed in so you could if you're uh well-versed in math or just been doing lead code enough you'll probably recognize this pattern is that okay the two i should have done this a little bit cleaner but sorry let me draw this out real quick so yeah so this is easier for me to edit but yeah so uh you know you played with commentary problems then you'll realize that there's two ways to do the first one two ways to do the second one two ways the third one two is fourth one and so forth right dot and in total with 16 characters there's going to be 15 oops how did that happen 15 buckets and with the 15 buckets each of them having a two power of two that means that they're actually two to the 15 number of uh possibilities all together so two to the 15 when you plug in the calculator it's about 32 000 that so that's gonna be um oops so that's gonna be way fast enough uh even if we do something funky um i'm gonna do some pre-optimization um i'm gonna do some pre-optimization um i'm gonna do some pre-optimization just because it makes me sleep better because i don't know uh it looks yucky otherwise uh and the precalculation i'm gonna do it for this problem is just making sure that the um you know the bits are the substrings are paddle drum right because you can do this thing where you do this recursively and every time you go recursive uh yeah you do a recursion um you know you do a thing but then you have to make sure that the last string you added is paradromic and if you do it every time the computation adds up and it actually usually adds in a lot more complexity but if we do it beforehand and then we have an old one look up then we can better bound our worst cases so that's basically what i'm going to do um and as i said because we do this and we're able to um you know the number of substring in a string in general is just n squared because there are n ways to put the start um to start you know to start a string and then there's n ways roughly speaking i know it's andrew's two-ish it's andrew's two-ish it's andrew's two-ish uh to choose the end that's after the start and so that's n square string and it takes another end to kind of check if it's a power drum you can actually do better than that but if n is equal to 16 i'm going to just leave it at the end cube algorithm so that we could focus on the what i think is the hard part for now which is the two to the end point right um which is backtracking or recursion or whatever there's different ways to do it and actually i would also say that just for future maybe up solving is that um in this case you have to do a backtracking e thing anyway because n is equal to 16. um oh sorry well n is equal to 16 so you could do it and it's fine but also because you have to output the exact things anyway if you're given the problem and they just want you to ask the number of uh ways to do it without outputting the paths then you may be ahead of me and in that case you could use dynamic programming and you use dynamic programming because you could just keep the count at each uh each cell right and also for additional up solving is or at least getting more theory into your head uh another way to think about it is about this problem to solve similar problem is that okay you know let's say there's a now i'm gonna add a bucket to the beginning and now bucket to the end and you know you can ignore what i said earlier first for now but basically you're trying to get from this bucket all the way to the end uh so you're trying to get from the left most point to the right most point where there are edges uh yeah there's an edges if it's a power drum right so let's say you know this goes a pattern then there's an edge here goes to here you know at and there's always uh edges of length one because one length strings are always parandrums right so stuff like that and if you kind of write it this way with respect to edges and stuff maybe you recognize that this is actually a dag and this also goes with the dynamic programming but also another way to format this problem is going from the beginning to the end count the number of paths going from the first note to the last node and that's actually a problem that comes up from time to time uh depending on the formulation and stuff like that and so it is something that is definitely rough um that's something that's definitely worth practicing as well um and actually if you know yeah uh so these are just up solving i'm just going over things that you can observe for this problem but in this case the less interesting part is that after you come up with the fact that this is going to be 2 to the 15 or 2 to the n uh and maybe n cubed plus 2 to the n um once you come up with that the implementation is not as uh interesting for me um but okay but now we're going to start doing it and because i caught it uninteresting i'm probably gonna get like five wrong answers because that's how karma works apparently uh especially when i'm on stream but yeah definitely try to up solve it and figure it out so i'm gonna write the cache for now uh so yeah how do i want to write the cache part um okay so yeah let's just for start in range sub n let's say n is equal to length of s uh for n in ranger from start i guess i could include star because you got one length once um and then it's just a symbol if parallel drum or is paladin uh s of s to n i think i always get confused then we draw an edge from start to n plus one okay so how do i wanna do that well let's just go um cache of start of n is equal to true um or n plus one because n could be the same character so it's meant to be exclusive but i gotta make sure that this is right i always forget how sub strings work in uh or sub slices or slices working by fine with respect to that so we'll double check that but um yeah so now we need two things which is pound room uh string or words say and i'm just going to write it lazily right uh as you go to reverse subwood uh except for we have to join it back to a string and we also have to write the cache which is uh force times n plus one for range of n plus one okay right okay so basically here we have an n cube algorithm to uh precache the power drum right so yeah so this is basically off my head there are definitely optimizations you can do you can actually reduce this to n square and if you have you know fun time i would recommend that um so now we're able to do uh what we said which is a recursive port and what i want to call it let's just say construct uh naming is hard definitely work on your wording help uh work on your naming um but yeah that let's keep track of the current array or like the progress array and character index that's happened let's put the index in front um and it goes to the end okay so now we have an answer that i just put outside for um yeah just for being easy but in theory if you want to do it cleaner you just return stuff and then construct them together but technically i think this is actually safer it's okay so if index is equal to n i think um yeah okay i just want to think right this needs to be n or n plus uh n minus 1. if this is the case then let's append the current array to um to answer and then we return one thing to note and sometimes i don't go over it because i forget is that current array is going to be a reference um because it's an array or i know it's the value to the pointer to the array or the memory address of the wave you want to be specific this is python specific though for some languages similar so what we so if you just append it without what i did here you're going to um append the pointer and then and all your answers are going to look the same um i'm gonna leave this like this actually uh just to show you later but note that this is why i had this here um so that what this does is that it gets this it makes a copy of the entire way uh so yeah so that's basically why i do that if you look at the syntax i'm gonna remove this and then i'm gonna forget it by the time i get to it so that just so you uh could see why that or see what happens when you do it but anyway um okay so if it is not end then okay um do we look at the current array hmm yeah okay so basically now we do another loop um do we want to do another loop there are two ways to do it i guess um okay i'll do it the other way um i think it just becomes an implementation detail i think it's the same right away current construction say um and then now we have to add change of thing where if current is equal to empty because if current is not empty that means that something messed up somewhere oh and that's messed up somewhere it's just that we forgot to put the partition at the last one with uh with which we should so i could have also used the last element of the current array but yeah i feel like this is maybe cleaner maybe i don't know but yeah so now for you to index um we choose to either the two things we can do right uh we can either current add um i mean i know what i want to represent but i think i'm just have to make sure that i'm getting it correct uh so something like this so that just adds it to the thing hmm is this the way that i want to code it just think about implementation advice uh current away um okay i know what i want to do sorry so yeah so now new current is equal to current plus s of index so this is now the new current array and then now we choose to either end this here meaning you know now we have a new empty string because we ended the string and then kernel way would just oops add a new element of new current because we append it or we just keep on going with the current progression and not put a string so when this is new current and then still current i hope this is ex uh makes sense but basically this one is we do um we do a recursion we start you know we cut it off that means that so we put the new current into the current array as a new element uh in this case well we just keep on going so yeah uh and i think this should be okay i mean we have to actually call this in the beginning which is construct uh zero mtra i mean empty string and empty array and then let's give it a go uh yeah so again oh well i missed something silly which is that we have to make sure this is um this is a powder drum so actually uh it is wrong in number of ways huh this is surprising well i know why this is uh reacting not what i said with the copyright even though i think you should do it in general it's because here i reconstruct a new array every time instead of append so it depends on how you want to do it uh officially and the way that i did is that apparently every time i add a new element i create a new array which is actually way less efficient but then i also don't oops how did that happen but then i don't have to remove the array after this to do uh do the recursion so but in any case yeah uh as you can see here though uh this basically is what i want to do um it is not the right answer because we don't filter out the power drum stuff which we can do it quickly but i want to check real quick how it looks on 16 things and this is going to be the worst cases we do a powder uh if we just split it at every time right so yeah definitely going to try some time here maybe this ends up being taking too long because uh oh no it takes about it was only 350 milliseconds so that was that's way fast enough i guess it's just taking a long time because it's trying to print out the output um so okay so i then i'm not going to like i said you know and this is obviously not the right answer because i print out way more because i don't filter off non-parallel drums i don't filter off non-parallel drums i don't filter off non-parallel drums but you know um i also want to see the performance of the worst case just in case though i mean you know we did the analysis so we're happy here um okay so i guess the other way to think about it instead of having a current uh string which is uh well it doesn't help us with the lookup we should just go with the start and index which is the same thing really oops so let's start here at the zero as well maybe negative one this is an awkward start index but uh but yeah so then now we can check if cash of stored index and current index if this is um a paragraph then we can use it right i'm also worried about all five ones to be honest uh let me think about this for a second because this comes up a bit uh if this is good then we can construct a new uh we could add it to a new element so then now we start at index plus one in that case and just kern away plus uh the new string which is now just what's that word of uh word of start index to index i always forget if the second one is a character or not but uh okay and otherwise no matter what um yeah so this is only when we take it out um am i missing a case i feel like something's a little bit weird oh no this is an ongoing thing um otherwise well not even otherwise would give me a second man i think i lost my train of dog for a second uh just you know this is what happens when you solve these things live sometimes um okay so i mean this part is right but now what we want is just in general where we want to start a new word here right because if we're able to get to here that means that this is a new word so can i mess up i think i'm getting a little bit confused with my indexes uh that's my confusion here oh yeah i think i just missed the case in my original thing that's what no it looks okay that's a little bit weird then um let's try this um so i think this should work except for that now the kernel really doesn't make sense oh i know why i'm just trying to translate for my old thing but yeah but now here i have to do index of index so basically like one character um hopefully that's right oops word is not defined was it called s uh current is not defined where do i use current oh uh oh yeah we don't use it anymore um do this still needs to be done anymore no i guess not right i feel like i'm having off by one somewhere to be honest so uh so we'll see let's give it a go well that's a little bit sad i mean like this should at least always give us something but yeah why isn't it he's giving us a one character answer did i not do this right what is it well let's put oh maybe i just hm like i said maybe i got the string part confused uh what does is this from string from one to two or something or how does that work uh okay let's just print i might be way confused about how the slices work that was my laziness uh okay hmm i don't this actually doesn't help me in describing this but uh let's see start end but i definitely have spaces that i wouldn't like um some reason i thought that if they're the same they would have at least one character so uh okay so basically it's n is not inclusive okay so that's the part that i wasn't sure that i'm quite wrong on uh for some reason i thought it'll be inclusive but it is not okay fine okay still wrong huh my original recursion is good but i didn't check the thing to use the cache let's put out the cache real quick um a little bit silly right now just to make sure that it works okay so it definitely works for some stuff uh this is to sum to the zero so zero to one works so that's just one length right okay yeah uh so basically we just that's what we want to do so why maybe just start index is a little bit weird let's take it out for a second ah an interesting problem i knew this was going to happen right uh okay so this looks better from here oh that's why it just needs to be index plus one okay off by once because i wasn't careful with how i used it but uh and i misspelled construct that's okay that's an easier to fix problem um at least that means it's printing something that's why judging is so slow i should have taken this case out okay so this is better but still not great uh okay but the reason why is because um because start index and index could be the same and we do loop twice so uh so yeah okay so we could just add um an if statement i mean it's that doesn't matter but if so is now you got index and this um but this is only because we double counted in both cases so yeah ooh wow still in huh did we that is a man hmm that is weird is it now because uh let's do this no that doesn't make sense right uh well we definitely need to do that in any case but well the start index is real i mean i definitely messed up somewhere because we always do index plus one um so i've i need to start index to be index in one of them yeah because we want to start the index here um okay i think i was just translating the code wrong and then here i guess we don't need it anymore because that doesn't make sense anymore in context because those are not they shouldn't be overlapped i think i was just a little bit confused clearly uh and now this short video is way too long okay oh yeah then now we have to go back here and we have to add if start index is not and then we could do it uh otherwise you have these dangling things oh it is this is go to end whoops it's late in the day uh okay so that looks good um let's try some other cases that isn't like that doesn't blow up my timing uh and do i have two empty strings now okay fine and we already have one this is good this looks good let's give it a submit a little tired and this shouldn't be even that hard i talked a lot for this problem but oh no huh maybe i've been off by one somewhere then because of this thing i mean hmm also ironically i have if i did it without the precalculation i would have gotten right already with the way that we did it the first time but i think i'm just messing up some state somewhere with our off by one somewhere which is unfortunate but wasn't even that how did this happen oh no oh i misread the output i this is actually just doing more right like uh or like i for some reason i don't expect the answer has this but we were missing it but now that i see that we actually had an extra thing i'm confused how do we start from there hmm driving off by one somewhere how does this even get constructed there's no there should not be a way for start index to get to from zero right that is weird like hmm how did i have a typo somewhere clearly or off by one maybe but hmm that's sad i'm sad this is what happens when you observe stuff live uh okay so this is concluding a string how do we get here without a c all right let's just print this out progressively uh i mean okay so this is either last but how did this kernel way became this that is odd isn't it ah let's do this before all the recursion hmm how do we get from one zero one's okay how do we get to one two oh wait what how do we get to one two oh this is uh this is just silly um it should be the start index because we've not what this is doing is that we're adding it to the current start index oh that me okay there we go oh i should have tested the other cases first let me get out of wrong ends am i okay fine okay so a lot of silly mistake on that one um and that's i would also say that's half because i try to rush through it uh you saw a couple of our five ones i think if i was if i respected this far more because maybe it's because i said it was uninteresting in the beginning if i respected this problem more i would pay more attention while i'm doing it and going forward just to make sure that i have all the off by one's okay i actually don't even know how this video is 30 minutes but uh but yeah what's the complexity again we already did the complexity what's the space well it's gonna be 2 to the n because uh times n because that's the number that's the size of the output right meaning um meaning that no matter what you have to print that out um it's going to be n times two to the n at the worst case uh plus n squared or n cubed or no this is n squared for space so uh so yeah let me know for y for this form uh this is a long video let me know what you think and i will see you tomorrow bye
Palindrome Partitioning
palindrome-partitioning
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`. **Example 1:** **Input:** s = "aab" **Output:** \[\["a","a","b"\],\["aa","b"\]\] **Example 2:** **Input:** s = "a" **Output:** \[\["a"\]\] **Constraints:** * `1 <= s.length <= 16` * `s` contains only lowercase English letters.
null
String,Dynamic Programming,Backtracking
Medium
132,1871
101
hi guys welcome to the channel this is vaga going to do another leech code question and the question in question is number 101 symmetric tree so you're given a tree and you're supposed to write um to return a boolean on whether or not it's symmetric right so this is pretty straightforward and uh the thing to note here is supposed to be an exact mirror image meaning that um the left child of a node should be the right child in the case right and the right child of a node should be the left child right so for example if you draw a line here you see um uh the in this case the left and right node are the same right so it doesn't matter but when we come down here we find that the left two's um right child node is four but the other two the right two's left child node is four so like it's exactly a mirror image right so we could come here and for symmetric and we're going to create a function um that will compare we'll do the comparisons for us right so we could call it def um we call it mirror and it's going to take in um self and it's going to take uh two trees right we could call it tree one and we could call it uh tree two of course right d2 so those two and um what it's going to do is if we check if uh if either t1 or if t1 is none or t1 is none right if t1 is none and t2 is similarly none if either of this is true right we want to i don't know um return false or okay so i'm not sure okay fine yeah we return fault right we return true because um an empty array an empty tree is an exact duplicate of an empty tree right that's weird okay um that is if both of them are none you return true if one of them is none uh return false right because a tree can't be a mirror image of an empty tree can't be a mirror image of a real tree right so we could say if t1 is none and t2 is none capitalized now this is supposed to be r so if one of them right if one of them is none right we just return false like so right and then what you're going to do is you're just going to return and whether t1 dot val if the value is going to be exactly as at t2 dot val right if those two are the same and we call this function on the left side self dots mirror on um t1 dot right and we pass in t2 dot left so we call it alternating like this t1 dot right and t2 dot left and we call it the same self dot um t1 dot left and t2 the right like so right so um we basically alternate we call it on the right and the left and then the left and the right like so right and then after that what we need to do here is we need to return true right so we need to return not return true we need to return um self dot mirror and what we want to do is pass in the various routes like so basically that is a pretty straightforward question so it shouldn't be an issue and when we submit it we should also get an answer which is uh correct right so basically i think um we have done the job here and the time complexity and the space complexity the time complexity is going to be oven because we go through every single node and the space complexities we do not create uh structures so the space complexity is going to be over one we don't create any single structure thank you for watching subscribe to the channel and i'll see you in the next video
Symmetric Tree
symmetric-tree
Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center). **Example 1:** **Input:** root = \[1,2,2,3,4,4,3\] **Output:** true **Example 2:** **Input:** root = \[1,2,2,null,3,null,3\] **Output:** false **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `-100 <= Node.val <= 100` **Follow up:** Could you solve it both recursively and iteratively?
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
1,641
hey everybody this is larry this is day 10 of the may or day 11 wow of the may lego day challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom um i'm still in san francisco so that my timing of my doing and also releasing the video is a little bit awkward um yeah i just missing some people and see how it goes hopefully today's problem is okay hope everyone else is doing all right uh this is uh you know tuesday or wednesday the american where you are so yeah today's problem is 1641 count sorted rouse strings given an integer n we turn the number of strings of length n that consists of rows and are lexigraphically sorted okay um yeah i mean i think this is i mean this is going to be dynamic programming and this is just one of those um you know counting or what's it called cometoric type things um and then we can think about what it means right that means that uh and a couple ways you can think about it the way that i think about it is okay um the number of strings of link and actually i forgot to plug in my headphones so let me know about their sound quality let me know if this is better than yesterday's um the same or worse um and then i could i mean i have my headphones here i just haven't plugged it in because i wasn't sure about yesterday um let me know also about the volume is it loud enough is it not enough let me know um okay but yeah but this problem askes you length of only rounds and lexographically sorted right so basically you could break this down to five different um uh five different sub problems if you will problems where you can okay you have length of n that ends with a and it ends with e ends with i ends with o and ends with u right and then of course these questions depend on what is the length um what is the uh um you know what is what how many strings of length n minus one right so you can definitely do this recursively i for these type of problems i call it um i generally don't just because i don't know i don't think there's any good reason why it doesn't um it's just like i think for me choosing between top down and bottoms up it just depends on how both familiar and also how i've done it always in the past and you could write the top down easily you could write something like cal of um maybe not easily but with practice it'll become easier and then you just have a like length left with i just write l or maybe index is a little bit better from zero to n and then uh last character is just less last right and of course we have a e i o u but we could also replace a i o u with one or zero one two three four because and keeping it sorted and that should be good enough really um and here you can think about the proof force version before you add the memorization right and you can just do um okay so let's just for i in range from last to um five right and this will be inclusive because it'll be sorted and then it's just you know total is equal to zero total plus or equal to count of index plus one i and then the way n return total and that should be good uh maybe i'm off by one but oh no this is actually zero and zero is to actually that's not technically true actually what we want is one more layer of um and also i forgot the basic case i'm just saying sloppy here uh yeah and then now you have totally zero and then basically we're choosing the first character and then sum it up like the first character being uh the number i which is corresponding to a thing and then for each of those we go okay we for each of those we have to start from i because has to let be lexigraphically sorted so this is the last number or last digit or last count depending on how you want to count it and then we go to the next index um with the previous index being i right so that's basically the idea and of course this is going to time out for bigger numbers but i just want to show um at least i want to see that it works for smaller numbers did i want them for test case uh huh oh i messed up here this should be zero i and not i zero because the last the foot the first digit should be i right from zero to five um and yeah and of course i get the wrong answer somehow um let's see did i just have one off by one i think i just have an off by one but uh yeah because i think for two rep 15 so i think i just have off by one but why did i have off by one um okay yeah because we should start at one assuming that the first character is already i instead of starting from zero where we don't have any character so i think we should be good here one two three four five six maybe even be fast enough but that's basically the idea i actually usually do this bottoms up just because for these things i kind of count them in parallel um but yeah and of course this is going to be too slow once we go to uh 33 right this is gonna timeout and then what you can do is oh i was wrong huh okay wow 33 is actually not that bad only 66. i didn't really do the math for that one i suppose let's see look at it for 50. you should still cash though uh and you should definitely i like doing the bottoms up just because like i said um just past experience and i think this is a little oh wow huh i didn't realize that not that many things and it's i mean it's still too slow and we should cash but it's actually not that bad um i to be honest i probably have done this problem before and i probably did it bottoms up so if you want to check out bottoms up well let's take a look first but maybe this time will be a good top-down way of doing it so then now of top-down way of doing it so then now of top-down way of doing it so then now of course we want to cache this keeping in mind that this takes two seconds so let's make it faster well the way to make it faster is by memorization and the memorization takes in to account that for every possible input up here um for one given input you always have the same output and therefore we should cache it right that's basically the whole idea index can go from zero to n technically one to n because we did it this way but well either way it's fine and then last could go from zero to five right um so this is going to be linear time as we saw or linear number of so yeah the total time is equal to um time per test case of time per input and then the number of inputs times time per input and of course the inputs cancel out so you just have time right the number of inputs is equal to five times n and each input will take at most four or five branching factors so that's o of one time so in total th this will be o of n times or tangent of five times n times which is all bad of course we have to actually do the caching but that's logic that lets me go to the next step uh yeah and now let us write cache as you go to uh actually the way that i write is i that's just for teaching purposes um i have you know fours times uh okay five small n plus one and then cash is equal to i don't know none times uh and then now then we can reduce this a little bit by saying okay if has cash of index and last then return cash of index and last and then of course we can now just cache this by saying okay we have the answer let's cache it goes to true and then cache of index of last is equal to total and that should be good enough let's give it keep in mind that took two seconds let's see if that went faster it should be yeah during the second it's gonna be fast enough one additional track let me give it a submit first one additional trick oh let's see i've done it twice alright one additional trick i would say is keeping in mind that 771 day streak nice keeping in mind that this possible inputs the only 50 possible inputs right so if you were going a little bit too slow let's say we didn't have this caching thing like we talked about um you can actually pre-calculate the answer for all 50 pre-calculate the answer for all 50 pre-calculate the answer for all 50 answers and then just have it in an array and then return it yeah and then that'll be fast enough um because and you could do this locally on your computer or something because even in the worst case let's say it took two seconds to do n is equal to 50 and then you times that by 50 right this is a very pessimistic estimate but it takes a hundred second which means it takes about a minute and a half but after that minute and a half or so uh com pre-computation we have the answer com pre-computation we have the answer com pre-computation we have the answer that is bracing fast even faster than this so yeah so that's definitely a technique that you can use um yeah let's kind of take a look to see what pasta we did uh some having crazy allergies in that stuff even worse to be honest yeah this is how i usually do it um so i'm not surprised to see this definitely check out that video and yeah for bottoms up situation how they did the first time oh wow actually i didn't know this but that makes sense actually this is uh um actually this is kind of funny i actually i don't remember this formula um and you may have to check the video but the reason why um this is n choose four um is because i said i'm choose four maybe i'm messing this up but i actually remembered what how i came up with this formula at the time this is a year and six months ago i remember seeing this one in the contest um and because i actually just solved a problem on another contest that's kind of related and i think i just recognized um i just recognized the pattern because i think i might have brute force to some small ends and i recognize the pattern and then i just put it there but this is not sensible i don't remember how to do it anymore because i think at the time of this contest i didn't like it came up like i did that week or two weeks ago or something like that so something very recently so i was able to do this but um but i don't think that's uh i don't think that's normal i'm just curious how i did in that contest uh given that i quote cheated on this oh that's sad huh it took a while here actually which farm is this cave smallest path oh i should have gotten this one much quicker i don't know what happened here um but yeah sometimes it is what it is i think if i did it today i probably would have gotten it pretty quickly but some you know sometimes you have bad days and you know or you could you know you practice so that your bad days are still pretty okay right like passes the bar so anyway that's all i have for today let me know what you think still in san francisco uh bay area stay good stay healthy take your mental health i'll see you later and take care bye
Count Sorted Vowel Strings
countries-you-can-safely-invest-in
Given an integer `n`, return _the number of strings of length_ `n` _that consist only of vowels (_`a`_,_ `e`_,_ `i`_,_ `o`_,_ `u`_) and are **lexicographically sorted**._ A string `s` is **lexicographically sorted** if for all valid `i`, `s[i]` is the same as or comes before `s[i+1]` in the alphabet. **Example 1:** **Input:** n = 1 **Output:** 5 **Explanation:** The 5 sorted strings that consist of vowels only are `[ "a ", "e ", "i ", "o ", "u "].` **Example 2:** **Input:** n = 2 **Output:** 15 **Explanation:** The 15 sorted strings that consist of vowels only are \[ "aa ", "ae ", "ai ", "ao ", "au ", "ee ", "ei ", "eo ", "eu ", "ii ", "io ", "iu ", "oo ", "ou ", "uu "\]. Note that "ea " is not a valid string since 'e' comes after 'a' in the alphabet. **Example 3:** **Input:** n = 33 **Output:** 66045 **Constraints:** * `1 <= n <= 50`
null
Database
Medium
615
1,866
hey what's up guys uh this is sean here so this time uh it's called number 1866 a number of ways to rearrange sticks with k sticks visible okay so this one you know um it's a classic you know uh dp problem right so basically you know you're given like uh they're like unique size of sticks uh whose lens are integers from one to n right and you want to arrange the sticks such the exactly k sticks are visible from the left okay so a stick is visible from the left if there are no longer sticks to the left outfit right so for example if the sticks are arranged in this way you know the sticks so there will be like three uh visible sticks you know similar like you know basically they're like kind of like bars right a line in the row right so this is the first one no the second one is like three right third one is two uh first one is five right and then the last one is four something like this right so if you look at from the left you can only see this one and this one because this two will be blocked by the uh by some higher ones on the left right and since the disk length is there like they're all unique from one to n right so they're like basically all unique all different uh numbers okay and then given the n and k right so return the number of such arrangements uh basically you need to return all the possible arrangements such that you know given n sticks they're like k a visible sticks looking from the left okay so some examples right so this is the very basic one so we have three disks from a one two three and we need to see two sticks from left and in this case we have three arrangements right that's why we have three and under the example two actually this one gives you like a special case right or a base case which means you know whenever so when doing the k when the n is equal to k in this case we only have there's only one possible arrangement basically we have to arrange the numbers from we have to range the numbers from smallest to the biggest right because we want that's the only way we can see all the sticks okay and here's like a very big one okay and the constraints is like what 1000 right and that's it right i mean so for this kind of uh number of ways you know problems you know most likely you're gonna need uh need the dp to solve it or plus some combinatoric uh idea on top of that but still right i think you most likely 90 94 i would say 90 of the time you will need the dp concept to solve this kind of number of ways right and so how can we solve this one the easiest way is just to give try some examples right now let's say we have like n is equal to six and one and then k is equal to four how about this one right you know basically you know they're like we just need to find like find a way to break down this problem into sub problems you know so how can we break it down right i mean basically you know we just have to we usually have we can try two ways first you know we try to place the first stick right the first one or we can try to place the last one right you know because you know usually you already will try to place the for the first one but you know but for this problem you know if we try to place the first one it will not give us uh the correct answer because you know so what's if we place the first one right uh the pl the first uh stick here you know depending on uh what's the stick after that right we'll have like different answer right because let's say if the n is equal to let's say we place three at the very beginning right conve guaranteeing that these three uh will okay so i think the only guarantee the only thing we can guarantee is that you know these three will be seen right and if you're trying to use this one like and to break it down into a sub problems you know let's say we put three here right and then we'll be like okay so we can see this one here now we have n minus one numbers and then we have a k minus one case here right so which means that you know if we can have like a dp here you know in the end like so after three here you know okay so we have like already seen one numbers and then we seem to figure out like then uh we have n minus one number left and then we just we need to figure out okay uh if we can see k minus one num uh sticks right but you know if you guys remember so the way with dp work is that you know the previous state you know the previous stage should not affect the next state right so if we try to place the stick at here you know based on the number based on the stick we put here it could affect this one you know basically you know let's say if we have three here you know if we have two okay so let's say if we're trying to put one and two here right okay so we're assuming that okay so if by looking at this dp sub problems starting from here you know okay we're assuming that okay this one two should be uh it should be visible but since we have three at the left you know this two will not be seen that's why we shouldn't that's why this way this dp breakdown will not work right instead since we're looking from the left side you know if we can fix the right most one and then we can sure if this one can be seen or not right because we're looking at the left and how can we do it right let's say again right we have this one is going to be this round right so we have six and four so let's try to put the stick on the last one actually there's a there are only like two scenarios here we just need to uh distinguish if we put the biggest number on the last one or not and the reason being is that you know so if so the case one is that you know it's the largest number largest second one is the not it's the non-largest number because you know if we put the largest number in the end in this case which is six right if we put six here no matter what number what sticks we have before this the six will always be visible right so in this case we can guarantee that you know so if we put the largest number here you know the so the nut the problems can be break down into a sub problems which is going to be a dp of what of like n minus 1 uh k minus 1 right okay so this dp means does dp and k it means that you know given like n numbers and we need to see k sorry given n sticks we need to see k uh s sticks from left and this n number it doesn't have to be one two three four right it could even it could be a one two uh three and five uh assuming this n is equal to four i mean what i'm saying that it's a number does not have to be consecutive because you know they're always different right so it doesn't really matter if they're consecutive or not because we can always arrange them inside in a way that's you know can satisfy this dp state here right so if we put six here right so now we have so the sub problem becomes some becomes to okay uh given like five different sticks we need to see four i'm sorry we need to see a c3 right because we have already guaranteed that the last one can be seen so that's the that's this is the first uh scenario here and the second scenario is this one if we don't put the la the largest one here then what does it mean let's see we put four here so if we don't put a 4 here sorry if we don't put the largest one here and we have a smaller number here what does it mean it means that this stick will definitely not be visible because 6 will be somewhere here 6 will be somewhere on the left of 4 so which means that this four will definitely be invisible okay right then what's the sub problem for the for this case it's going to be a dp of what so we have a n minus one and then still we have k visible stick we need to figure out right and like i said you know it doesn't really matter which one we fixed or we put here isola is not the largest one the sub problems are all the same right because you know if you have four here not if you have four here you know we have like we have one two three five six left right if we put three here we have one two four five six right they're all the same even though the like the numbers are different but still we have like five numbers we need to figure out a way that we need we want to have like uh k we still want to have like a k visible sticks and how many scenario we have for this one it's going to be n minus 1 right besides the largest one we have five different sticks we can try to put it here and all of them will end up with the same sub problem which is n minus 1k and yeah that's it right so that's the basic the state transition function for this dp and on top of that we just need to figure out like a few like edge cases i think the first one is we already seen that right where n is equal to k right when n is equal to k you know we just need to return one because there's only one arrangement for that right and second one is what second one is the uh i guess is that the k when k is equal to zero because you know because n is always greater than k right and we have a case uh we have a case is that we always try to put the largest one in the end right but if we keep doing this way you know so there will be a case that a case will be become to zero where but while the n is not zero right so which means that's this is going to be an invalid case indeed right because we still have some n there but we already have like k-sticks k-sticks k-sticks available for sure which means that you know we they will get like more available uh sticks than what we then would what we need to show so if the k is equal to zero and then we need to return zero because this mean represents it means that is not a valid scenario yep so we start with that being said you know we can start coding and as long as you can figure out those kind of two scenarios and the coding should be pretty easy you know so we have n in the k right and then oh by the way so this one can be solved it's both top down and bottom up dp uh i just figured out this i just thought this top line is a little easier to understand okay so case one right put largest right stick to the end so if we do that you know going to be a we have answer starting from zero right so it's going to be a dp of n minus 1 k minus 1 right so that's the k the case one and then case two put none largest stick to the end right so in this case we have n minus one possible ways and each of them will have the same sub problem which is dp n minus 1 and k because this stick will definitely be invisible from left right and then we return the answer that's it right so that's the basic the two cases here and for the edge case right so if the n is equal to k we return one right that's the and then if the k is equal to zero then we know okay so but we still have some n left right then it means that we'll definitely have uh have more visible sticks than k and then that's the invalid scenario and the last thing is that you know we need to uh do the modular right i mean y7 right let's do dp of nk do a modular can i do this or what i have to do is do the modulator from here i guess either way should either waste is fine okay let me try to run this one okay this one works if i submit time limited hmm let me see i think it might be because i need to do a modular inside of this dp instead of outside you know let's try again yeah so this time passed right i mean i'm not quite sure you know um for this part maybe the uh um maybe the conversion in python has had some like side effects of the runtime here and yeah so anyway right so that's it right i mean it's pretty straightforward right time complexity obviously of n times k right because well because we have n times k state here and yep so i think that's it right i mean it's a dp problem you know only two state here you know the only uh tricky part here is that you know instead of trying to put stick from left to right you know we should try to put a stick from right to left so that we can basically break down the problems into a sub problem and yep i'll just stop here and thank you for watching this video guys and stay tuned see you guys soon bye
Number of Ways to Rearrange Sticks With K Sticks Visible
restore-the-array-from-adjacent-pairs
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,2,5,4]`, then the sticks with lengths `1`, `3`, and `5` are visible from the left. Given `n` and `k`, return _the **number** of such arrangements_. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, k = 2 **Output:** 3 **Explanation:** \[1,3,2\], \[2,3,1\], and \[2,1,3\] are the only arrangements such that exactly 2 sticks are visible. The visible sticks are underlined. **Example 2:** **Input:** n = 5, k = 5 **Output:** 1 **Explanation:** \[1,2,3,4,5\] is the only arrangement such that all 5 sticks are visible. The visible sticks are underlined. **Example 3:** **Input:** n = 20, k = 11 **Output:** 647427950 **Explanation:** There are 647427950 (mod 109 \+ 7) ways to rearrange the sticks such that exactly 11 sticks are visible. **Constraints:** * `1 <= n <= 1000` * `1 <= k <= n`
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
Array,Hash Table
Medium
null
1,971
Welcome back again you will get the calling. What we need to know is that we have given you a source and a test nation and let's say we have some path like this and it is connected like this right let's see. From this point you will be asked whether you are in this Point, this is our source, can you reach here by walking from here or not? If we look at it, then yes, I am a lot, I will go from here, I can reach here from this point, what end? Whatever destination you have, can you reach, if you can, then you have to return blue, respect wise, understand you and after that how to solve your problem, okay, you can reach this point, let me see, there is a director to go from here to here and You can reach there by going right. I will ask whether the van goes through you or whether you go through you. If the way goes then the van will see. Brother, I can come only through you. If I can't go ahead then this is the fault. It will return, it will make it positive, both are positive, no, I can't reach five on my own, this is our right, if we can't reach 5, then how will I approach it and if I had combined these two with lets, then let's both of them If I have added it, then if now he asks, brother, can I reach van five, then where can I go till this round, I say, I can go on the van, I can go on you, then I say, van, see what? You can reach the punch and then he would have said that brother will come back after finding out from three whether this is possible or not and then he will see that he will call further and can reach at 35 from here you also return something like this Han I can reach here there is a way to reach 5 right okay we will get more information about the output so how will we build inside right we are getting something like this we are getting a tutorial what will be in it the first one will be an area 0 If connected to 1, then I make zero. So what is the information from here, zero is connected to van, this is zero, this van is connected to zero, this is connected to you, van is connected to you, if you are connected to these, then you are connected to zero. We can make it something like this, in front of zero I can write that zero is connected to van, then zero is connected to tu, zero, I will make something like this that there will be a map, it will have vertices in front of the map, wait and I will make it. I will wait for it, I will take vertices, zero van, three and one in front of them, this register is late, here our interior is connected in front of the store, it is connected to zero and with whom can I get connected, so let's check this. What will I do at the time, I will go here first, go here directly from zero Ca n't reach, then go to 2nd, let's see, then can only go to zero, then come back from you, not even from first Can reach means over and we will never be able to reach from 0 to 5. We will make a map, wait for the artist and after that what will we say that Han will call his ten whether all the elements are lying inside the earrings, then direct is the way. If it won't go, but which of them is going, isn't it going? Right, so first of all, let's do the same, you wait, earn list is the interior versus list and what I do, the interior will come out from there, I have made the list today 5 seconds of this. Inside we will give it a team four, so what will we do, map dot get exploit, which is add, this is ahead, we have the first zero element of this area, right, there is a zero index in front of the zero one, that is zero, we will understand 4. Removed the name in front of 4 and will add it to 5 meaning this team has taken zero, how is it connected, then zero is connected, how the word must have gone, let me show like first of all, I must have got this, I must have got zero and van, so we have He said, ' and van, so we have He said, ' and van, so we have He said, ' Get this van from me, whatever release is there in front of the index, the van will be added to it. Lately, then I said, ' Lately, then I said, ' Lately, then I said, ' Get the van one, get this van, add zero in the list in front of it.' When Get the van one, get this van, add zero in the list in front of it.' When this matter comes, you will say that it will be completed in front of you. It has been completed. If I want to make a call then let's start it. Say done. This is our start and this is our start. What will we pass till the destination? This is a map which is made by us. One more thing has happened, we will reduce it, if we mark it, then for now we will create an area named Visit It. Okay, whatever you visit once, do not visit again and after that, if you have to go from the beginning. We have to return something like this, from late we will create a variable named flag, we will return it and when this call is made, what will we do, whenever we get the answer, we will create a mix, we will do that for now. It will remain false like we will get it whenever GF calls, whenever it is updated after DFS Colony, it must have been found in it, if not, then we will attend only positive, now the matter is over, return information for us, hello, we got it, we Have visited because we have put a call on it, we will do it If I start map dot get, what will it give, it is not equal to the same, if it is so, what will we do, we have made a global flag, will give it to it, eg. And what will we do if we come to this point but it is not there while making a call then we will check it if our number is not already digital then only we should make a call and here I will tell you where to go right this is done one more There may be a situation that your flag has already become true since late, it has become true while making the call and either you are putting it as already visited so we have to return, we will write or you have already put it in our flag. What are we doing, the gym, we have already found it, ours has been found or already, if you are going to search for it again, then it will handle it and one or two more will not be found, because we have found it here. The butt is handled with a handle, if it gets hit, this right here will stop it. What did we do? First of all, I made a map. I filled you up. It became full with all the points. I filled it up here in front of you. I once made a visitor. Do n't do it again. Grab each element of the list. Let's start getting the map. You are starting from zero, the van is in front of zero and you must have read it, so you are the first one to grab the van. Grab the van. Have you checked our destination? So it is not the destination, if it is almost true, then break two breaks for this, then what will we do, will we make a call, we made the call and after making it, we made a route for it, now I am seeing whether the route from the van goes to Punch or Otherwise I started the van. Ok, this was bullion, here say it will not happen, you have to return it, converted it at the start.
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
1,022
this is a binary tree problem and it's binary in even the values so it's not just binary tree its values are also binary that is node values are 0 and 1. so here in this problem what we have to do all the nodes will have either 0 or 1 so you have to start from root node and then traverse the tree so when you traverse the tree sometime you reach the leaf node so whenever you reach leaf node so in this case we have three leaf nodes so this represents each leaf node represents a number and what number so start from root it's one then we go here zero so the path you have to take the path from root to each of the leaves so path to this leaf is one zero 0 so this represents number 1 0 so 1 0 means 4 1 is 1 0 is 2 1 0 is 4 so this represents 4 similarly this leaf represents 1 0 1 so 1 0 1 means 5 and this leaf represents 1 0 so this is 2 so you have to return the sum of all those values represented by leaves uh as uh with other tree problems mandatory problems here we will use recursion so if you are uh just starting with recursion and you have done a few problems related to tree traversal then this would be a very good exercise for you and it's a good candidate for interviews and it should clarify your doubts so before jumping into tougher problems if you can solve this then you are on the right track for uh understanding the recursion with trees so let's see how we can solve it so uh clearly we have to start from here and in the question it's even mentioned that number of nodes is from one to thousand so number of nodes is at least one that means root will always be valid so how we can solve this so uh we have one here so let's write down all the values here so this represents one zero one this represents one so you notice that what is the common ancestor of these two leaves it's this one and what this node represents one zero so you have to start from root so root represents one if this was zero root would have represented zero so there is no parent of this so it's a single digit the number of parents you have the number of digits you will have number of bits you will have in the binary representation so root has just one bit either zero or one depending on the value so root represents one and this one will now be the most significant bit so if you see the ordering here this we are starting from most significant bit and the leaps value is the least significant bit so now this one will be the most significant bit for all the three leaves so this is fixed so you have to try to find how to solve it so let's forget this part let's first think of the base case as with other recursion problems so the base case would be that if you have to call it on uh an empty or null root null tree then you will return zero if null then zero second base case would be that if you are calling on leaf and we will be keeping track of one sum running some while passing from root to that leaf so if leaf then return the sum itself otherwise we will do some recursion so how should we solve it so now with this we get an idea that if one is the root then one is the most significant bit for everything so we pass one to both of them so we pass one here and we pass one here to both of its child both of its children now this child will see that i am getting a value of 1 and now my value is 0 so how can i append 0 here so we can left shift it by one so this will become one zero and now add the current value so this value will be the zero one so adding zero does not change it will be one zero so now this has become one zero similarly if you look at this leaf this node again we have passed one here so it will try to append its value to the parent's value so in order to append that in the least significant position it has to shift left so one was there it left shifted by one so it becomes 1 0 now it will append it so it will just add 1 to it and it will become 1 so now this is representing 1 again this will check whether i am a leaf node or not if i am a leaf node return this value if not pass this 1 0 to both its children or if there is one just one child pass it to its child so it will pass 1 0 here now let's look at this node so we are talking about this node so what this will do it will just it its task is to append its value to the value passed by parent has passed one zero so it will left shift one zero by one and it will become 1 0 and it will append this 0 so add 0 here so it will be 1 0 so now this is the value that it's holding it has produced next it will check whether i am a leaf or not so after check it will return this because it's a leaf and what is the check very simple check if both left and right child are null so it will return 1 0 and what is 1 0 it's 4 so it returns 4 to its parent so let's row in red it returns 4. now come to this leaf node here also it will pass 1 0 the same value is passed to both its children will again try to append it so directly write it will left shift and add one to it so it will become one zero one then it will check whether it's a leaf node or not it's a leaf node so it will return this value one zero one which is nothing but five so this returns five and what this will do it will return the same function recursively with its left and the sum so here some will denote this running sum 1 0 in this case plus f write 1 0 so we will have a variable here in the code sum but here let's say we are working for this we are working in this part of the tree similarly you can do the right part so it came here and again it was it returned 1 0 that is 4 and this one returned 5. so it will return 9 back to its parent so here it returns 9 similarly this would have also done the same thing f of left and right have passed a value of 1 and again right and one so this left has returned nine similarly if you proceed in the same fashion it will append one to the past value that is one so it will create one it's not leave so it will pass the same value to its child so it passes one here it gets one and appends one to it by left shifting and then adding now it's a leaf so it will return back so it's seven so it returns seven here and its left would have returned 0 with this case its left was null so we would have called f left 1 so it would have returned 0 for null we return 0 so left return 0 right return 7 so total is 7 so it returns 7 now the root will again add both of these values returned and it will be so we had written 9 here 9 plus 7 16. now let's verify we have 1 0 which is 4 1 0 1 which is 5 1 which is 7 which is 16 so this works so let's write the formal code for this how we can do this so we have the main function where we have root and nothing else let's define another function which takes root and a sum which is passed to by the parent so it will simply return f root 0 and now this is the main function so here the base case was if not root or root is null return 0 otherwise sum equal to some left shift by 1 plus its value root not well and it will check if leaf so instead of leaf you will write if root dot left is null and root dot right is null so if leaf return sum else return f root dot left sum plus f root dot right sum so same sum is passed to both of these and we are done so you see here we are using recursion this f is recursively calling it and it has these base cases this is the base case and this leaf is another base case so let's write the code for this in c plus java and python so if leaf return the sum otherwise so if one of the child is null it will automatically return 0 so its value will not be added now we are done so let's run it so there is some error here let's see what it is uh so maybe this is the error so oh yes this was the error it was thinking of left shifting sum by one plus root val and it was zero so zero shifted by one again remains zero so it might be creating a problem for this example and uh so to make it clear we have to first do the shift and then add the value so that operator precedence does not come here and the solution is accepted and we are around here but if you try a few times you can land in on this tower also so what is the time complexity uh here we are doing nothing special we are just traversing this tree and we are not wasting any node multiple times so we go to root node calls the same function recursively for its left and right children and below so we are going only in downward direction that is we are not wasting any note twice so it's often so time complexities of n just like any other traversal and space is the only space used by the recursion stack so if you include it space can be of the order of height but if you ignore this implicit space then it's of one that will all depend on how you measure the space now let's repeat the same logic in java and python so it's a very simple code that's the power of recursion here and the java solution is also accepted and here it takes 0 second 0 millisecond that is 100 and finally we will write it in python 3. and the python solution is also accepted
Sum of Root To Leaf Binary Numbers
unique-paths-iii
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit. * For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_. The test cases are generated so that the answer fits in a **32-bits** integer. **Example 1:** **Input:** root = \[1,0,1,0,1,0,1\] **Output:** 22 **Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 **Example 2:** **Input:** root = \[0\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `Node.val` is `0` or `1`.
null
Array,Backtracking,Bit Manipulation,Matrix
Hard
37,63,212
1,361
Well, it has just been course number 177 of the it code and they put this problem up, it was quite ugly. It can only solve the problems. This problem is more or less what it is about is that they are going to give us a graph with a tree and we have to see yes and all The nodes of that graph of that tree give us they do n't know that it is only a binary tree, that is, they are going to give us a value n that means the number of nodes there are and they are going to give us a rule where the index of each chain Mind you, this arrangement means or each node is represented, for example, the left child of node 2 is going to be zero, 12 is going to be 3 and the right one is going to be none because this is worth minus 1, so what it comes down to is, well, let's see if this is A luminary in the example of a poem is because ordinary prevention is one who only has up to two children, this is traditional, the ordinary system, all the new ones only have 0 to 2 children, this is not because they share the same child, this is not It is because these are mutually father and son and it is not because even though they are two binary trees that are asking you for only one to exist, only one is activated so well the problem is actually very simple I don't think it should be half in the same open contest the problem of comparing dates and thousands became more difficult for me because obviously you can't use the functions in the calendar classes or anything like that so if it hadn't been trivial then well it seems like this what I did was use a set in checkers in front so that it is a binary tree only if there is only one way to access each node then that is what we are going to validate so we are going to create a variable called x index which is going to be n 1 that is the amount 2 - 1 because we have side the amount 2 - 1 because we have side the amount 2 - 1 because we have side 0 then guayaybí ex is greater than or equal to 0 how does this happen - - - so we don't forget then if child reads ah and ex is different from -1 we are going to do ah and ex is different from -1 we are going to do ah and ex is different from -1 we are going to do this and the same for ride chavez although yes it is different -1 we are going to see if it is although yes it is different -1 we are going to see if it is although yes it is different -1 we are going to see if it is contained contains steele side if it already contains it we are going to return because if it does not contain it we are going to put it with as and the same for this other nothing because next because they are returning to false if it is already contains because it means that we already went through there so it means that it is not an ordinary one since we are done we are going to return trump only if that point 6 is equal to n 1 we are going to return if not we are going to take photos we are going to see if it works and it works for this Let's see if it works for everyone and well that's the solution to the problem.
Validate Binary Tree Nodes
tiling-a-rectangle-with-the-fewest-squares
You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree. If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child. Note that the nodes have no values and that we only use the node numbers in this problem. **Example 1:** **Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,-1,-1,-1\] **Output:** true **Example 2:** **Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,3,-1,-1\] **Output:** false **Example 3:** **Input:** n = 2, leftChild = \[1,0\], rightChild = \[-1,-1\] **Output:** false **Constraints:** * `n == leftChild.length == rightChild.length` * `1 <= n <= 104` * `-1 <= leftChild[i], rightChild[i] <= n - 1`
Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m).
Dynamic Programming,Backtracking
Hard
null
203
hello everyone welcome back and today we are looking at question 203 which is remove linked list elements so we are given the head of a linked list and an integer value we want to remove all the nodes of the linked list that has node that value equals to the value that they give us and we want to return the new head let's look at example one we have a linked list with one two six three four five six and they want us to remove the value six so simply we check all the nodes of the english and whenever we see a six we want to remove that node and we need to fix the pointers of the linked list now you might look at the input and you see that the head equals all those values and you might get confused but let me tell you that in lead code when we have linked lists and when you return a node right the lead code platform would return that node and all the nodes connected to it because we have a linked list now when they said the head is equals to all of these they are saying that the head is one and basically all the nodes connected to one we can see are two six three four five six so the head is just one and these are the nodes connected to the head and we see that the output after we remove the six is basically one two three four five so in short we need to return the new head and lead code itself will just return the that new head and all the nodes connected to it which is 2 3 4 5 basically now example 2 is saying okay the head is pointing to nothing and the value we want to remove is one well we don't have anything so you just return nothing empty armling list now example three is saying that the head is seven and all the nodes connected to seven have the value of seven and we want to remove seven so we just remove everything and we return an empty linked list so let's go to the blackboard and explain how can we do this okay here we are at the blackboard and as you can see i have drawn linked list containing one two six three six one is the head of the linked list this six is detail and thus it points to nothing on the right hand side i have wrote code that we will fill out as we go to understand the approach used to solve the problem now let's say we want to remove the value six we want room of six what should we do well we can go through all the nodes of the linked list and whenever we see the value 6 we want to remove it and thus go to the previous node fix its pointer so that it will point to the node that comes after the node that we want to remove so as i said we need to have access to the previous node but we have a singling list which goes in one direction using this singling list we cannot access the previous node what should we do well we can create a previous pointer so this previous pointer will access the previous node and you might ask well what is this on purple pointer when this will point to the current node so whenever we see value that we want to remove we will use this previous pointer to access the previous node and we can simply fix that pointer to point to the node that comes after the node that we want to remove okay but now let me ask you hey i want to remove the value one same approach we go to one does this node containing the value that we want to remove yes so let me go to the previous oh hey we don't have a previous node one is the head of the linked list this is an edge case and i hate edge cases one of the best ways to remove or to reduce the edge cases in linked list is to use dummy node so what we can do is that we can create a dummy node here that contains absolutely nothing and this dummy node will point to the actual head of the linked list so now when we say hey remove the value one we go okay let me go to the previous node we see we have a previous node which is this dummy node that contains nothing and we can take this pointer and point it to the node that comes after the node that we want to remove in this case if we want to remove one this dummy node will point to two and two will become the new head of the linked list okay so this dummy node is used to reduce the edge cases in the linked list okay so let's start and yeah we want to remove the value six so remove the value six okay good so the first thing we said is we want to create dummy node and hey we created it and we see that its next pointer is pointing to the actual head so when we write the code we need to do that so we can say the dummy the domi.next the domi.next the domi.next equals the head of our linked list so dummy.next equals the head dummy.next equals the head dummy.next equals the head so now we have this dummy node and this node is connected to the actual head of the linked list okay now we have two pointers as we said the previous pointer and the current pointer well the previous pointer should start somewhere and we have this dominate for a reason so that the previous pointer can start here so previous equals the dummy node which means that this previous pointer will have the address of this dummy node in other words this previous will point to this dummy node and now the current pointer will start at the actual head of the linked list so current equals the head of the linked list okay so now for instance if we want to remove this one we can use this previous to access the previous node and we can say hey previous that next pointer needs to point to current.nextpointer current.nextpointer current.nextpointer you see we will use the previous and the current node okay so let's start with the um approach itself we are starting at the current node we will ask ourselves a question thus this node contains the value that we want to remove in other words if current the value equals the value that we want to remove right this is the current pointer if current.value equals the value that we current.value equals the value that we current.value equals the value that we want to remove we will do something in this case does one equals to 6 no so we need to go to the else section what should we do well we know that we what we don't want to remove this one so there is no need for the previous pointer to points to the previous node we can advance the previous here and now the current will also go to two because we don't want to remove this one here is the current so what did we do well we go to the else section and we said oh yeah the previous will equals where current is pointing at remember current was pointing here so we took the previous and we advance that to where current is pointing to so else the previous will equals the current so we will take the previous pointer and points to where current is pointing to and outside this else we said we need to advance the current pointer why outside this else well because inside the if and inside the else we need to advance the current pointer so we can just write it outside of the fl block you if you don't get this now it's okay you will see this as we advance through the linked list so the current equals the current dot next again if the current is here what is current.next well current is pointing to current.next well current is pointing to current.next well current is pointing to one current.next is this yellow pointer and current.next is this yellow pointer and current.next is this yellow pointer and this yellow pointer is pointing to two so when we say current equals current.next the current will go to the current.next the current will go to the current.next the current will go to the next node again if current value equals value does 2 equals to 6 no go to the else section we said hey take the previous point it to where current is pointing so let me take this previous and pointing to where current is pointing and we said hey advance the current as well so current equals current.next take this current and current.next take this current and current.next take this current and advance it here same story does 6 equals to 6 yes now what well we said we need to have access to the previous node do we have access to the previous node and yes we do we have this previous pointer pointing to the previous node well good now what should we do well we say okay go to the previous node take the previous the next pointer which is this yellow one take this previous.next pointer and we take this previous.next pointer and we take this previous.next pointer and we need to make this node points to where current.next is pointing to well current.next is pointing to well current.next is pointing to well current is pointing to six current.next is pointing to six current.next is pointing to six current.next is pointing to three so now the previous.nextpointer previous.nextpointer previous.nextpointer will point to 3 as well so what did we do here if the node that we are at contains the value that we want to remove we need to go to the previous node and we want to say hey the previous node the next pointer needs to point to where current dot next is pointing to this is what we did we went to the previous and we took the previous dot next and we are pointing to where current.next is pointing to when we current.next is pointing to when we current.next is pointing to when we finish this if we need to get out of the if else block and we go here oh we need to advance the current as well it makes sense 6 will be removed there is no need for the current to stay at six we want to remove i mean we want to advance the current to the next node so take this and advance it to the next node so now do you see why i have the current equals current.next outside the if else block current.next outside the if else block current.next outside the if else block because in the if we need to advance the current in the else we also need to advance the current so put the current outside of the if else block because we will always advance the current so now there is nothing pointing to 6 and now six will be removed by the garbage collector so let me fix the drawing to make it more appealing to the eye now we go again hey does the current value equals the value that we want to remove is three equals to six no go to the else advance previous to where current is pointing to and now we need to advance the current so current equals current.next one last so current equals current.next one last so current equals current.next one last time does 6 equals to 6 yes so what we need to do is hey go to the previous node fix its next pointer so do we have access to the previous node yes previous nodes three so we said previous dot next which is this yellow pointer will equals to current.next will equals to current.next will equals to current.next here is current.next is pointing here is current.next is pointing here is current.next is pointing to null so previous.next will also to null so previous.next will also to null so previous.next will also points to null and now outside of the if else block we need to advance the current equals current.next equals current.next equals current.next take this put it here so again nothing is pointing to six can be removed and let me fix the drawing to make it more appealing to the eye and we have this as you can see we have successfully finished everything we removed all instances of sex from the linked list and now as you can see i did not fill in the oil condition yet but when did we stop well when the current pointer reaches no in other words while current does not equals to null we need to keep moving and once the current is null we will break from this while loop and we need to return something what should we return we said we want to return the head of the linked list but guess what we have a dummy node that always points to the head of the linked list i told you i had edge cases and this removed the edge case of the head so we have a domino that always points to the head and we can just say okay we want to return this dummy but next since dummy always points to the head just return to me dot next the domain.next will always be the next the domain.next will always be the next the domain.next will always be the head of our linked list so let's go to lead code and we will write exactly the code that you see here okay here we are at lead code and we said we want to create a domino so let's create that so list node um let's call it i don't know dummy because it makes sense equals new list node okay good and we said this dummy node will always points to the head of the ring list and we need to make that connection so we can say that hey the dummy dot next is equal to the head of the linked list makes sense and finally we said we need to have two pointers a previous pointer and a current pointer on list node previous it will start at the dummy node and the current pointer will start of the actual head of our linked list so we can say that list node on current will start at the head of the linked list good and now our logic begins we said we need a while loop and we said we need to keep looping until current hits null or in other words while the current does not equal null we need to keep looping and what should we do well we said we need to ask one question if the current the value equals the value that we want to remove we need to go to the previous node we need to have x the previous node using the previous pointer so we can go to the previous and we need to fix the next pointer of the previous node so previous dot next equals what well it will equal the node that comes after the node that we want to remove so previous.next will equals current previous.next will equals current previous.next will equals current dot next so now what if the node that we are at does not contain the value that we want to remove well we said we need to go to the else right so else what well simply we said we need to advance the previous pointer to where current is pointing to so previous equals current and we said in both cases and the f or in the else we need to advance the current pointer and we said we need to put that outside the if else block so outside we will say the current equals current dot next and when this while loop finishes or in other words when current hits null we will break and we know for sure we have removed all instances of the value that we need to remove so at the end just return the dummy dot next why is that we said the dummy will always point to the head so dummy.next will always points to the dummy.next will always points to the dummy.next will always points to the head of the linked list okay so let's run the code and let's submit okay so looking at the time and space complexity starting with the time complexity we looped through all the nodes of the linked list to make sure that we remove all the occurrences of the value that we want to remove assuming we have n nodes in telling list the time complexity is being o of n now in terms of the space complexity we only used one dominoed and the rest was complete pointer manipulation since we only used one the minor the space complexity is big o of one i hope you guys enjoyed the video make sure to like and subscribe best of luck to you and see you in the next one
Remove Linked List Elements
remove-linked-list-elements
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_. **Example 1:** **Input:** head = \[1,2,6,3,4,5,6\], val = 6 **Output:** \[1,2,3,4,5\] **Example 2:** **Input:** head = \[\], val = 1 **Output:** \[\] **Example 3:** **Input:** head = \[7,7,7,7\], val = 7 **Output:** \[\] **Constraints:** * The number of nodes in the list is in the range `[0, 104]`. * `1 <= Node.val <= 50` * `0 <= val <= 50`
null
Linked List,Recursion
Easy
27,237,2216
121
um hey what's up guys NIC ye I do tacking cutting stuff on twitching YouTube I'm doing all the leak out and a crank rum so I playlist for those I'm a channel everything else in the description this problem is called best time to buy and sell stock it's an easy problem a lot of likes will give it a like it's super easy alright so you have an array for the iPhone meant for which the iPhone mint is a price of a given stock on a day I all right so this is the each day each index of the array is a day and each value is the value of the stock on this day so if you were permitted to complete one transaction we can buy and sell one stock we divide then we have to define an algorithm to find the maximum profit we can make right so if we buy a stock on the first day and it's you know worth $7 and then we sell it on the second day $7 and then we sell it on the second day $7 and then we sell it on the second day for $1 for $1 for $1 we're losing six bucks so that's obviously terrible algorithm or terrible solution right what we want to do is we want to buy for $1 and then sell at the want to buy for $1 and then sell at the want to buy for $1 and then sell at the next maximum value right we can't sell we can't keep grabbing for $1 and then we can't keep grabbing for $1 and then we can't keep grabbing for $1 and then sell it for $7 because that was the day sell it for $7 because that was the day sell it for $7 because that was the day before we bought it and we can't go back in time obviously so what we're gonna do here is you can't you can do a double for loop so you can do a for loop and find you know you can check each element so you start at 7 and then you have another loop that checks the difference between 7 and all of the next elements that come after it and then to have a max profit variable and keep updating it like that but that's event squared solution and no one's gonna like that so what we're gonna do is we're gonna have a variable called min bail set to integer dot max value right always 7 mins to Max's and maxes 2 mins initially and then we'll have an int max profit we're assuming these are all positive so I'm just going to say a zero okay so we're gonna do our it's a single scan through prices top lane I plus we're gonna do two checks each time so each time we're gonna check the prices of I less than then we just set them down to prices by pretty standard right this is just I found them in an array like pretty easy okay otherwise this is the well not otherwise but this is just another check we're always gonna do we're gonna do if prices of I - min Val is greater than prices of I - min Val is greater than prices of I - min Val is greater than max profit then we reset the max profit those prices by - min Bell so just those prices by - min Bell so just those prices by - min Bell so just pretty much an intuitive algorithm here you just set the min bow so each time we would go from it would start at 7 and then it would go to 1 and we would check each time you know say it's one now and then we're on element five we would do up 5 - 1 that's 4 so 4 would get set as up 5 - 1 that's 4 so 4 would get set as up 5 - 1 that's 4 so 4 would get set as the max profit because all we have to return is the max profit and then you know if the min bell would stay at 1 obviously in this case cuz one's the lowest value and then you know as we keep looping we always check if prices of I so we'd get to 6 eventually if 6 is minus 1 is greater than max profit then we would reset it and then we get the max profit so really easy right here all you have to return is the max profit that's all we're searching for not really it's kind of like a more beginner problem mode say so that's pretty much it so let me know if you have a better solution but yeah definitely check out the other problems and thank you so see
Best Time to Buy and Sell Stock
best-time-to-buy-and-sell-stock
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock. Return _the maximum profit you can achieve from this transaction_. If you cannot achieve any profit, return `0`. **Example 1:** **Input:** prices = \[7,1,5,3,6,4\] **Output:** 5 **Explanation:** Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. **Example 2:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** In this case, no transactions are done and the max profit = 0. **Constraints:** * `1 <= prices.length <= 105` * `0 <= prices[i] <= 104`
null
Array,Dynamic Programming
Easy
53,122,123,188,309,2138,2144
68
Hello Hello Everyone Diwakar Distance from Type Coding So today in this video we are going to solve this question Text Vacation You must have seen on your browser that all the lines on the legs on which you sleep, they all end at one point. Or the width of the line is determined by the site except the last one on time, so on this video we will see how different it is, friend and tax, its justification is basically how the words are, how are their parents and then solve it. If we will write to do then now some examples back let us understand how the words are inches on the line that if I have these words this is basic one sentence okay this is one sentence and all the words on this all those who WhatsApp them to me One paragraph has to be inserted, that paragraph will have as many lines as it can. If it is three or four lines then this is the max tweet of all the lines that it should be 16th. Okay, 10 minutes to fit the entire world from here to here, I have to close 16. So let's see how this work is done, let's see the size of all these years, on which there are five for me, there are two on this one, there are four on this one is yours, okay what will I do now, I have 16 Line 16 spaces on one line, okay, it's something like this, one line, it has 16 spaces, now what am I doing, as many words can fit in it, no maximum, fit as many votes as can fit here, true, that's all the categories. One will be presented in the middle right then we will be able to disturb that this is a big dude this is the word okay so basically what do I do this here if I put the team then on the next page the match is then there will be a space black here a body After weak there will be a space and then what will be the next okay this one tweet again a blank space at that time loved and again a space and after that the next word here is a traffic jam moment exam so here you can complete it here But its length, gh, example, it is not all on this line, but this is the line that will go after the voice mail, then there will be a space here, okay, it is okay even if it is a line like this torch light, please take record, okay Okay, but if you look at this line now, this line is not justified at all. Right, all the words which are there should have come at the end. Okay, so what does his father do? If I had solar total six pisces. And the length of the word I have is total all swears here 4 5 6 7 8 6 - 81 miles 285 here 4 5 6 7 8 6 - 81 miles 285 here 4 5 6 7 8 6 - 81 miles 285 here art special children 123456789 here space no I will distribute them invalid among all the words ok So here basically I have to delete two places, one at this place and one at this place, so there will be four spaces at both the places. Okay, keep this square aside for this and one penny will go here 1234 Then next year it will be or this time again these 1234 different moods will go NN Okay okay Beau on WhatsApp and here is the word Beau and here is the word The space that was supposed to come between them is basically in village district Everyone has tight but one The question comes that friend, if I do not have any invalid distributed configuration, okay, basically, if I have one more word tight placed here, then it comes here and one more space is placed here, okay, then I would do that basically. What to do in this case, whatever extra space is left with the current one and the first one is 21, basically you can do this in the beginning, okay let's see the pimple, sometime the next body black is here, example on Reliance. Then look at the off express here the text is by taking the offer tena bricks piece, then here the express is again the text, then here the appointed ne main example is of 17 length, then here two lines are done and then four is their thirty. When I went here, everything was snatched, Vande Thirteen The word had come, three spaces were saved, look at this, three spaces are left and how much space do I have, there should be space between all the sections, okay, so express between these two wires here. There will be some specifics for this and there will be a space between these two WhatsApp, the fight wave should end here, the torch light on the ceiling, I want to disturb at both these places, but the second two, the three, that is not possible. Yes, I am not able to event and distribute, can't, okay, so what is going to happen in this case, you come here to give some space on one and here you can know something white, so first of all, tighten one of the enemies, the pieces of both are equal. It's done, I have one more extra left, so again you give it to the starting one, okay, you take 11 more examples. If I have the basis in some space, then this is a bowl here, there will be space here, there is a word, they are here. Word is ok and one more border basically I have to put space three here and here ok so how will I delete this piece first one special this idea to all if you have space left then space to all Make 22 spaces. Okay, now suppose if I had one more space then I would have given an express starting from three to seven and here both places come to 22. Okay, if I had one more space then I would have given those children. This is why I give express, then that's why express, these two worlds sleep on an inch and here two sleep on that, it is okay, if you can be invalid, then definitely do the maximum by deleting the sugar, if you are not able to do so, then you can give a party to the fitting person and give him a little 21 It's better, only good luck will work. 51 I had two places and three spaces, so the starting ones will take Kudus piece and later they will give you one, this special dry at both the places is okay, then the next big one will go to Ajay that here one for money or else Next will be bigger text set torch light it is completely completed at the end ok if the voice is the last line then Uday Singh name moment of text just tell the justification tight then you write that too just-350 caption2 There are some specific children but the last Why is there a line space because here we don't have it so what do I have to do in the middle of all those if there is an if example if there is one after here okay so here basically what could I do if I follow the online strategy above, put two on it here and then put it here, it's fine, but there are no multiple spaces on the last line, there is only one space, here there is a distraction, the express will come and then here or it will go, it's fine. Now all the remaining here will be blank spaces, whether it is one, two or four, only then there will be black money. Okay, so now we know this, let's look at the pimple. Okay, I am basically you start. Or this is the one which we just gave two examples, unfortunately it was just that there was no extra. Okay, the second example, so here what must be, this is the last pandor of course and the space in between is that I have got disturbed on this line. I did not get these awards, so the word started at the beginning and after that the entire space is filled here, okay and the last line, next two words were being fitted here, so there is a space between the two years, okay and the rest of the last line is filled. -Complete okay and the rest of the last line is filled. -Complete okay and the rest of the last line is filled. -Complete space has been taken, here there is not complete space between the two, here there is only one torch light, because in the example here too, the valley could not be distributed, so there are two spaces here, which are two spaces here and There is a space here, okay, it had a place among the total five and there are two deposits from three candidates and one such deposit, here is the next butt, again Sara came in the middle that there is a benefit here too, there should be a district here too. Went to the last line left, there was only one bed left here, if you look at the exam, the edge with torch light was the last bed, after that the entire space is filled here. Okay, so in this question, again, this is the one with words. Hey. It is being given there, got WhatsApp ray and then max with, what should be the weight of each previous line, okay and if yours is that you will generate a string for surveillance of all the previous lines, you will make this trick by tweeting that and now one If you put 19 princes on the list and send it, then it is good. Here, you cannot arrange the words in a big way on the sequence that falls, that is why you will get the order. Okay, this is the second day of the first rules. The order of WhatsApp will not change. 800, you can try now. If you can solve this, then how to normalize it, village, how did you Mirzaam, every moment this WhatsApp light to me, if it was said that hey, you have to print the max length on every line, the max loot, that you have to keep so many people that so many If you can save the character then what am I going to do, I will see, friend, maximum how many words can come, plus that, there is a space in between all the words, only that is fine, only one will be presented, then how many votes can be cast, so let's look at the tight example ball and If this neck tweet was tan or had a lid, is it ok, I do n't have the space. O tell me in this video what to do, first of all it is rank four, otherwise it is rank four, ok, so this one came first, now I want to increase the next one, so this one has to keep a space first. So this one can increase the height of four, this is the first world speech IS of length, if you want to increase the next one, then its length is two, there should be two places along with it also needs a space, it needs Atlist Express Right now, you are looking at the list, Atlist Express is here. Will come then the next one will return this is ok so power if its length is two then it needs 3 places ok or plenty plus request that 728 this is clear guys have come four this five and six together is ok now I know the next one should also come If there is a root then this is also fine, then if there are two lengths, then take one and then add a new one, then this tree will fall on its own, okay, one spray came here, after that, whatever is there, could not fit here, basically. 3 more should have been made, it's okay, they have already come on this, if you add three on this, or if the requirement is more than the number of characters that will go on the 10th, then this one will not fit here, so I was able to add two words. If the words are a global two, then of course the space that will be there will be one hang it a few words - can be made if here make it 1431, okay as many as there are in the space, then the size of the word here was pour plus two. There was a teacher class size and there was a space requirement, okay so what am I going to do here, I will request how much space is the height, now do these words and remove it, I removed it from here to here, okay that here. Total no was tied, there was a gun place here, Meena is there, Varsha has gone, animals have gone, three spaces each is fine here and I have to pay the bill on three spaces, I have to close only one, so here is the one in between the two. Complete on the middle here is ok so take it absolutely and here three two ko tight ignorance if two here sleep on it he still I words are not complete one big here four lane and second word let's confirm name and third again It is from the team, okay, so I will put four lengths here or these three loops of uncle. If these three loops of uncle are fitting on my line, then I have to distribute the space at two places between them. WhatsApp for Night Total Words Pay Hey, how many core plus 600 characters do I do, which line is straight, okay, so basically, how many specific spaces are there, here, like, and then four spaces are left, there are two gun spaces for ghee, that both can be prevented, this is now the court. There are 4 here, I will put the duty on two people, so here, two each will be put on it in the middle of all the classes, site again, if the width on this line instead of voting is mud, then it is fine, it would have been a good day. I have an account of words, the character in the word, their account is 10, right electricity, remaining, the one on remaining is five dysentery and special pass, the place is view account, instead of remaining, it is called vacancy, 25 grams are vacant and how special is it, then the candidate. Candidate, what should I give here, what am I going to do in the fifth 2nd playlist, I will do it with the money given to the youth and now the work has been completed, let's take a big share, if I have equal here, once here, equal here. There is one butt here, basically four WhatsApps, so three candidate space candidates, tight here and here, okay, so what will I do, friend, my line's bad was on that with - I have sung the word's length. that with - I have sung the word's length. that with - I have sung the word's length. Given and w sum if I had got this one then it's okay for the electricity vacancy the vacancy has a sweater and there are 38 candidates okay for the vacancy how will I do it then you make it 10828 battery you get to everyone will get two here will definitely get two Two have come here, two have come here, now the remaining 8 models are left, this is the request, oh tight, these two, the starting one will get more, this one has got one, now there is one ring left, this one will get one, so okay, it's ours. The whole time was correct, WhatsApp was here, the remaining part was vacant, I disturbed the add, so the line became completely full, okay, now we don't have to do this the next day, so the cyber space for the last row is distributed as it is. There is no last on the last rupee, this is exactly the last one but there is only one, it does not do pimples, just gives a space and you fill the stomach on the remaining area, okay then fold it again, now how to call the previous one. Now we are going to see how to implement this on the code customs, so there will be a point up for that, here the lightning is telling that man, this is the word, I have to add something like this here and some people, something like this What will happen is that this is a pointer to me which is telling me to add this word, night, what will I do to you, word count, I will put one on which words of I don't length, this is my length, okay, the word character account, something like this M, after this If I have to add the next guy means that here one and one more quantum can be made in these physical two I plus one is torch light electricity send the next guy that is here it is telling that friend starting is. Basically the work has started from here, it is telling that now add this guy, on the line, he has at least 1 word, now it is fine here, yes here, why did I not check, see, you have a tan strain on this question, by the way. The length of all the words in the army will be less than the max width. Okay, so a single person can always fit on the line, so if the work is starting here, then I have added him directly. Now I have to see whether I am a dacoit person. I can add the character, okay, then the income tax return will be done for this, my current account is okay, four drops on four disks, add plus to it, the words are of Zelda length, hence this Jaiswal word which has two guys, two characters. And along with it will also bring a space tight plus one, if after adding this it is still laddu judicial waste, against the line of maths with k, then you can definitely do this, I will add it and update it. Subscribe The words you don't length ok where I make this paste also legal right now I am working only on the words with the character pace because it was only one day they indulge in the right place ok so again yes this To work, I have to put candy crush here, whatever it is, it should be added, torch light, advice, maybe this one is also added, next one will be too much, so in flight, definitely this one is also added, this one should also be added. Okay, you go here and see the exception. Okay, so basically what it will do is that how many words you can add, it will tell you on the line. Okay, now again what I have to do is I have to find out how many remaining vacancies you have. Is Vacancy Chikli Max Videos Word Count That So Busy And For How Many Pages Are Candidates A The Candidates Electricity If You Had The Word Length You Can Charge Three - There Will Be Word Length You Can Charge Three - There Will Be Word Length You Can Charge Three - There Will Be 43 Spaces Okay Now I Have Kept On The Last One And This Is What It Is Right It is on the word which could not be added and here Z plus will not be there first because here this press thing will not happen. Okay, so I am an example, again we would activate 'g' which I put initially. activate 'g' which I put initially. activate 'g' which I put initially. Four guys are here and plus two. Plus two equals two 8 chapters subscribe to okay so basically this is J and this is exactly here and paid how it Monday I have added this crazy monkey is standing which has not been added okay so total in the middle of this If you want to know how many words are there, then what will I do, then here you give McKinsey - I Laxman, if you give McKinsey - I Laxman, if you give McKinsey - I Laxman, if you write Indian Tech, 02 guest - 20, then guest - 20, then guest - 20, then equation three, you do not need Laxman, you will not need it. Okay, so basically it means how many. How many spaces are there apart from the vote, so on this - it has to be closed right, so here this - on this - it has to be closed right, so here this - on this - it has to be closed right, so here this - I - one, so how many candidates are there on you, I - one, so how many candidates are there on you, I - one, so how many candidates are there on you, J - I liner is okay with so many candidates, so J - I liner is okay with so many candidates, so J - I liner is okay with so many candidates, so again the same and other people use what we have. Before this, show that here do the previous divide so that we will know how much money everyone will get and do it in models, how much extra space do you have this year, torch light, give it to the actors one by one, okay, we have come like this. That if I have three paisa, a torch light, then the actress left will be 082 only because if you look at the actress, if I have the vacancy of all three and I have the extra space, the extra specific three, then this one. Give one, so listen, everyone is getting one, otherwise if divided here, it would have been three, everyone should get three. Okay, this extra is basically never going to be given to anyone, some gun is only going to get extra, so next. Day here is the option how will we do so first of all that a must have at least ok okay atleast must be so many so vacancy divided by a candidate tight and here how many extra are there so vacancy modules candidate how much extra is torch light sticker Now I got all of them, now I start making the line of biscuits on a string form into a string gift for my wards. Okay, what will I do, let's start, put one, then how many pages will there be in the atelier, put so much space, if someone is an actress. If it is then install one expressbis then the next award is fine but if you are here regarding this then basically we will start the work from intake hi-fi and if we basically we will start the work from intake hi-fi and if we basically we will start the work from intake hi-fi and if we go till engine z then it is ok, started the work today and do n't follow the oil, I am before you. Will decide, okay, a string miller will be created here, he will add it on Singh builder, I have added the word tight with the string of WhatsApp off, now I will end space here, so the athlete is telling how many pages there will be. If you are going to be private, then enter here, take some 202 isle of man at least and plus string daughter and had expressed now again that if I have some extra children, that is the one who is a transcendence phone extraordinary, then one more space. Express up and what and extra can come here, each letter has been decreased, so someone has taken away the remaining amount, here all this work of the screen, if then there will be a mistake on the last button, the meaning of the word 'Khedi'. What is meaning of the word 'Khedi'. What is meaning of the word 'Khedi'. What is mine, what will happen to me, first of all, okay, or else some money will go, this word is to be taken on the right side, so here it is here, then here it does not come in the space, okay, so here I am going to generate electricity. We will simply impose a condition that if this is the last stop, your request is Ujjain minus one, then you do not have to do any special work, spread the torch light above, then this has gone commando, so the airline has given me this electricity, all the above except the last one. I had to do tight list for this, I took out the actor, please don't capitalize this last one, I have to give only one space, okay, so now let's take this whole thing and also do one thing, okay, so basically this Extra vacancy, I will have to do all this work by creating a separate blog, here I will check in some way whether this is an extra line, this is the last line, the work was already done, there will be some more work, tight hug in. The question comes that friend, how will I know who is there or not? Look, Akhilesh, basically what it is a cylinder on which your last word has been added. Okay, so if the last word has been added, then it is there next to it here. But it will happen if the dance becomes as big as the J Awards calendar. This was the last line that the last has come in the middle. Okay, so I am part of the collection here, but this work should not be of Akhilesh, if it is seen like this here then it is to separate it. It is not necessary, look, my entire work here, it depends on the vacancy and can, it is at least and extra, okay, so I give this work to my friend, it is good here, if it is a train, I will train it. Let me check, okay, now it will be simple. Committee, remember this one for the foundation. Okay, we joke that if what is equal is what is the last line between the lengths, so here I will do the least one. Now I give and emphasize the extra, oh I will get a tree for everyone and no one will get extra, torch light, the sun will decrease here and here, if the ring builder will be made, then it is okay and everyone will add here now. If there is one more case, then this is basically the work I have done, what will he do now, as many people as were here, 12303 have been added, here is the next turn, what do I have to do, I have to start again from where the police station is, right here, give you We will keep the bar and start creating a new one from this point. Okay, so come on, basically I will sequence you here. Up and all are not printed. The line we created on the free gallery has to be added to a list. Right, this cream. But Ayush will do it for me and will spoil it here that till the time I come to this length I want to learn, I will keep working on it. Okay, now we are here, what should I do, I have to simply add on it, I am SBI dot, A string, okay. And there is a requirement to make a list too. Play list Offspring Loot is new. Hey list, now this work has also been completed and there is still one problem on it and this is the last problem, what is the problem, it happens like this sometimes and not the last. The whole world could not fit on the line like this is an example Torch light Justify And this is further ahead and here there was vacancy left, to complete the vacancy I had to add space here Side should be sixteen length Cannot leave all the springs empty Here we will add to the tree as much as there is remaining space and along with this work is also done on the upper line, that is if you have only this 10 Lanka for two years and also if you have 10 Lanka and you are told that friend who Next is that it is sixteen, so on the first word there will be a word of length 10, soft 6 spaces will come, then that is Shesha Gaya, if Enfield Aslam's dat, space behind, both of them cannot come in one line, okay, I am going to reach you, I will see the similarity in this if from 16. If it is less then keep adding light on it here before adding that if similar juice B.Sc mix this less bank max that if similar juice B.Sc mix this less bank max that if similar juice B.Sc mix this less bank max jhal with then you keep painting on SB Express is ok now this work is completed torch Light it and let's see, the list has to be returned. The words were that I have not made the jhal, WhatsApp ji don't length, it has become a function, here there is a function in bring, write is a pane physically but its length is happened. tha jhal ki chick and demand 204 Here basically what was can and how many spaces are there if one word extends further then there will be no spaces ok so what will I do on that so basically if can request is to head then extra previous zero on the vacancy If it comes, then it's fine. Otherwise, if it's voice, we will calculate it. Torch light. And here too, if there is only one word, then can. If the record is head, then how many should you be at least? If there is no space, then what is the benefit of dividing? By doing zero here too, it is okay, the Ribbon Express here will definitely give the look of light, okay, it has gone wrong somewhere, now Sacrifice and Example two people have gone together, this is a mistake I have made here. On the given function here I have just added the length of the words see something like this here what I had to do is former wonderland which will come next will do 38 it was something like this 3 and will do express and this is ok to the word then the next will come So this will also do 3 ends, I will calculate all these in the evening but the request will be to max with, okay but here we are only word by word so I have added the dot length, space will remain here so something like this will go after this. Now why did I not use Pace for this Ibadat Manage Space did not work, I have added Torch Light Space also, I have a requirement to have an account here, so again you can use the same from here or if you want. Candidate, you can basically increase this candidate will tell you that this is such a specific requirement, there is still increase aerospace, okay, so I said that the word count here and till now is as much as World Cup 2011 and along with it. The candidate with space is ok, okay, because of this reason of the word after me, I have added one to the length of the word, this less should be moved forward, I am still the length of the world and all the spaces in between are also there. After adding parenthood plus one space, if it is small then it is exactly one and yes, as soon as the word is filled, I will delete it, then basically I will know how many candidates are there, okay, who wanted the vote, this work can be done from here also. Okay, so right now this is what it is doing for this, let's submit it and try to see if it is delivering all this. If you have learned something from this video, if you have seen it, then like this video and share it with us. Subscribe to the channel Thanks for watching Jhaal
Text Justification
text-justification
Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. **Note:** * A word is defined as a character sequence consisting of non-space characters only. * Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`. * The input array `words` contains at least one word. **Example 1:** **Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16 **Output:** \[ "This is an ", "example of text ", "justification. " \] **Example 2:** **Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16 **Output:** \[ "What must be ", "acknowledgment ", "shall be " \] **Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified. Note that the second line is also left-justified because it contains only one word. **Example 3:** **Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20 **Output:** \[ "Science is what we ", "understand well ", "enough to explain to ", "a computer. Art is ", "everything else we ", "do " \] **Constraints:** * `1 <= words.length <= 300` * `1 <= words[i].length <= 20` * `words[i]` consists of only English letters and symbols. * `1 <= maxWidth <= 100` * `words[i].length <= maxWidth`
null
Array,String,Simulation
Hard
1714,2260
204
Hello Hi Everyone Welcome To My Channel It's All The Problem Account Friends This Problem Is Cotton Skin Apple Microsoft Amazon Interviews And One Of The Basic Problem Which Comes In Top Problem Starting Programming Ko College Problem Inch This Number And Subscribe Them Total Number Of Prime Numbers For example will start from 12357 adiyan cold subscribe number is number 10 2012 that and have no and the number which is not the product of nov22 prime numbers of the natural numbers which include subscribe share like two three and the prime numbers 2357 rest will not be Called number is clean simple number two will run from serial number between two to two all so much will not find any true two numbers and their chocolate is 0.5 inch time and their chocolate is 0.5 inch time and their chocolate is 0.5 inch time complexity of this side of tell this is the method used oil oo from two to two A separate into a book called this method 151 check whichever is a dish of is prime male account increment account otherwise will keep doing it an Indian will return also account of which problem sunidhi solution vikram ko of n square can use that for rate optimization and use this Thank Subscribe So How Can We Optimize Subscribe Weakness Run Lutaaye And Must Subscribe This Channel * * * Satya 324 504 That Into Three Is Domestic Fuel Other First To Prepare And Similarly 1622 So And 12121 Suid Si Valve Want To Be Our This Channel Subscribe to and subscribe Performance from and to and from This is this problem According to the test Give very much expected Which requires no value Subscribe Policy of electrons So Vijay to Docode Observation made this approach Subscribe Our prime numbers will take off the big and take off the first number to the number multiple subscribe so he also rate wikipedia page subscribe and share subscribe 4,650 will create a subscribe 4,650 will create a subscribe 4,650 will create a 56001 and will also have always mean that 0 subscribe to do French twist for orse sure on enter the time television and similar When veer multiple starting from 9953 already subscribe scanning center for every 1000 hello friends who want to listen and will keep doing cutting this and business account avoid all the prime actual in when members this video and tried to predict your self first section and decoding Part-16 self first section and decoding Part-16 self first section and decoding Part-16 Champion Athlete Window So He Dropped Within That You Will Judge Appointed Solid Prime Or Not Subscribe To Start From All Will Be The Prime Time Of Not Defame Your Tempered Glass Starting From India E Request You To Another Adhinkash Thyother Already Got A Plus Avoid This is prime time to start from subscribe and enjoy a lesson and when skin and hair mask prime of history for its composition and over to select right to run test cases multiple passenger live 0123 floor 500 600 800 a flying and toys seven bigger number 14 porn Such Power Cord Its Boys Were Getting Correct Answers For Maximum Test Cases For Various Types In Film Porn Acid Hearing On 28th Remind Skating Compile Energy Currency Derivatives Were Getting A Wrong Answer Hair So Let's Move Thursday Morning Hair Going To One And All The Distance From i2i a special co i plus se so sorry ft yes ok NSS 400 here not running voice accounting year will not give correct answer sued over evil account after running bishop lucerne weir website for all the best in the time in the world equal speed true increment way Raw Main Soy No Agency Near Death Experience Investigation Agency for Spreading of DR Zeus Running Is Root of End Drut End Steps Ulta Level Meeting Inside Rest of the Prime Beach SP Astrostudents Subscribe Scored and See If You Can See This Code on the Date and Time Complexity After this approach this route on Wikipedia this hair subscribe like and subscribe my channel 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
1,758
hey everyone today we are going to solve the question minimum changes to make alternating binary string okay at first I thought I just change to zero if previous character is one or vice versa but it doesn't work if we have like this like a one z0 1 0 so if we apply the logic to this input string we should return five so because uh first of all we find one right and zero so next should be 1 Z so in that case we should change here and five times right but actually we should return three in this case so that means we should change here and here so after that we will get like 0 one 01 so um problem is uh we don't know um we should start with Z or one that's why we should check the two cases and compare how many times we should change the characters when we start with zero case and one case Okay so let's think about starting with one so in this case the string should be like a one Z One Z something like that right and let me put the index number so 0 1 2 3 4 5 and if we get the remainder of index divide two so that should be like a 0 1 so if we like if we do like a z divide two we will get a zero remainder right and uh if we do like a one divide two we will get a one remainder right so uh string should be 1 0 so this means that if we have the same number of remainder in each uh index so we need to change that character so the reason why we use index divide two is that result of index uh divide two in each index are opposite of 1 0 so 0 1 0 right so it's easy to uh it's easy to count change times so of course you can manage zero and one by yourself but uh this is a like a smarter way right so for example um so the strings should be one Z 0 and one Z and one0 0 so um remainder should be like a 0 1 so in this case um so we should uh change the same number so different and the same so here and here so that's why uh in this case five times uh if we create like a one Z One 0 1 Z from this input uh string okay so let's think about starting with zero case so of course we can manage zero and one and change them one by one but uh I have like a smart idea so when I think about some logic I usually use a small input so let's think about one Z so in this case if we create a one zero and so how many times do we have to change zero right so let's say so 01 case zero times and uh how about one zero case two times right and how about this so input is 0 or one so in that case so one Z case should be uh one right um yeah so if we change one of uh characters so we can create like a one zero right and uh how about 01 case also one time right so if we change um this zero to one so we will create a0 one and if we change this one to zero so we will create like a zero one right so just one time and how about this um Z one so in this case one Z case should be two times right so completely opposite of one Z right so that's why we need to change this zero to one and change this one to zero two times but how about 0 one case zero right we don't have to change anything because uh it's same as 0 one so um let's focus on length of input string and change time of one Z case so in this case so length of input string is two and the change time is zero and how about this so length of string is two and uh change time is just one and uh how about this so length of string is two and the change time is two and the important thing is that so did you realize that so if we subtract number of change time of one Z case from um length of input string so we will get a change time of 01 so length of input string two and the change time of one Z is zero right so if we like calculate two minus Z so we will get two and if we calculate like 2 minus one so we will get one and if we calculate 2 - 2 so we get one and if we calculate 2 - 2 so we get one and if we calculate 2 - 2 so we will get zero this logic works because the input string consist of zero and one only and our objective is to create alternating sequence of zero and one so for example when we have like a zero z0 Z and uh if we create a 1 Z One Z in that case we will change this zero and this zero right two times how about when we create like a 0 one01 so in the case uh we will change this zero and this zero so when we create a 0101 so we need to change characters that we don't change in one Z one0 case so all we have to do is just length of input uh string minus one 1 0 change times equal 0 1 0 one uh change times okay so let's go back to this input string 1 0 1 z0 so if we create a 1 Z 1 0 so in that case we will change this zero this one and this zero so five times right so we will take a minimum times so mean and one of candidates is five pass how about 0 one01 case so as I explained earlier so change time of 0101 case is length of input string minus uh change time of one Z One 0 case so length of input string should be 1 2 3 4 5 6 7 8 so 8 minus 5 so three that's why we should return three in this case so if we create like a 0 1 01 0 one01 so in that case we will change this one and this zero and uh I think this zero right yeah so that is a basic idea to solve this question so without being said let's get into the code okay so let's write the code first of all let's say start one Z so this is a change time of like a one Z One Z case and initial with zero and I start rooting for I so we use a index number and the character in enumerate and the string s and we need to convert uh to integer so int c equal I divide two and I get a remainder if they are same so we should change current character so that's why start one Z Plus equal one after that all we have to do is just return mean and start one Z versus length of string minus start one Z yeah that's it so let me submit it here look get and time complexity of this soltion should be order of n so where N is a length of input string and the space complexity is I think o1 so we don't use a extra data structure this is a stepbystep algorithm of my solution code yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
Minimum Changes To Make Alternating Binary String
distribute-repeating-integers
You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not. Return _the **minimum** number of operations needed to make_ `s` _alternating_. **Example 1:** **Input:** s = "0100 " **Output:** 1 **Explanation:** If you change the last character to '1', s will be "0101 ", which is alternating. **Example 2:** **Input:** s = "10 " **Output:** 0 **Explanation:** s is already alternating. **Example 3:** **Input:** s = "1111 " **Output:** 2 **Explanation:** You need two operations to reach "0101 " or "1010 ". **Constraints:** * `1 <= s.length <= 104` * `s[i]` is either `'0'` or `'1'`.
Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to be assigned to this number.
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Hard
null
904
hi everyone this is steve today we're going to go through legal problem 904 fruit into baskets let's take a look at the problem in the row of trees the ice tree produces fruit with type 3 eye you can start at any tree of your choice then repeatedly perform the following steps there are two steps step one is add one piece of fruit from this tree to your baskets if you cannot stop second is move the next tree to the right of the current tree if there is no tree to the right stop okay note that you do not have any choice after initial choice of starting tree you must perform step one then step two and then back to step one and then step two and so on until you can stop you have two baskets so here's the key you have only two baskets which means they that which means that you can only hold two types of fruits and each basket can carry any quantity of fruit so the basket is of gigantic volume it can hold any quantity of a fruit it can hold like one minute or two minutes but you want each basket to only carry one type of the fruit each what is the total amount of fruit that you can collect with this procedure let's take a look at these examples example one is one two one what does one two one mean it means there are two types of fruits one is the with the number one the other type of fruit is with the number two so it means two types of fruits all right on these three trees there are three trees total zero one two so there are three trees indicated by these and the types of these fruits on these three trees are one and two and one so what why the output is two that is because we can crack all of these three fruits right so zero one two three a total of three we can collect all three fruits that is why we can collect one two and one that'll be that is because one and one these two are of the same type of fruit so we can collect both of them and the other remaining basket is for type two all right i hope that makes sense let's take a look at the second example zero one two and two how many maximum number of fruits that we can carry that is three so let's start from the beginning if we start from zero that means we can carry only two right that is zero and one we can carry only two types of fruit the first type is of type zero the second type is of type one we cannot have type two although there are two of type two fruits right that is because that means we all have three types of fruits but we are only given two types of baskets all right so instead what we want to do is that we want to start picking fruit from type one that means we can collect three fruits which is one two right so here is the explanation let's take one more example then we can start thinking about the algorithm the third example is one two three two okay so if we start picking the fruit from the very first one again we can pick only two right so one and two that's the only two types of fruit two quantities of fruit that we can pick if we start from the very first one right because the third one is of type three which is a different type the third type than the first two which means we cannot put into our only two baskets right so if we start from the second one which is two then we can pick all four we can pick four fruits out of the five which is much bigger than only two right so that is the correct output which is two because two three two so three fruits out of the same type which is two only one fruit is of a different type which is three and this gives us the maximum quantity which is 4 that is why the output is 4. the same goes for this case right so now we can think about the algorithm the idea that comes to my mind is very straightforward it's kind of similar to a sliding window problem we can use a sliding window that keeps that helps us keep track of the maximum number of fruits that we can pick within this maximum within this sliding window what we have within this sliding window is a max of two types of fruits as long as we encounter a new type a third type of the fruit we need to find the first index the starting index of whichever the earlier one that we need to get rid of right and then we'll just keep moving the starting window until we reach the end along the way we'll keep updating the max fruits this is a variable or kind of a global variable that we can keep updating that will give us the maximum fruit that we can pick i hope that makes sense for example here just looking at example three we'll start from here index zero and then we come to here is one and two so the max fruits at this point is two and then we encounter three at this point this is the third type of fruit which we have only two types of baskets which we cannot hold right so at this point we want to find the earliest index the start index of our sliding window in this case it should be two because we have a new one that comes in the only second type that we can hold is the one that is closest to this which is two of course we can have multiple twos here then we'll just define the very first index of two that doesn't have any other types of fruit in between this two and this three i hope that makes sense and then we'll just keep moving the sliding window two pointers starting index and any index all the way to the end of this given tree array along the way we're updating the max fruits variable in the end we'll just return max fruits i hope that makes sense if it's still kind of confusing let's put the idea into actual code then everything will be much clearer now let's start writing code first i'll have a variable called max fruit in the end we'll just return max fruit next we can have a simple integer don't be scared that this is a set is going to give us o and space complexity no it's not it's still o1 time complexity because we're only going to maintain two elements in the set right because we have only two types of baskets new hash set next we'll have a index i'll call it start index will start from the beginning and then this is basically the left pointer of the sliding window the right pointer keeps moving towards the right and the left pointer will update it as well if we encounter a third type of fruit let's see tree length i plus if as long as we have never encountered two types of fruits yet that means set size is smaller than two or we have encountered two types of fruits but both of the two types of fruits the one that we're currently iterating on is still one of the two types we're still good so set contains tree i if this is the case what we can do is we don't need to update the start index what we need to do is that we'll just add this one into this set and this set will just contain the two types of fruit that we're currently have in within our sliding window and then we'll also update max fruits we always try to update this one just in case there is any possibility that we have a bigger sliding window size so here we'll have i minus star index plus one so this is going to give us the maximum possible length for example let's take a look at this one this example well i starts from zero and then so the first one and two so we first go to one right one is here is it's going to come into this if branch because at this point sat is empty then we update here i is zero minus zero is zero plus one is one so max first is going to give us one right i hope this may make sense and then else we only need an else we don't need to check whether the size of the set is going to be greater than 2 because that's impossible as long as it's not smaller than 2 it must be equal to 2 because that's just the size of the set that we're going to control if this is the case what we're going to do is that we want to find the last index that is not of this type for example here still we're looking at example 3 at this point when we iterate on this type of fruit which is three what we want to do is that we are sure that this is the third type of the fruit because there's already two types of fruit in the set already what we're sure is that the one that is right on the left side of this one is the type of fruit that we can sure that we can be sure that we can maintain in this hashtag in our basket because this is the second type that we are going to maintain however we need to find the very last index of the originally first type of the fruit all right in this case it's going to be this type which is one so we want to find the last index of this type of the fruit because we find a new type of fruit and this one is going to replace the position of this one so we need to find it i'll have another variable just called last one and this is the one that this is the originally second type but it's going to be the other type of fruit the second type of fruit that we can maintain in our current in our newly expanded sliding window so it's going to be i minus 1. in this case suppose we're iterating on this type of root and this i minus 1 is going to be 2 right so what we want to do is we want to find the last index that is not two of type two so we want to find one so what of course this is not super optimal i'm just writing a for loop inside the for loop so this is going to give us some not super nice time complexity but at least it's very straightforward i understand so in this case we want to start from i minus 2 which is this one if i is at this point here and i minus 2 is going to give us here and then j is greater than 0 j minus as long when emery we encounter the one j not equals to last one that means one and two then these two types these two fruits are not of the same type then that means we find the index that we want so we can update the start index to be this one to be j plus 1 which means it's going to be this is j and j plus 1 is this that means we find the start index and then we'll remove this one from tree j then we're going to remove the original first type of fruit that we used to keep in our sliding window which is this one right we remove this type of fruit in this hashtag now we can just break out this is guaranteed to exist because the only it will come into here only when the size of the set is equal to two so we can safely break out now what we also want to do is that we'll add this new type of fruit into the hashtag and also we'll do we'll try to update the max fruit all right this is the entire algorithm now let me hit run code to see if it works hmm it doesn't let me take a look what's going on it gets index minus one out of bounds for length three somehow it comes here let me double check if the size oh i think this should be all right because this is either we have not encountered two types of fruit yet or we keep encountering the same type of these two types of fruit so this should be an all condition instead of n let me hit run code again all right accept it now let me hit submit let's see if it's going to work all right accept it is uh not super impressive i guess it's because i have a nested for loop here so feel free to optimize this we can actually use just one more index as long as we keep track of the last index of the first type of the fruit that should be good let me hit run time submit again and really know that's totally fine but here is the idea of this problem i hope it makes sense to you guys for uh helping to understand this problem it's you can call it a sliding window solution or two-point resolution it's solution or two-point resolution it's solution or two-point resolution it's not really two-pointed because i have a nested for two-pointed because i have a nested for two-pointed because i have a nested for loop here of course you can you guys can optimize this by not using a nasty for loop you can just use one more variable to keep track of the last index of the first type of the fruit in the sliding window that should simplify the code and help with the time complexity as well but here's the idea please do me a few and gently tap the like button that's going to help a lot with the youtube algorithm and i really appreciate it also please don't forget to subscribe to my channel as i have accumulated quite a lot of different legal tutorials data structure and algorithm videos and also amazon web services certificate how you can help prepare and study for stanford aws materials and get aws certified feel free to check them out hopefully i'll just see you guys in just a few short seconds in my other videos thank you very much for watching see you guys in the next one
Fruit Into Baskets
leaf-similar-trees
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the **type** of fruit the `ith` tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: * You only have **two** baskets, and each basket can only hold a **single type** of fruit. There is no limit on the amount of fruit each basket can hold. * Starting from any tree of your choice, you must pick **exactly one fruit** from **every** tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. * Once you reach a tree with fruit that cannot fit in your baskets, you must stop. Given the integer array `fruits`, return _the **maximum** number of fruits you can pick_. **Example 1:** **Input:** fruits = \[1,2,1\] **Output:** 3 **Explanation:** We can pick from all 3 trees. **Example 2:** **Input:** fruits = \[0,1,2,2\] **Output:** 3 **Explanation:** We can pick from trees \[1,2,2\]. If we had started at the first tree, we would only pick from trees \[0,1\]. **Example 3:** **Input:** fruits = \[1,2,3,2,2\] **Output:** 4 **Explanation:** We can pick from trees \[2,3,2,2\]. If we had started at the first tree, we would only pick from trees \[1,2\]. **Constraints:** * `1 <= fruits.length <= 105` * `0 <= fruits[i] < fruits.length`
null
Tree,Depth-First Search,Binary Tree
Easy
null
693
hello today's problem will be problem number 693 that is binary number with alternating bits the problem statement is given a positive integer check whether it has alternating bits namely if two adjacent bits will always have different values so let's take an example of what the problem statement states is so we are given an input n is equals to 5 and we are returning true why so because the binary representation of 5 is one zero one and at every position it has different bits preceding to the bits before it or the adjacent bits you can tell so at zero we have one at one we have zero so the next positions bet is one so this should return as true let's take an example of 10 so this is the my representation of 10 it has different bits in every position so this will give true again and let's see how we're gonna do it so the intuition behind the program is to first take and store the last bit of our integer or the value given so how will find the value so we'll just do n mod 2 and we'll get our last index value so x will be storing zero and we'll simply take y we should not take y first let me just first delete it so after taking x is our last bit so we'll delete our last value because we have taken x we need to compare two adjacent bits right so we'll be comparing zero and one so x is storing my zeroth bit so how will we store the first bit will simply delete this bit and we'll store this bit so n is equals to n by two so the zeroth bet is related now so this is deleted our current bit looks like this one zero one so we'll store y is equals to n mod 2 so this will store my this bit this is our last bit right now so this will store this 0 and 1 and we'll just check if x is equals to y so if x is equals to y then we'll be returning false or else we will be returning true so this is our total algorithm so let me just show it in the code how we are going to do that so in the code we have taken a quite a bit different approach than it just to save some more time so as we were here we will in the while loop this whole part was executing in the while this whole part so as we can see the x and the y these are getting repeated we do not need two variables to be repeated again and again we can do it with just one though we'll be requiring two variables to store the value of x and y or the current at the previous values but we can do this in only one operation and store it so how are we gonna do that let me just erase this okay so this should do again we'll be taking the example of 1 0 that is 10 1 0 so first we will store the last bit in our x value or x variable that is n mod 2 and then we will enter our while loop this is our while loop w so this is our while let's take this as our while loop and what we will do is we will store y is equals to x and why we are doing this i'll just get to it y is equals to x and then what we will do is we'll just delete the last element like what we were doing in the previous example that i showed you so we'll just delete the last element and how we can do that we'll just do n by two so this is it and this statement is n is equals to n by 2 the statement is n is equals to n by 2 and the next statement will be x is equals to n mod 2 so we have already deleted this part and now we are left with this bits so now we have left with this after this iteration so in this iteration we are having 1 0 1 as our current n so x is equals to n mod 2 this should store this bit here so we'll store this bit here and we'll be comparing y is equals to x and y is equals to x so what was y is value was the previous value here which we deleted that is zero so y's value was zero and x's value is one so is z is equals to one no so we'll continue and if y is equals to x that means if there were to be 0 instead of 1 then if this is 1 0 and this is also 0 or this could be 1 even so if z is equal to zero that means the zeroth position value and the one position value is are both equal then we'll be returning false or else we'll be just returning true and the code part is let's get to the code part and this is just the implementation of it and i have done here is zor operation here just simply means n is equal to n by two nothing so dramatic nothing too different it's just a basic is or operation if you know it and this should return false and this should return true so what i'm doing here is i'm just taking the last index value i'll be iterating over the loop and then i'll be storing y is equals to x that was done here y is equals to x which will store my previous and current value of the bits and then i'll be returning let's run the code okay this gets accepted let's run some sample test cases and let's submit it and this is working perfectly fine and there's a much cooler way to do this problem so that is with bit manipulation and i'll be showing that too and i'll be just releasing this part the whole part what is this and let me take an example of that just state 10 again so that is 1 0 so this is 10 our n value and we know the zor property that is if we do ones or zero then it should give me one and if we do saw of the same bits that is one will be getting zero or if we do of zero and 0 will be getting 0 so that is it so we'll just do the saw of this number that is 1 zero one zero with the right shift of n to one that is n will be right shifted to one that is
Binary Number with Alternating Bits
binary-number-with-alternating-bits
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. **Example 1:** **Input:** n = 5 **Output:** true **Explanation:** The binary representation of 5 is: 101 **Example 2:** **Input:** n = 7 **Output:** false **Explanation:** The binary representation of 7 is: 111. **Example 3:** **Input:** n = 11 **Output:** false **Explanation:** The binary representation of 11 is: 1011. **Constraints:** * `1 <= n <= 231 - 1`
null
Bit Manipulation
Easy
191
787
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 cheapest flights within K stops so in this question we are given n which represents the number of cities and they are connected by some number of flights you given an array called Flights where every element inside the flights array represents three elements the first element in every flight represents the from and the second element represents to which is the destination and the third element represents the price which will take to fly from source to destination so this indicates there's a flight from source to destination with the cost of price which is the last element inside every flight so we are also given three integers Source destination and K and our task is to return the cheapest flight from source to destination with the at most K stops if there is no such route we have to return minus one as our output now in this example n is equal to four which represents the four cities 0 1 2 and 3 and we are given the flights areay and this is the source this is the Destin and this is the price to fly from 0 to 1 it is taking 100 so to fly from 1 to 2 it is taking 100 again to fly from 2 to 0 it is taking 100 fly from 1 to 3 it is taking 600 to fly from 2 to 3 it is taking 200 and the source is zero and the destination is three so these are the targets so we have to start here and we have to end here and we can take Max k equal to 1 K stops in between so we start from here where can we go it has only one outgoing path so you go from 0 to 1 and K is equal to 1 and from one where can you go you can go to two or you can go to three so initially you went from here so the total price is equal to 100 if you go from 1 to 2 the total price is 100 but K will become 2 is greater than k is equal to 1 K can Max be 1 so if you go here you end the iteration here and this is not the destination so you can't go here and what is the other way you can go here once you reach here that is the destination but what is the price you're paying 600 the answer is going to be 100 + 600 which is 700 which going to be 100 + 600 which is 700 which going to be 100 + 600 which is 700 which is the expected output here so here we are going to start from here and we have to end here right so what comes to your mind to form the shortest distance so to find the shortest distance you always have to go with BFS so this will give you the shortest distance but here the problem is this is a weighted graph BFS will work on unweighted graph because for example if we have this uh graph so you can't directly applied BFS because here we start with the initial node and we add this into the queue and in the next iteration we are going to access this level and here as you can see you already reached the destination you found the destination from source to Destination 1 to 3 and the cost is equal to 250 and you return 250 as the output because you found the destination but that is not the shortest path because in a weighted graph there are other ways also to go so you can go from 1 to 2 and you can go from 2 to 3 three and you can go from 3 to uh this is four so you can go from 2 to 4 and you can go from 4 to 3 and this path is going to cost you 50 + 20 + 10 which is equal to 80 and there + 20 + 10 which is equal to 80 and there + 20 + 10 which is equal to 80 and there is also one more path 1 to 2 to 3 which is going to cost you 90 but here the shortest is 80 so 80 will be your output so you can't directly apply BFS on a weighted graph but here it says that you have one more metric that you can take Max K stops so here once you reach this level so if you say this is L1 and this is L2 here K is equal to Z and here K is equal to 1 and you can still go further because K is still one here K will become two it means you can't go down from here this is the last level you can reach with K is equal to two so from here you can still go to this level so here we can apply BFS on a weighted graph even if there are weights we can apply BFS because of this condition of K which we are given as input in our question so let's take one more example and see how we can apply BFS and build our adjacency list to calculate our output and as we know for BFS we have to use a q to keep track of all the nodes in every level so let's see how we can solve that so let's take this example we have to find the shortest path from 1 to 3 and number of stops is equal to 2 so here we are going to keep track of the shortest distance for every path so I create an array which is going to have the same number of n here n is equal to five right so I create an array short as distance and before implementing BFS we have to make our adjacency list right so we have to build our adjacency list from the input flights array so I create a adjacency list using hashmap where the key is going to be the source and the value is going to be the destination and the cost so this is going to be an integer array with a list so this will be inside a list so initially we are at one so for one what is the outgoing uh distances we can go to two and we can go to three so two 2 what is the cost it is 10 and we can go to three what is the cost it is 50 so those are the two outgoing bounds for one and now we go to the next and for two what are the outgoing lists we can go to four we can go to three so take two you can go to four and it will take cost 10 you can go to three and it will take cos 30 and next for three there's no outgoing bounds for three so you can't go anywhere so for four you can go to three and you can go to five for three it was taking 15 and for five it is taking five and from five you can go to three so for three it is going to take five and that is the only element and now to implement BFS we have to keep track of a q which will uh go level by level we start with this level so we Implement Q as a link list right so initially inside the Q we add the source and the distance is zero so to reach one from one it is going to take zero distance and initially inside this distance array we are going to fill with the maximum possible value that is 2 power 31 minus 1 so these are the index positions but let me represent them as nodes so I'll change them to 1 2 3 4 5 so now we access this element and add it into the Q what is the shortest distance to reach one and one is the source it is zero so update that value to zero so to reach node one it is going to take zero distance and from one what are the outgoing nodes it is going to access the adjacency list it is 2 and three so for two what is the maximum value it is 2^ 31 - 1 or 10 what is the value it is 2^ 31 - 1 or 10 what is the value it is 2^ 31 - 1 or 10 what is the value which you can use 10 right that is the shortest distance you can uh reach for two so you update that and for three it is 50 so you update that to 50 go to the next level of the BFS the next level is 2 and three so these two will be added into the Q so 2 comma 10 and 3 comma 50 are added into the Q because these are the two uh nodes which we visited and after adding we updated those values into the cube by comparing it with its previous values we keep track of the number of stops we made until now we it was initially zero so now we reached here it is still zero once we expand this will be incremented to one now we are going to the next uh expansion right we reached uh till here and we reach still here and now three is the destination and there are no outgoing nodes for three so you can't expand here but from two you can go to three or you can go to four so there are two expansions so add those into get these adjacency list for two because we are at two so we are going to four to go to four we update uh the value that is the previous distance 10 which we reached until 2 and from there to four it will take 10 so the total distance is 20 so 4 comma 20 is added into the Q and for 3 to 2 you use 10 and from 2 to 3 you use 30 so to reach three you're going to use total 40 and now we update our values to reach four what is the uh value it is 20 or 2^ 31 - 1 which one is value it is 20 or 2^ 31 - 1 which one is value it is 20 or 2^ 31 - 1 which one is shorter it is 20 so update it with 20 to reach three the prev previous value was 50 and the current value is 40 what is the minimum it is 40 so updated and now you can remove this from the que and this also is visited so these are done and now the total number of stops is equal to one now to go one step further from four so this reach the end here and from four you can go here and you can go here so we increment one more stop so from four we expand its value so from four you can reach three but what will be the value it is 35 and you can reach five which is 10 + 10 + 5 which is 25 5A 25 so update 10 + 10 + 5 which is 25 5A 25 so update 10 + 10 + 5 which is 25 5A 25 so update the values now compare with three what is the value 40 is there 35 is there what is shorter 35 for 5 it is 2^ 31 - 1 what is shorter 35 for 5 it is 2^ 31 - 1 what is shorter 35 for 5 it is 2^ 31 - 1 it is 25 what is shorter it is 25 so update the value and now you can remove them from the Q and now K is equal to 2 and to go further we are at five but we can end our iteration here we don't have to expand for five to check if it is three because we reach the max limit if you want to expand for five we have to increment by one and this is three but this three is greater than two there is no use of expanding this path because we violating the number of stops so we end the iteration here because we kept track of this and once this condition satisfies what is the destination is three and the shortest value which is present at 3 is 35 so 35 is your out 35 is your output because this is the path you can reach the shortest value 1 2 to 4 to 3 so 1 2 to 4 and 4 to 3 has the value 35 whereas 1 to 3 has the value 50 but we need the shortest part 35 is shortest so we got 35 as our output now let's implement the steps in a Java program so coming to the function given to us this is the function name this is the input and representing the number of cities these are the number of flights and these are the three integers Source destination and C so let's start off by building the adjacency list so I'm going to use a hashmap so the key is going to be the integer which is representing the source and the value is going to be a list of integer arrays which is going to store the destination and the price for the source to destination now we need to iterate through the flights array using a for each Loop so I create a for each Loop and iterate through the input flights and we are accessing one flight at a time and then we are going to build our adjacency map so here as you can see we are inserting the source for every flight in the key which is the integer and the value is going to be an array in the form of a list so I'm creating a list and adding an array into that list and the list is going to contain the flight one and flight two index so this is going to be the first element inside the array and this is going to be the second element inside the array so this will happen for all the flights that is the input given to us and our adjacency list is ready now we need a distance array which will store the shortest distance until that City so it will be of the length n given to us so I create a array which is of the size n which will represent the shortest distance for that index so shortest distance of 0 will represent the shortest distance for reaching destination 0o and similarly for Destination 1 2 and 3 what is the shortest distance so initially I'm going to fill this array with the maximum possible value so I use arrays. fill to fill the shortest distance array with the maximum possible value so all the values inside this are initially going to have the maximum possible value now we need a q to implement BFS so Q is represented as a link list and it is going to contain integer arrays and now initially we fill our Q with the source so whatever is the source what is the shortest distance to re The Source it is zero right so I add source and the value zero into the Q now we need to keep track of the number of stops we made until now so we need an integer variable so I create a variable stops which is initially zero now I need to iterate through the Q so until this Q is empty I keep on running a while loop so until the Q is empty we keep on running the while loop or we also stop this iteration the number of stops we made until now is less than or equal to K once the number of stop stops are greater than K we stop our iteration and whatever is present inside this distance array for the destination will be returned as out and now we need to find the length of the current Q so that we have accessed all the nodes inside the current level so initially we access this so BFS is level order traversal right so we need to access all the nodes in the current level so I find the size of the Q and store it inside the variable Q L and now we use a while loop again to iterate all the current nodes inside the current level so until this length becomes zero we keep on iterating this while loop now we are accessing the array present inside the Q by using the pole method and storing it inside temp and inside this temp we are having the node and its distance so we extract the two values present at temp of 0 and temp of one temp of 0 has the node and temp of one has the distance and now we have to check if this node is not present inside the adjacency list as key then we skip the current iteration and go on to the next iteration so if the adjacency list which created does not contain the node as key then we just skip the iteration by the continue keyword and now we can proceed further if this statement is skipped it means that this node is present inside the adjacency list so for that node we get its corresponding value and inside this value we have an array right so we need to iterate through all the list members present inside the array so I'm getting the value of the current node from the adjacency list and storing it inside the array and now we have to extract the elements present inside this array so e of0 contains this value and E of one contains this value and what are we storing inside the adjacency map we are storing the source and for that Source we are storing its destination and what is its cost so for every array present inside that list we have to extract its node that is its neighbor so from the map we extracted this value and stored it inside neighbor and we are extracting the cost and storing it inside this variable cost now for this distance we have to add the cost and check if it is less than the shortest distance value present inside this are so if the cost plus the distance is greater than equal to the shortest distance for that neighbor then we don't have to continue our BFS so we skip our BFS using the continue keyword else it means that this value is less than the shortest distance so we update the shortest distance variable with this value so shortest distance of neighbor is equal to Cost Plus distance and now we have to update this value into the Q also right so we add that neighbor and its shortest distance value into the Q and now before going to the next iteration that is before expanding to the next level we increment our stops variable so that we check if this condition still holds true only then we proceed further and now finally outside this uh while loop we have to handle this case that if there is no path the shortest distance for the destination index is still going to have the maximum possible value so we check that if still that value is equal to integer. max value we return minus1 else we will return the shortest distance for the index DST so we are going to return by checking the condition that if the shortest distance array at the distance index position is still having the maximum possible value then we return minus one it means there is no path we haven't updated that value else we will return the shortest distance value whatever is present at this index as the output now let's try to run the code the test case are being accepted let's submit the code and a solution has been accepted so the time complexity of this approach is Big of n plus e into K where n is the number of cities which is the input given to us and E is the number of flights inside this flights array and K is the maximum number of stops we can make to reach from source to destination so here we are using bigo of n to fill our distance array and E into K is that we are iterating through all the edges inside the flights array maximum K times so in the worst case we have to iterate every Edge K number of times so e into K so the overall time complexity is Big of n plus e into K and similarly the space complexity is also B of n plus e into K because we're using a Q and the reasoning is the same as the time complexity that's it guys thank you for watching and I'll see you in the next video
Cheapest Flights Within K Stops
sliding-puzzle
There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`. You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _to_ `dst` _with at most_ `k` _stops._ If there is no such route, return `-1`. **Example 1:** **Input:** n = 4, flights = \[\[0,1,100\],\[1,2,100\],\[2,0,100\],\[1,3,600\],\[2,3,200\]\], src = 0, dst = 3, k = 1 **Output:** 700 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. Note that the path through cities \[0,1,2,3\] is cheaper but is invalid because it uses 2 stops. **Example 2:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 1 **Output:** 200 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. **Example 3:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 0 **Output:** 500 **Explanation:** The graph is shown above. The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. **Constraints:** * `1 <= n <= 100` * `0 <= flights.length <= (n * (n - 1) / 2)` * `flights[i].length == 3` * `0 <= fromi, toi < n` * `fromi != toi` * `1 <= pricei <= 104` * There will not be any multiple flights between two cities. * `0 <= src, dst, k < n` * `src != dst`
Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move.
Array,Breadth-First Search,Matrix
Hard
null
1,673
hello guys welcome back to the channel today we are solving another lead code problem that is 1673 find the most competitive subsequence before jumping into the solution I would highly recommend you should read the problem statement on your own and give at least 15 to 30 minutes this problem so let's get right into it what problem is asking that you need to return the most competitive subsequence so what is subsequence you know if you are given elements you can take whatever you want but you cannot change their order so this much is clear and what is competitive over here means if you have read you know but still I would convey if this is a subsequence and we have to decide which one is the most competitive one I would say one three four is the most competitive subsequence as you can read over here we will take the one which is smallest and in this case this one is the smallest so let's take an example to have a more better understanding so if this is the case and K is 2 you have to return the smallest competitive sequence of length 2 so let's take make the subsequence 2 and 3 comma six five comma 2 and 5 comma 6 and last one is 2 comma six and when you first compare which I would say you know 2 comma 6 is the winner because it is the smallest not like this case because here one duplicate Do Not Duplicate same but here 4 is this smaller than 5 so that's why we take we took one comma three comma four so that's why also 2 comma six so I hope you understood what you have to do so now let's do the observation so very first observation would be can we say smallest subsequence instead of continuously naming competitive subsequence let me explain as you can see this is the length 2 subsequence and which one we did took and which one is also in the answer it's 2 comma six so that points to one thing smallest subsequence so you can say this also so if this is true it also means something it is in increasing order the smallest number will always be in the increasing order for example take these three digit and make the smallest number so smallest number would be 1 comma 2 comma three or 123. as you can see and you can make yourself but one comma two comma 3 will be the smallest and you can see the number are in increasing fashion so it's again points to something but still wait how we can approach this if Is it feasible to make the subsequence and then decide no I hope no and I am sure no not hope I'm sure no because n is around 10 to the power 5 and if you make every subsequence and then compare it will not be a good time complexity we need something kind of O of n and now back to the point how we gonna do this of any kind of thing and we want increasing order and we want insertion and deletion option faster because we want to do this o of n which data structure we should use which algorithm we should use I would say monotonic stack because it fits our requirement because we can push in O of one we pop you know of one that is pretty much fast and why monotonics tag because it is in increasing fashion monotonic means increasing decreasing but in this case we are taking increasing stack so increasing order we need and we take increasing sorry monotonic stack of increasing order by for obvious reason of one push and over one pop so now still one thing is left we are also given k we have to deal something what we have to can we take K like this number of deletion is equals to length of this nums minus the k so over here length was 4 and K was 2. so by chance it is that number of deletion K is similar but there are cases where number of deletion are not similar so let's get back to it why number of deletion is required so let's see in the above case you selected two comma 6. there are two ways to select 2 comma six one is select two comma six or another way could be in this given nums how you can get 2 comma 6 when you delete this Take 2 comma 6 is the one way or delete three comma five to get 2 comma six okay which way to select I would say this way why because it is not easy to take two comma 6. because you cannot just jump to two comma six you will take three comma five you will take three then how will you decide that not in future you will you can get something smaller it is little difficult and we are using stack and we want our algorithm to be easy and also fit in monotonic stack because we want smallest but doing this is not easy in monotonic stack because if we take 3 comma 5 not 3 comma five sorry if we take three then how will we decide that 3 is the smallest if we take three because we cannot just jump to two comma six we have to iterate over it and we are using stack you know why monotonic stack everyone is increasing fashion three comma 5 is in increasing fashion so why delete three comma five why delete three comma 5. 3 comma 5 will only be deleted when we'll encounter 2 comma 6. so in order to get to 2 comma 6 you have to delete 3 comma 5. that is the case that we will delete three comma 5. to get to 2 comma 6 because they are also in increasing we have to delete them the three comma five so that's why we are taking this route or deleting 3 comma 5 because 2 comma six if we will search for 2 comma six things will not fall in place but if we do that we need increasing if we go with the mindset that we need increasing so when in the stack 3 comma 5 is present and we have the mindset that we need increasing so what we will do when 2 is in counter 5 is greater pop it three is greater pop it so then 2 will be pushed and then 6 will be pushed also because it is increasing order and we will get our answer so how many deletions we have to do is the length minus the K that many deletions where we have to do in this case we have two but in other case we will not have K and number of deletions same so this much is clear the whole thing is clear let me write the algo and summarize everything what we will do is must have a monotonic stack second we will iterate over it and what we will do we will fill normally if top is greater than the current element the Curve and also the k this one would be the third step my bad Second Step would be the calculate number of deletion is size of array minus k and not k number of deletion because we cannot pop on our own because we have to have number of deletions so that's why this condition F this condition is true what we do we pop that's very basic kind of thing if you have done monotonic stack question and if this condition doesn't strike what we do just push and we keep on doing it and also one condition will be left if we get out of the loop by any chance and the number of deletions are still left because we have to do that number of deletion to get two comma six you know it doesn't mean to sorry the K and number of deletion will be same I am repeating again and again so in this fourth one is also important is if the number of deletions are left if number of deletions are left what we have to do we have to delete those numbers so what we will do if the size is still there and also number of deletion not K why I am writing K again and again number of deletion is still left what we do we pop and number of deletion minus that's what we will be doing and after that we just return whatever is in the stack we you can take it in the vector and just return it or even that we can take Vector only because there is a back function like top back function is also there so we can take Vector also and I just forgot we should have a number of deletion minus also so this is our elbow let's see the code and I will run that code only so let's see this is with our code instead of using stack I am taking vector so I just updated but you can name it number of deletion I just updated the K you can delete uh sorry not delete you can take number of deletions this is iterating and what we are doing over here is this if the size is still because we cannot access the back if size is zero obvious reason basic C plus if the back is greater than current we took n but you can write current and K is still there what we do pop back and decrease the K and if this condition doesn't strike what we do just push it we keep on doing and after that when we get out of this while what we will do check if is it has still the size and also what we will do if K is still greater than 0 so what we will do is pop back keep on popping and it is a short way you can also declare K minus not declare write K minus inside it I just wrote in the while loop basically both means the same thing I hope this much is clear there is no requirement of this I just return there is no requirement of this yeah there is no requirement of this and yeah this is the whole code let's try on it and see if it is running or not this is the code let's take the test case let's take a smaller one because video will get longer yeah this is the test case yeah we are iterating we are let me write it over here in case two we are over 3 and size is 0 this will not be triggered we just push it now we are at five size is something but back at back we have three and three is not greater than five so what we do just push it now here comes the two size is also back is back greater than two yeah it is so what we do pop it and what we do K minus over here K is number of deletion let me write it number of deletion is 2 but it doesn't mean that it will always be same you can do that how you can do that not do that check that do not do this step and run your code you will get the test case that you want to do this much I'm not doing that so when this happened we decrease the number of deletion to one now still we check is 3 greater than 2 yeah now again pop it this time it's 0 so we have exhausted or all are deletion now we push it to because this line will be executed when we get out of this Loop so after this we are over 6 and what we check back greater than this what is Back 2 is greater than 6 no just push it and we get out of this Loop and K is also zero this will not be encountered and we just return it why we are able to return it stack because we have took a vector you can even take a stack and just pop it and reverse it and just do it why reverse it because it will be something like this 6 comma 2 and you need to return to gamma 6 so do not change the order it is a subsequence I hope this much is clear so let's submit it and see if it is running or not yeah it is running I hope I was able to make my intuition pretty much clear and if I was so consider subscribing to this channel liking this video and sharing with others and if you have still problem with monotonic stack I have other videos on the channel on monotonic stack you can go and watch it so you have to do what you have to do so keep grinding you guys are awesome see you in the next one bye
Find the Most Competitive Subsequence
find-the-most-competitive-subsequence
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`. **Example 1:** **Input:** nums = \[3,5,2,6\], k = 2 **Output:** \[2,6\] **Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive. **Example 2:** **Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4 **Output:** \[2,3,3,4\] **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `1 <= k <= nums.length`
null
null
Medium
null
143
at least you're giving the hand of a single linked list the list can be represented as node 1.203 etc node 1.203 etc node 1.203 etc so basically we're giving your legs for example one two three four we want to reorder to be one four two three so one and then last note and then second and second to the last and then this is the question and then for this question I'm going to separate it into different steps I'm gonna first um found the middle of the link list and then I'm gonna split the link list into first half and the second half and then I'm gonna reverse the second half of the blink lace and then I will um iterate through both linked list and then January and then change the pointer so I can manage to link list first let's start coding so first I want to find the middle so to do that I will have used it slow fast printer message so I will have a slow pointer pointed ahead and then I will have a fat pointer also point to the Head and also I want to have a list node called first half here so I can keep track of the tail of the first half now and then I will say well if that's not equal to now and fast the next that's equal to now I will update the first recorder I will move through one other time and then move fast to another time and then also before I update oh I want to record keep track of the slow so I will say first have to tell equal to slow and then after the while loop my slow should be at the head of the second half like this so I want to separate those two lists so to do that I will just say first have to tell about next equal to now and then next step is I'm gonna reverse the second half to reverse that I will have a fill pointer I will have a current pointer slow and uh another one I will have a previous initially printer now then I will start the world look so well curve not equal to now okay I will first have record the next note petition so I will say 10. equal to third.next third.next third.next and then I will say create the next equal to previous node update to current node and the current node 32 times node after this process the second half is reversed next step is to merge so to merge um we first make sure to get ahead of both lists so for the first half the head will be the original hat and then for the second half the head will be the previous node and then after we get that we can have a while loop so well true in Center for Loop I will say first for example for this example we have one two three four so after the first two sets we have first half one two second will be fourth three so we want 1.2 so we want 1.2 so we want 1.2 second half hat so also before I do that we need to keep track of the next note so we don't lose the reference so first we have this node I will call it temp one it will be storing the next note so I will say ten one equal to First the next after doing that I can change the pointer so first the next well we'll point to the second and then after that I will update the first note first down equal to Temple and then I will do the same similar scenes for second list so come to uh second the next and then second the next Echo first second equal time two okay there are some edge cases we need to take care for example we need to have a terminal condition so let's say when we add two after that we first will track the next position which is now so here we Temple will be now and then after we change the pointer we update the first two now that means the first list is we reach the end so that means the merge process is complete we don't need to do anything because we don't want to continue to make the second is point two now so in that case we can say if first go to now we know we finished so we can read and then actually we can say break yes so we break through the breakout the while loop and then this is how we code it so let's see let's handle some edge cases so if hat is equal to now or at the next equal to now that means it's an emptied English or doing this with just one node in that case we don't need to do anything so we can just return and then lastly the time complexity will be often even though we have one two three Loops which is three but we drop constant so it's become an and the space complexity will be all of one as we can see we do always in place we didn't create any other data structure so let's use constant space next Let's test this code before let me go through one last time let's submit we pass the test
Reorder List
reorder-list
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **Input:** head = \[1,2,3,4\] **Output:** \[1,4,2,3\] **Example 2:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,5,2,4,3\] **Constraints:** * The number of nodes in the list is in the range `[1, 5 * 104]`. * `1 <= Node.val <= 1000`
null
Linked List,Two Pointers,Stack,Recursion
Medium
2216
203
hello and welcome to this video today we will solve the lead code problem to remove linked list elements in this problem we have been given the head of a linked list and an integer val and we've been asked to remove all the nodes of this linked list which have the value equal to the input val and we need to return the new head in the example provided we have the head pointing to the linked list and we have val equal to 6 and very quick to remove all the nodes where the value matches 6. each element of the linked list is represented by a list node each list node contains an integer val and the reference to the next node in the linked list which is next so let's understand what removing a linked list node involves so for example i have my linked list with the head pointing to the first element one has a reference to the next element 2 and 2 has a reference to the next element 3. let's say i want to delete the element 2. what i need to do in this case is i would need to make the reference next inside of the head node point to the node three instead of the node two so that would mean hit dot next equal to head dot net dot next since hit points to node one head dot next points node two and hit.next.next two and hit.next.next two and hit.next.next points to node 3. by doing this we're saying change the node 1 such that make its reference point to node 3 instead of node 2. in java we have garbage collection which takes care of de-allocating any unused memory so in de-allocating any unused memory so in de-allocating any unused memory so in this case the note 2 will be eligible for coverage collection and that effectively deletes the node now let's look at how we can delete all the nodes from a linked list whose value matches well now to delete all the elements from a linked list matching a value we need to traverse the linked list from the start till the end we just saw that if we want to delete a node we need to make its previous node point to its next node so that it skips over the node we want to delete but what if our linked list is such that the node we want to delete is at the start of the linked list to overcome this problem we can delete all the nodes at the start of the linked list which match our given value we can then traverse the linked list and delete the remaining matching nodes from it to delete the nodes from the start which match we will simply check if the heads value matches well and if it does all we need to do is make head point to the next node by saying head equal to head.next we will do this in a while head.next we will do this in a while head.next we will do this in a while loop till all the elements at the start of the node matching the valve have been removed after removing the first matching node we have moved our head to the next node we do the check again and see that it matches as well so we move head to the next node which is one now hit points to the first node one and it doesn't match our value since we need to return the head of this linked list we cannot move it else we will lose track of the first node so we will define a temporary reference called current will initially point to the same node pointed by head we will now iterate through this linked list using this temporary current node and check the value of the next node if the next node's value matches our val will make current.next point to the node after the current.next point to the node after the current.next point to the node after the next node doing this the node 1 will now point to node 2 instead of the node with the value 6. we will again check the value of the next node from the current node to see if it matches our val in this case it doesn't so we will move current node to the next node by doing current equal to current.next from the current equal to current.next from the current equal to current.next from the new current node we will again check the value of the next node to see if it matches our input val 6. in this case it doesn't so we will simply move current to the next node checking the value of the next node from the current node we can see that the next node matches our input valve 6 which means we need to delete this node we will execute current.next equal to current.next equal to current.next equal to current.next.next which means the node 3 current.next.next which means the node 3 current.next.next which means the node 3 will now point to the null effectively deleting the node matching the value 6. this point we have finished iterating through the entire list and we can return the head of the list now let's implement our solution using an alternative approach and then a recursive approach we'll start iterating the linked list and remove all the nodes which match the val from the beginning of the linked list to handle the scenario where all the elements of the linked list have the same value as the val we need to make sure that the head is not null after we have removed all the matching nodes so far we will create a temporary reference called current and initialize it to head and use it to iterate through the rest of the linked list we will iterate through the linked list till the next element is not null and we will check if the next element's value matches val matches then we will delete the next node from the linked list else we will move the temporary reference current to point to the next node we will return the head of this linked list i have added a few different test cases in the first test case the number we want to delete occurs at the start middle and end of the linked list now let's implement our recursive version of this algorithm in the recursive approach we will call our method recursively we first check if the head is null and return null if it is we will try and remove all the elements from the beginning of the linked list which match our input val and if all the elements had matched that means we would be left with the null and we will return it i'll use this example here to explain the recursive approach the above while loop will make sure that the matching value 6 is deleted from the start of the linked list now we know for sure that the first element of the linked list will not be matching the input val 6 so we will have to check the remaining part of the linked list for any matching values we will call our method recursively and pass it the remaining part of the linked list by calling head.next as the first by calling head.next as the first by calling head.next as the first parameter and assign the return of this call to the head dot next itself the first time we call our method recursively with the sub list the first element of the sub list is 2 and since it doesn't match our well the while loop will not execute and it will then recursively call our method with the sublist starting at number 6. the while loop will now delete this head element of the sub list because it matches the input well we will again recursively call the remaining part of the sub list recursively and this way we will be able to remove all the matching values recursively and finally we will return the head of the linked list these were the two algorithms where we were able to delete nodes from a linked list matching a given value in a single pass i hope you found this video useful please remember to subscribe and like and share this video thank you
Remove Linked List Elements
remove-linked-list-elements
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_. **Example 1:** **Input:** head = \[1,2,6,3,4,5,6\], val = 6 **Output:** \[1,2,3,4,5\] **Example 2:** **Input:** head = \[\], val = 1 **Output:** \[\] **Example 3:** **Input:** head = \[7,7,7,7\], val = 7 **Output:** \[\] **Constraints:** * The number of nodes in the list is in the range `[0, 104]`. * `1 <= Node.val <= 50` * `0 <= val <= 50`
null
Linked List,Recursion
Easy
27,237,2216
779
hello everyone welcome back here is vamson with another live coding challenge so today we are going to tackle a popular problem from uh L code the key symbol in grammar so let's dive into it uh so the task is to build a table of n rows and we started by writing zero in the first row now in every subsequent row we replace each occurrence of zero with uh 01 and each occurrence of one with one zero so given two integer and key we are uh to return the uh key uh symbol in uh the end row of the table so for instance if our n is free so n uh is free and yeah let's say key will be uh four so uh the first row will be as F so first row will be just uh zero and then second row will be 0 one and the third row will be 0 1 so yeah we're replacing zero and one zero so uh if uh n is three key is 4 what should be the output will be uh zero so we output uh zero so now uh yeah as we probably understand the task better with example let's talk about the logic uh for solving this problem so we can observe a recursive pattern based on the properties of the uh generated sequence uh which will help us solve the problem efficiently so uh we can solve it using uh with two different approaches so we will start with recursive approach uh so which is uh quite interesting and we will create a method named uh yeah so implement the method a key grammar inside a class called uh solution so yeah let's dive into implementation I will also write some comments so base case uh so if n is one return zero and find the length of the N minus one row so Len will be two to the power of nus 2 and now determine the half in which key falls so if key less than length uh if key is in first half symbol is same as symbol at Key and row and return self key grammar n minus one and key else if key is in second half symbol opposite to symbol at key length and minus one row so return 1 minus uh yeah 1 minus our key programmer n minus one key length Okay so this is uh the first approach using uh recursion yeah let's run it just to see if it's working for test cases so yeah all good so yeah all working uh perfectly so now uh in this method we have a base case uh if n is uh one we return simply zero otherwise we calculate the length of the nth uh row and check if key is in the first half or the second half of the row and make recursive call accordingly until we get uh the uh solution so uh let's uh submit it for unnus cases to yeah verify it's working so yeah all working perfectly um bitting 97% with respect to memory and bitting 97% with respect to memory and bitting 97% with respect to memory and also run time uh yeah uh 47 milliseconds between 64 for so uh more or less uh runtimes are consistent but I think I have a best runtime of about 302 milliseconds so yeah uh so let's clean it up and now the second solution so uh second solution is quite uh interesting it's a bit count approach so now let's move uh on more uh let's say optimize and concise approach using bitwise operation so let's implement it will be return bin uh key minus one count one mod two so yeah just one line of code uh so in this approach we convert uh key minus one to its binary representation count the number of one bits and return the parity even or old nature of the account so uh it's really uh quite tricky and interesting approach uh based on mathematical properties of yeah this task so yeah as you can see everything work perfectly so let's submit for unnus cases and really concise one and yeah it took 44 milliseconds beting 97 with respect to memory uh let's uh rerun it to double check so yeah probably uh differences between Rand and because basically uh both solution uh yeah should have quite uh similar yeah so they have quite similar run time but uh basically the second should be uh faster uh if we uh look at for example uh bigger uh numbers because uh it doesn't use call stack so basically with respect to memory uh it's constant memory time uh and in first approach we had uh yeah and uh complexity so everything uh work uh perfect uh and yeah so we have successfully solve key symbol in grammar problem using two different approach in Pyon and uh yeah the recursive approach help us understand the problem better and the bitc count approach provide a more uh efficient uh and tricky uh solution that uh it's yeah really good to know and have in your uh programming uh toolkit uh I will also provide uh implementation in other languages like rust go uh C++ and more in the rust go uh C++ and more in the rust go uh C++ and more in the description below and make sure to like share and subscribe to the channel for more coding Adventure tutorial challenges uh machine learning uh yeah and much more and drop any question or suggestion in the comment section below and uh if you like it uh please give it a thumbs up and most importantly keep practicing stay motivated happy coding and see you next time
K-th Symbol in Grammar
max-chunks-to-make-sorted-ii
We build a table of `n` rows (**1-indexed**). We start by writing `0` in the `1st` row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`. * For example, for `n = 3`, the `1st` row is `0`, the `2nd` row is `01`, and the `3rd` row is `0110`. Given two integer `n` and `k`, return the `kth` (**1-indexed**) symbol in the `nth` row of a table of `n` rows. **Example 1:** **Input:** n = 1, k = 1 **Output:** 0 **Explanation:** row 1: 0 **Example 2:** **Input:** n = 2, k = 1 **Output:** 0 **Explanation:** row 1: 0 row 2: 01 **Example 3:** **Input:** n = 2, k = 2 **Output:** 1 **Explanation:** row 1: 0 row 2: 01 **Constraints:** * `1 <= n <= 30` * `1 <= k <= 2n - 1`
Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk.
Array,Stack,Greedy,Sorting,Monotonic Stack
Hard
780
1,447
That's Naresh Lootkhor Problem 147 Celebration More Than This List Of All Celebration Will Win 211 To 239 Meter Is Equal To The Can We Do Subscribe Like Share And Only One 2012 Is Not Only Possible Subscribe To Fuel Surcharge Meaning 154 Tomorrow Morning Have Similar To What We Can Do We Need to Front Rock Fractions of All the Numbers and Also Celebrate Using Suvvi Divide and Rule and [ Divide and Rule and [ Divide and Rule and Subscribe Now that Aishwarya to you that and will render following from pointer in the basically better is Ayurveda University Will Start From One And Will Go Till Its President And Chief Barauniyan And Share Plus Veer V Subscribe 2002 NGES 9 Plus Ep 209 Mean That You Get The First Chief Come Bauji Chieftain Necessary Natural Acid Which Will Return Amazon Do Subscribe Divide divide be that hybrid device jcd plus slabs operation them even a little directly subscribe and [ operation them even a little directly subscribe and [ operation them even a little directly subscribe and a man will return naked the research of set a family in f**** time the chief a family in f**** time the chief a family in f**** time the chief now half the fuel in this disorganized manner hence removed Take a that Phelps retired chief of being always smart MP3 the first time to temple that surgical strike to run for the tasks in the floor possibility defiance styris a solution setting on off's a solution setting on off's a solution setting on off's subscribed song and observation his wife in square complexity Vikas Vihar Running To Do The Time Complexity Of Solution To You And Thank You 21 You
Simplified Fractions
jump-game-iv
Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**. **Example 1:** **Input:** n = 2 **Output:** \[ "1/2 "\] **Explanation:** "1/2 " is the only unique fraction with a denominator less-than-or-equal-to 2. **Example 2:** **Input:** n = 3 **Output:** \[ "1/2 ", "1/3 ", "2/3 "\] **Example 3:** **Input:** n = 4 **Output:** \[ "1/2 ", "1/3 ", "1/4 ", "2/3 ", "3/4 "\] **Explanation:** "2/4 " is not a simplified fraction because it can be simplified to "1/2 ". **Constraints:** * `1 <= n <= 100`
Build a graph of n nodes where nodes are the indices of the array and edges for node i are nodes i+1, i-1, j where arr[i] == arr[j]. Start bfs from node 0 and keep distance. The answer is the distance when you reach node n-1.
Array,Hash Table,Breadth-First Search
Hard
2001
77
okay today's question is question 77 of the leap code combinations given two integers n and k return all possible solutions or return all possible combinations of k numbers out of the range 1 to n you may return the answer in any order so we have n which is equal to four here n being the range so it's going to be one to four k is the number with which the arrays can max out at so it's two here so we've got two four three four and all of these are unique combinations so there aren't any duplicates within here so we need to take that into consideration okay so what this question is asking for a result array which contains all of the different combinations within the range of one to n so here we have the first example where n is equal to four we have all of the ranges here one to four it's asking for all possible solutions so that suggests that we'll be using a recursive solution if we first take one and we have some kind of current array which is going to store our potential solutions that we can later push into res so if we take one we've got two three four left at this point in time current is equal to one because we've taken that and we've pushed it into current then if we take two we have three and four left current at this position is one two now if we take three we'll have some if conditional logic which checks so we're going to prune this recursive tree and by pruning i mean we're going to stop it at this point because current dot length is equal to k dot length so when current dot length is equal to k.length we do not search any equal to k.length we do not search any equal to k.length we do not search any further because any values beyond this point will not be able to go into results so at this point we're going to push the current one and two into res and then we're going to backtrack we're going to go back to this level we're going to move across so we're going to check in the array if there are any other possible solutions we can choose 3 here so we choose three we only have four left current at this position is from here one and three from here again we can't go any further because this will not be a valid solution so we just push current into results so one and three is pushed into here now let me just remove this current because it's in the way of the tree now we go back we backtrack we go back to this level we find four we do the same with four so we take four here there is nothing left at this level so current at this point is one and four so we push that into the result array and then we backtrack so we backtrack from here we reach this level we realize there's no further positions to move across to so we backtrack to this level we look to see if there are any other possible solutions we could go to we have two so we take two we have three and four left we are not adding one we're doing this in order so that we don't have any duplicates so at this point current is going to be two we take three so we take three there's only four left and at this position current is equal to two three we can't go any further because it's out of range we push current two and three into the result array we backtrack we go back to this level we take four there is nothing left and current at this position is two four so we can't go any further so we add that into results and then we backtrack we go back to this level can't go any further go back to this level we have three so we take three we only have four left current at this level is three we take four there's nothing left current at this position is three four we can't go any further so we backtrack but before we backtrack we add three and four into the array so we backtrack to this level we see this four we check for there's nothing after it so it's not a potential solution because we need of lengths two where k is equal to 2 and 4 will not provide us with that so now all we need to do is just return res so time and space complexity time is k which is the maximum amount times m factorial over n minus k factorial in space is o n factorial over n minus k factorial okay so let's jump into the solution so we start off with an empty result right we create our recursive function we're going to call it dfs because that's essentially what we're doing with backtracking we're going to pass in index and current so dfs is going to be called with the index starting at 1 because we want to in range of 1 to n and current is going to be an empty array and at the end we are going to be returning result so in this backtracking solution we need a base case and this is if current.length current.length current.length is equal to k then we can push into result current and here we've created a copy of current because we're going to be manipulating current further down in this function so we need to loop through the values of n and it needs to be less than or equal to n because we are starting at one and we're going up to and including n so one to four we want to include for and in here we just want to push i into current then we need to recurse so dfs i plus one because we want the next position housing current and then lastly we need to backtrack to find all possible solutions so current.pop let's give that a go okay great
Combinations
combinations
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`. You may return the answer in **any order**. **Example 1:** **Input:** n = 4, k = 2 **Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\] **Explanation:** There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination. **Example 2:** **Input:** n = 1, k = 1 **Output:** \[\[1\]\] **Explanation:** There is 1 choose 1 = 1 total combination. **Constraints:** * `1 <= n <= 20` * `1 <= k <= n`
null
Backtracking
Medium
39,46
11
hello welcome back to oh elite code with hatchery benji now you may be wondering since last episode ben has your screen time gone down and the answer is no unfortunate listen mate i've been watching teenage ninja mutant turtles and spiderman this 1994 mate i've got to stop myself it's actually clinical like this is bad it's bad but uh we're back on uh the old elite code uh and i'm here instructor banjo so today what we're looking at well we're looking at this container with most water problem so what's happening right we've got an array and each uh little well each index of the array is the position of our bar and we can contain water between two of these bars so like in the diagram so between the two red bars obviously the maximum amount of water you can hold is the base or the distance between these two and in this case it's just the right index minus the left index so if you imagine we're looking at this one and this one this is index zero one two three four five six seven eight so eight minus zero is eight so that means our base would be eight if we were looking at these two but because we're looking at this one it's eight minus one so this is seven times then that minimum of the height of the two bars we're looking at right so that's the maximum amount of water we can hold in a container that's using these two bars and this just happens to be the solution so let's think about this problem we're trying to find the most amount of water we can contain using these random bars that we are given so one way we could do this is we could literally just do this brute force approach so we take our first bar and we find how much water we can contain between it and the second bar then what we do is we look at the first bar and the third bar then the first and the fourth and each time we just check is this greater than the biggest area we've seen so far and then once we've compared one with every single bar we start at a two and compare with every single bar and then three and compare with every part so why don't we just try coding this so what we want to do is we want to create an integer and we're going to call this max area so initially we want our area to be nothing right because we're never going to have a negative area but somehow we could have zero so we want to make sure we start at the lowest area so we're not making something up you know if we have in max area equals 10 and that's actually above any area we can find if we have really small bars and they're close together then we're going to return at the very end into max area which is 10 but we can't actually hold that much water so that's just a false result so we want to start the lowest area we could possibly have which is zero once we've got that we just have to create a couple for loops so when i say four in i equals zero and then i is less than height we are length right because we want to go through our array and our array just happens to be called height which is a little confusing but it's uh it's just an array of the heights of the bars at each index in the array so uh while it's less than the height dot length we want to increment it by one then we also want to create another for loop inside this with maybe a different pointer so to speak and we'll set that equal to zero uh as you know we won't we'll set that to equal i plus one right so if we're looking at the first uh bar with everything else we want to increase j we want to start j of the second bar we don't want to start out i because if we're doing what how much water can we contain between something and itself nothing so we want to start at one uh beyond i and then loop up until the very end so we'll also say while j is less than height also if you're noticing my noodly fingers i have tried to swap my keyboard layout and uh let me tell you i did an english essay and my teammates would not very happy made the amount of things i spell i sorry listen i elky no my yeah my l key has become s key and i've i had to spell all it was just it's just after right so now that we've looped through uh for j so we've gone through um what do we check it so we're checking if max area is ever greater than our current max area so the first time it's zero so pretty much everything is going to be bigger than zero but each time we want to set max area to something new if it happens to be bigger than the max area so what we can do is we can actually import math.max so this is going to take import math.max so this is going to take import math.max so this is going to take two parameters and it's going to return the larger of the two so we just have to say we want to take the maximum of our current max area and now this is where it gets kind of funky i want to take the minimum of height at i and height j at j and once we've got that minimum we want to actually multiply it by r minus l right hopefully that's all good we got our brackets nice and closed so if this is a bit confusing what's going on here let's start in the middle so we have our minimum of height at i and height at j so what is that what's going on here so let's say in our example that this is i so we've started here and we've looked at this one looked at this and we've gotten to the end well what is the amount of water we can contain well it's the base times the height right that's how we get the area so the base in this instance uh like we saw before is this index minus this index right which gives us the length of the bottom so this is index eight because we have um zero one two three four five six seven eight right so this is index a even though we have nine items in our array and then this is index one so eight minus one is seven so we have a base of seven then we wanna multiply that well hold on so this base of seven is this right minus l so that's how we get right this index minus left um now sorry i'm doing right minus left but that's definitely not right we want j minus i because j is always going to be above i and this is basically the right point right so this is the right index minus the left index or sorry i totally messed that up j minus i sorry if that was confusing and then we want to multiply that by some height but we want to multiply it by the minimum of the two heights we're looking at so if we multiplied it by this height we'd actually start getting water that overflows over this bar so we cut that doesn't work we need to multiply the base by the minimum of these two heights right because our water doesn't overflow this bar so we do this height which is the minimum of height of i and height of j times j minus i which is our base and then if this is bigger than our max then math.max is going to take this and then math.max is going to take this and then math.max is going to take this and it's going to set max area to it otherwise if max area is bigger so say we've got this as our area and then we go to here and compare this one well this one's closer and also a smaller height so we'll have less water so we don't want to override the max area so that's what this map math.max is area so that's what this map math.max is area so that's what this map math.max is doing so after this for loop and this other for loop we're looking at every single bar with every single bar at the very end we just want to return max area because at the very end this will be the maximum area we found so if we run this you'll see we're accepted and then if we give it a quick old submit so totally ignoring the other solutions you'll see that we are faster than 16 of java submissions but 16 that's we can do better right this is right corker but it's not that bad we can do better so now let's take a look at some proper explanations because that was a little quick certainly confused me uh i probably sounded confused so say we've got this example this is our array index 0 up to index 7 we've got the heights of the bars so index zero we've got our height one index one we've got a height ten and then three all the way to our last bar that has a height of six at index seven so what we did previously was we just looked at this bar with this bar and then with this bar and just brute force went in looking at every bar and finding the area each time and if it was bigger than the biggest area we had seen well let's make biggest area equal to what we've just found but that might not be the most efficient of strategies right so that would be o of n squared time and by that i mean in the worst case way in a way not exactly because we don't look at every item for every item but for each bar we want to look at every single bar so we want we have n times n time right so this is the n squared but that's not desirable so what we can do is uh we can find something that runs in linear time so we just have to scan each bar once but how do we do that well let's check it so this is just the same example what we can do is we can start and this is where my little cheeky left right came from so we start at the left but we also start at the far right so we'd create a pointer called l and a pointer called right and right is just the furthest rightmost index so in this case it's seven and left is totally the opposite so the far left index in this case zero um and it'll always be zero but the right might vary if we have more elements so what we want to do is we want to find this area right so it's going to be something like this because the water would overflow if we do anything higher than that it would overflow over this bar that has height 1. so now if we moved right one to the left our water level the area of water would only go down because our base is gonna shrink right it's gonna get smaller and our height is still bound by this small bar which is only height one so if we move left we're only going to get smaller so there's no point doing that and then actually even in the worst case say we had a little bar here that was 0.5 we'd actually decrease 0.5 we'd actually decrease 0.5 we'd actually decrease the amount of water by a lot not just the base but also by the height so we don't want to move the higher of the two bars right left and right what we do want to do is we want to move the smaller of the two so if left is smaller than right but not the index the value at the array so if 1 is less than 6 which it is in this case then we actually want to update l to be l plus 1 so we'll update that and move it to the right so then l comes here and we're looking at this and this is the grand daddy of bars it's height 10. so then we'll set max array if this is greater than what we had seen previously then next what we want to do is notice we have the same kind of situation if we start moving this one on the right over and over we're never going to get um something larger than this right the only way we could get something larger is if we move the smaller of the two bars so let's move this one to up to here and then up to here and notice this is actually probably going to be the greatest area but that's the idea so the idea is let's look at the left look at the right and only move in one of the bars if it's smaller than the other so move the smaller of the two in so i've got this random slate here but hopefully that makes sense so start the left start at the right and then whichever one smaller move it in one all right and then at the very end we will return the max area that we found and luckily we don't need to return the index of which bars create the biggest area so we don't need to keep track of that so we literally can just go through even if we find it right at the beginning uh that doesn't matter so let's check this updated idea so how does it work well we similarly want a variable called max area and we want that to be initialized to the smallest area we find of water which is zero because we can't have a negative volume of water that is uh i don't know what that is impossible then we also want an int l so this is going to be our left most uh index and then similarly we want an r and this is going to be the height dot length so that length of our array remember if you saw the problem last time we don't actually want height we want height minus one now that's because if our height was length three we'd have a zero index one two that we could access so if we did r equals height.length we'd actually get equals height.length we'd actually get equals height.length we'd actually get three all right because zero one two that's three elements but if we access the third we're off the diving board and like this problem is dealing with water we would we'd be drowning in it right so next up what we doing well we got a while loop right because we want to make sure that left and right have not crossed each other as soon as that happens we're starting to look at elements that we've already looked at and that is just a total waste of time so while le left is less than r what we're going to do is want to set max area to equal and this is very similar uh to what we're doing previously so if uh we want to find the maximum of the current max area it's very max area not area max and the minimum math.min and the minimum math.min and the minimum math.min of the height at i but not i this time so it's a bit confusing the height at l and also let's write that correctly and height at r and then what we want to do is we want to multiply all of that by our minus l so this is our base right um but then this is the additional check we need so that we're not checking for every element we want to say if the height at left right that's less than the height of right then what do we want to do well height at left is less than the height of right so let's move the left up one so we'll just do l plus simple as that so our else case takes care of the fact that uh left and right might be equal and if they're equal doesn't matter which one we move inwards so in every other case if height uh at l is not strictly less than height to r then let's move r to the right so we just do our plus and then at the very end we exit our while loop and we just return max area so this just like the other uh way of solving this problem oh sorry i did r plus we want to move right one to the left so we want to actually subtract one we don't want to add one otherwise we're going way off our array off the diving board and uh drowning so if we run this boy you'll see that i've got this error with height and uh some other little cheeky bracket error but you know what that's the keyboard in it uh if what's happened there then beautiful lads right we're on that boy oh wait i forgot to hide your length oh it's just a shambles oh wait somehow i've deleted oh no i've done that weird insert thing haven't i okay there we go right run that boy and there we go we're accepted and we'll do a quick submit so last time i think we were faster than 16 of submissions this time we're faster than 94.45 that means we're faster than 94.45 that means we're faster than 94.45 that means we are in the top six percent of mines memory usage wouldn't worry about that one it's all about speed and so there we go happy days we've got elite code number 11 container with the most water sorted it's easy for us uh hopefully that did help uh this was a bit of a waffley one so i apologize for that's uh yeah it's just one of them isn't it but uh hopefully that did help uh if there's anything that i can clear up leave a comment any other problems you need uh need a little uh little titillation with let me know anyway cheers and bye you
Container With Most Water
container-with-most-water
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`. Find two lines that together with the x-axis form a container, such that the container contains the most water. Return _the maximum amount of water a container can store_. **Notice** that you may not slant the container. **Example 1:** **Input:** height = \[1,8,6,2,5,4,8,3,7\] **Output:** 49 **Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49. **Example 2:** **Input:** height = \[1,1\] **Output:** 1 **Constraints:** * `n == height.length` * `2 <= n <= 105` * `0 <= height[i] <= 104`
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle. Area = length of shorter vertical line * distance between lines We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
Array,Two Pointers,Greedy
Medium
42
63
welcome back friends today we are going to solve lead code problem 63 unique paths 2. so uh here a robot is given uh in the starting position and robot wants to uh you know reach to this ending position given by star right and there can be obstacles like this is representing uh in red color so this is the obstacle so robot cannot go through this cell so let's just quickly you know read this description a robot is located at the top left corner of m by n grid marked starred in the diagram below the robot can only move either down or right at any point in time the robot is trying to reach the bottom right corner of the grid marked in the finish now consider if some obstacles are added to the grids how many unique paths would there be an obstacle is space marked as one so as you can see this is the obstacle and if you look at the obstacle grid which is the matrix that is given to us you can see 0 here so this is 0 then this is 0 1 0 so they have marked one for obstacle here and the last one is 0 right so 0 means it is available for the robot to move so robot can move in like this or it can move like this basically because zero is available but robert can go like this and this right because it is obstacle or robot cannot go like from here it cannot go like this because this is obstacle in the middle right so that is what the problem says so um you know we are let's just take this example over here so i am taking like two examples to explain you what are the steps how we are going to build the solution so we are going to use dynamic programming approach to uh gradually formulate a solution so the we will know how many paths robot has actually unique paths to reach from the start to the end right so uh so as you can see the robot is standing here so here is our robot start standing this is the starting and this is the ending point right where robot want to reach so we will be first we will do m by n empty m by n dp array right this is a empty in the beginning which is just like zero basically empty right so we will populate that dp array uh gradually so how we are going to populate this dpra so i will explain you so we know that robot can only go on the right side or on the downside right downwards so these are the only two directions which are possible for robot to move so if robot is standing here in the first row there is only one way to reach to this cell right where it is standing because it cannot go from anywhere like it is already you can just put one here because there is only one way to reach here so if robot want to go to this cell right then there is only one where robot can go by just going on to right side so we will just write one here right in the dp array and if robot want to reach this cell then it will again walk on the right side right like this and there is only one way to reach there because of that right because we only have two ways of directions either it can go right or it can go downwards right so we are done we have filled the first row now we will look into first column right so now robert can go downward to reach to this cell so it is only there is only one way to reach to this cell and if robot is standing here and it want to reach to this cell it can only go downwards right to reach to this cell so there is again only one way to reach there right it can just go downwards so now we have filled uh like the first row and the first column we have filled all the ones right because there is only one way to reach to those cells now let me change the color so uh now this is the obstacle which is given to us right so obstacle means we will be having only zero way to go there right you cannot go because it's obstacle now what we are going to do is how many ways we can reach to any of these remaining cells is you have to find the diagonally connected cells like these are the two diagonally connected cells for this cell right this is the cell that we are looking at and these two are diagonally connected cells so you have to add these cells so one plus zero you will add and you get one here right so similarly if you are looking at this cell right this cell you are looking so you have to add this diagonally connected cells so these two are diagonally connected cells for this cell so this is zero plus one is one you will add here and for this cell last cell you will add these two cells right these are two diagonally connected cells for the last cell this one plus one you will add two here so this is the minimum wage that like unique parts basically that you the robot can take to reach to the final destination so you have to return to here right so that's why when you look at the answer you will get to here right and you can also look in this uh i will just highlight the path for you so the only two ways robot can take to reach is this one right this is one way and robot can take other way as this is another way so there are only two possible ways to reach to the ending cell right so now we have already seen one example so now let's say instead of here the uh the like obstacle is on this cell right obstacle is placed here so ah you know as in the beginning we will just populate this one right this one uh first row we will populate with one and first column we will again populate with one right because there is only one way to reach here now when we are reaching like this cell we will calculate this one plus one so we get this two then we will calculate uh here we will get zero right because this is obstacle so we will have to put zero we cannot reach to this cell now to reach to this cell we have to consider the two diagonally connected cells to plus one is equal to 3 so we have 3 here and then we have to take these two diagonally connected cells right these two cells we have to consider to calculate this so 0 plus 3 is equal to 3 so in this case you will return three as the unique paths that robot can take to reach from source to destination and i will just quickly show you what those paths are so robot can start from here it can go here then it can go here this is one path right then uh this one is uh the another path will be just robot will go downward like this and it will go on the right side so this is another path too and the third path will be robot will start like this from here it will go here and from here it will again come downwards and then again go right so these are the three unique paths that we have to written as the answer right so this is how we gradually build the dynamic array here dp array and then the last cell value we have to return as our answer right so one other thing i want to also mention is if this if for example if this uh obstacle right it if obstacle is in this cell right let's say obstacle is in this cell where which i am highlighting here if the obstacle is here then in that case our dp array will what we will do is when we are filling our first row right so let's just draw the matrix quickly so here one as we will put but now this one is the obstacle let's say then we have to put zero so once we have any obstacle in any of the cells then it means that you can never reach any of the further cells right you will always have to put 0 here because you cannot go from that through that cell basically and same thing applies to the column also if you have obstacle let's say in this cell you have obstacle then if you put you have to put 0 here but once you put 0 here then you cannot go through this cell right so you will always have to put all the zeros here for all the columns for all the rows here basically right so that is one thing so let's just look quickly into the how the implementation works here so as you can see you know first i just have this total path function and i am passing the obstacle grid that is given to us and i am calling it as a matrix here i am getting the uh m as a row and n as a columns and i am creating a dpi here right with the same dpr is has the same uh length and width as the obstacle grid right same m by n right and now what we will do is first we will create a variable called as obstacle in way right and we will start like first we want to populate this first row right so we will always check if a matrix of i j is equal to 0 matrix of i j means we are checking the cells in the first row basically and there should not be any obstacle in the way right because if obstacle is in the way then we cannot go there basically so if there is no obstacle in the way we will just populate dpi 0 is equal to 1 for example this is 1 then this is 1 like that right for that first row and if there is some obstacle in the way or if the matrix i j is not equal to 0 right then we will have to populate i zero is equal to zero right so in case of obstacle we will populate i zero is zero here on the first row and we will just put this obstacle in a way is equal to true so always you know for the remaining cells in the first human remaining columns for the first row we will have to put a 0 once we have any obstacle any cell we find in the first row the remaining columns will always be zero for the first row because we cannot go through the obstacle so same logic we have applied in when we are doing like if robot is going downwards right so in the first column it is moving so that's what we will just say obstacle in a way is false in the beginning and we will check if 0 comma j is equal to 0 and there is no obstacle we will populate that as a 1 right so 1 like that but if there is any obstacle in the way we will just say dp of zero comma j is zero and obstacle in way is equal to true so for example if obstacle is here right let's say this is this cell is obstacle then we will put a zero here but now we have to go put zero everywhere else like 0 like this for all the uh remaining rows for that first column basically so that's what we are doing here right so i explained you already i think in details uh so now once we so now at this time we already have filled our first row and first column so first row and first column we have already filled in this code so now we are going to handle the remaining cells right so remaining sales means if the matrix means if it's equal to 0 right means there is a space for moment we are just going to add the diagonally connected cells here in dp of i j basically is equal to dp of i minus 1 j and dp of i j minus 1 means these are two diagonally connected cells basically so for example if you are looking at these three you are adding these two cells these are two diagonally connected cells for this cell right so like this that's how you will populate the dpi and at the end you are going to just return the last cell and let's just so this is the code this is our first example that we discussed and second example right this first and second that we discussed here i took it here and this is another example so let's just run the code and make sure it is working fine so as you can see uh first is two and second is three right so in our example also first is two and second is 3 so it is giving us correct answer and the for third it is 1 so let's just quickly submit this code so the code is working and getting accepted so as so this is the way you can solve unique paths for robot and you can use the dynamic programming approach you can populate gradually populate the dp array and you have to just return the last cell of the dpi so um you know i often create videos related to lead code problem solutions with java j2e technologies and uh helpful uh you know interview related videos for java g2e technology and coding solutions so please subscribe to the channel it helps the channel to grow and reach to more people thanks for watching the video
Unique Paths II
unique-paths-ii
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle. Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The testcases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** 2 **Explanation:** There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right **Example 2:** **Input:** obstacleGrid = \[\[0,1\],\[0,0\]\] **Output:** 1 **Constraints:** * `m == obstacleGrid.length` * `n == obstacleGrid[i].length` * `1 <= m, n <= 100` * `obstacleGrid[i][j]` is `0` or `1`.
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] else obstacleGrid[i,j] = 0 You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem. if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j] else obstacleGrid[i,j] = 0
Array,Dynamic Programming,Matrix
Medium
62,1022
5
so this question has been asked by Amazon Cisco Adobe Google Apple Oracle Yahoo Microsoft Goldman Sachs Walmart the list goes on and on the question is longest parring subin hi guys uh welcome to day one of 100 days 100K placement challenge in which 100K people will be getting placement after this challenge so and what you know what's the lucky thing why we starting today is because it's third Jan and today is my birthday so yeah that's the reason I thought why not start this today at this auspicious day cool uh so we will see everything from the very brute force from the very Brute Force to actually recursive approach which will actually be good and you'll see everything intuition based and then we'll go on to the bottom up approach also then we'll go on to two pointers and in the end we'll also have a look at this thing you will see what is this and how it is required and again it has been asked by quite a lot of companies recently so if you have your interviews lined up be prepared it will be asked now the question just says that we are given a string s and that string s we have to WR the longest palindromic substring now substring is any part of the string which is continuous palindromic is something which reads same forward and backward so a part of string which reads same forward and backward will be a palindromic substring and such substring such palindromic substring I have to find which is longest possible so in this you obviously we'll see that b a because it is a substring it is continuous part of the string it is a substring it is palent room because it is reading same forward and backward it is reading same or to just find out if something is Parr or not you can just compare the end portions for example m a m right this is a palr this you can see it is reading same for example r a c e c a r a c and E in the middle so this is also a palent ro so you can just compare start and end and thus you can figure out if something is a palr or not and the same way you can see two same characters it will also be pairing up and that is also a palindrome so I have to just figure out the longest palindromic substring in this entire string now the first very Brute Force which comes in our mind is that okay by H you said that you want to find substrings longest palindromic substring so let's take the end substring so what I will do is I will figure out all the substrings now to figure out all the substrings what you do is if you are at I so you will try on for all the JS which are forward you are at I you'll try for all the JS so which means if I am at this I'll try for this J and so on and so forth and same if I am at this specific I then I'll try for this J so as to make a i J pair that IG pair is indicating that this is my specific substring now I'll try for all the possible substrings and I will then check if that substring is a palindrome or not and to check that I already showed you that we will just compare start and end if it is odd then you can skip the middle one but you'll just compare the start and end now to make all these substring it will take n Square time because it is n square substrings and to check for that specific one substring out of the N squ substrings I'll take again o of n time to just check okay I'll compare St start and that's how I will take over of end time to just check if that specific substring is a paranor or not and thus you will be getting a Time complexity of O of NQ which is okay but still it's high but let's quickly have a glance at The Brood Force code although in an interview you'll just speak up with this code you will not be coding a Brute Force code ever in an interview because interview is a very short span of time in which you have to get to the most optimal approach and have to code the most optimal approach so just BR Force says if the length is one simply return the string itself because it's just one string one character is always a palr if I have a it's a palr it's just simple a base case now it just says that I will initialize my maximum length because you know that length at least will be one gutter it will be at least one now I just went on and tried for all the substrings it is for trying for all the substrings and when I try for all the substrings I will just check okay if that is a palindrome then this is palindrome function we have made differently which will just go and check just comparing okay start and end it will just compare left and right now while left is less than right which means I'll just compare my left and right if it is not equal then simply is not a p room else I'll just simply keep on reducing which means left will keep on coming inside right will sorry it will keep on coming inside so basically left and right are at the extremes it will keep on coming inside and keep on checking the pointers so as to check if it is a palindrome or not if it is a palindrome and also I want to maximize my length so if I'm getting a new length a more length palr then I will update my answer with the maximum length and update the maximum string which is the longest length paror and that's how in O of n CU you can solve in root Force but can we optimize it yeah we can how it is just simple that while you are seeing that okay you already know that this cc is a palr right and then while you were Computing for the new substring which was a c e c a then you were again checking the entire thing right now I say bro if you know the middle part if it's a pent Dr then why can't you reuse that middle part in the bigger part right so I can just reuse something now when reusing your pre-computed values comes in then your pre-computed values comes in then your pre-computed values comes in then for sure first thing comes in your mind is the memorization which is actually the father of reusing stuff memorization is buil just so that you if you are just trying to compute that same thing again then you will just reuse that so I'll just use the same thing that okay I know that this portion is a p Dr so I can Mark okay true or false from I to J if it's a p room okay I marked it as a true so that in future when I am Computing let's say from this I to this J so for sure it will go inside which means it will go and do i++ it will go and do a j will go and do i++ it will go and do a j will go and do i++ it will go and do a j minus so now it will land onto a new inj but I will have pre computed this value so I will just simply return that okay it's a palr and that's how I can use memorization to solve this up that's so wonderful right so I have this lnr simple you know memor okay which means I will have to write a recursive code in which I have two pointers lnr and they will be moving inside if I actually encounter them as the same value so okay I have to write the recursive code as I have a base condition will look something like okay I have two pointers L and R right now base condition is very small condition what if I will have just one character that's a simple base condition right what if I have two characters that's also a base condition so as simple as that if your L is less than equal to R now in this again two conditions will be there L is equal to r l is more than sorry L is more than R now when L is more than R which means your pointers were earlier at L and R then it's surpassed now okay if it's surpassed which means okay you have valid okay because you are only moving and saying it's valid and then if you had surpassed this okay which means everything you were saying was actually valid and then you surpassed from here so I will say you moving okay you are at this location same okay it's valid if it has surpassed also it is valid again in this you can also modify this check as lnr if it is less and you just have a difference of one which means L and R are just like this adjacent to each other L is here R is here then also if they are same you can also return a one or this condition we can handle in our recursive code and then when it will actually go inside then L will surpass R and then I can also return a one okay that's a simple Bas condition recursive condition you also know I also know that simply uh and R will be the states of my DP and DP is just part okay recursion States and then I can memorize the same states to make a DP State uh so I'll just simply get and return L Comm R now comes the actual recursive cases now simple as we saw okay if both are same then I can move inside so if both are same which means s of l s of like which means this specific string character if both are same then I can go and move inside right so if this is same then you can try for the smaller sub problem which means L + 1 Rus 1 L + sub problem which means L + 1 Rus 1 L + sub problem which means L + 1 Rus 1 L + one R minus one but if it is not same bro L and R will never form a substring please return fals from here itself you cannot even go inside that's the reason if they are adjacent then it will be same so it will get onto this condition then L and R will increase so L will go here R will actually come here so it will become something like this and something like this it will simply return a one because it's valid because in this here condition we have make sure that if it is not valid I'm simply returning a false from here itself now it is a simple case which you saw base case memorization and recursive code which you have to replicate in the code L is less than L is more than equal to R simply return a one if your DP value is not equal to minus one simply return the DP value the simple two conditions which we saw that if your value if it is equal then simply return that value which means increasing L and decreasing R and for sure in ultimately if it is not which means if it is not equal then simply return the false itself from here itself and for sure the simple conditions we in the main function we just initialized our n then we initialize maximum length and starting index just to so okay I'm starting from this index itself and why starting index because ultimately remember in the answer sir you want the string not the length right so starting will say okay I'm starting from this index my DP will see okay this is the length starting from this index length is this I get the string so I simply um M set my DP by minus one you just can have it then I go on to all the substrings and I'll just call my solve function but byya for all the substrings you will call the solve function of n Square Times which means this because we saw that this is a n Square time operation then for all the substrings you're calling it is NH 4 this is way too much no bro it actually in cumulative will be o of n² why because for a state which was already computed as soon as you will try to compute the solve function my DP will itself return the value itself so this entire thing will be o of n² itself only and now I'll simply go and check if the maximum length which I have got because of this solving my i2j if that is more sorry uh the length which I have got if that is more than my maximum length then I can update my maximum length I'll update my maximum length and then I can also update my starting index because starting from this index for this as the maximum L I'm getting my answer now when this entire portion is done which means when you have for all the substrings you can simply return your substring starting from this index of this maximum length and that will be your answer simply the time and space will be of n Square because of you saw that the DP states are Ln R lnr are both I and JS I and J will simply going to n and also space will be same as that of the time because you are using a DP which is lnr now uh the same thing if you want to write if you want are much curious about bottom up the same thing exact same thing you'll see exact same thing I'm saying because in this you will see you are going on to all the substrings and then you are just going and checking that okay if the answer is valid simply increase the L and decrease the r exact same thing we can replicate that in our method three which is the bottom up approach I do exact same thing you'll see the code is exactly same is just that I'll go onto all of my substrings only when the characters are equal and also uh this is the base condition to handle this base condition and here I'm checking the same stuff that J + 1 IUS one if it is actually that J + 1 IUS one if it is actually that J + 1 IUS one if it is actually true then okay my substream portion is actually a proper pal ring substring and then I can simply go inside and update my maximum length with this current new length so I update my maximum length I update my starting index and that's how I can simply get things done I'll have my starting index I will have my length itself here and that's how I can simply return the same approach it's the same top down approach bottom approach more less same it's just that how to write that stuff in the bottom approach and the same time is space complexity nothing much now comes the interesting part can we again optimize this interviewer will ask you so you will see that okay you use the concept this was the window now you could have expanded that and made this now you remember okay I was using I can memorize this window right now what I'm saying is if you think if you just stop here and think okay this was the window at the first place right and you want to memorize this window okay what's the answer for this window now remember this it's a window right rather than expand this window that would be great right so what I'll do is I'll simply expand this window and if I can expand this window I know okay for this L Comm R if this was a palr I can just simply try to expand this window itself so as to get a new palr so basically what I can say is I'm starting with this e I'll try to expand this okay check my CNC it is same okay again try to expand this a and a great then try to expand it okay R and that's how I can simply just try expanding and that expanding itself I can just store okay what's the answer now the same way this you'll say this was for odd numbers okay the same way we actually go for even numbers that okay you will have L and R here although you remembered L and R were at the same location was the all Ln thing here Ln R will be at the different location as in okay L and then just to that is r and then you can just try expanding the same way if you are encountering the same character so one thing we got to know that okay for odd length I will have to try expanding saying L and R both at the same index and then for the even length lnr at the adjacent index so I will have to try for both of them but byya um how will we know that when to try for odd length when to try for even length uh by but I'll say because you know the string length no Noya because we want to find the substring basically if I'm at this index if this is my I so what how about like how I would know that it will it form a odd length substring or will it form a even length substring how would I know if I'm at this I Index right I will have to go onto all the places and then figure out yeah bro you are right so what you can do is you can try for both the things which means at this location you will try for expanding at this as considering this as a odd index which means you will try and place both your I andj or lnr at the same location and also for this exact same case you will try for placing your I at this adjust location so that at the same index I'm trying to imagine it as both I'll try to expand it as odd index palr and also even Index palr right so I'll do the same thing I'll do that for both of them for this specific index I'll try to expand this considering okay it's odd and I'll also try to expand this considering it is a even I'll do it for every index I'll try for every I for every index I'll try for both the ways both the possibilities and that's what simply we can do now in this again you will see again it will try for all the eyes which means for this I'm just simply expanding so for all the indexes I'm trying for expanding it up till the end so for all the indexes I'm trying to expand that so simply is for all the indexes n operation i n index is still it's O of n squ time then what is the benefit of it benefit is in the space now you would not have to store the space so you will see the space complexity is actually o one because now you don't have to store it because you are expanding from here itself so you already know okay shorter answer I have computed and then I'm going on to bigger answer if it's not if it is not even possible to go on expand then okay no worries go on to next don't store never store it because you're always expanding the palindrome itself now in this exact same stuff roughly same uh n if n is less than equal to one return the string now um this is actually a function inside this function so I'll show you that what it does but let's go on to your maximum string which will be your answer firstly I got the starting character itself in my maximum string now I'll go on and try for all the indexes now for all the indexes I will go and try to expand them now okay I'll just meant I'll just get the OD Len string and the even lens string now to get the odd lens string I'll say okay it's as you remembered for the odd lens string my L and R are just the index I for the even length string which I'm imagining to be a palen roome it will be I and I + one so again for the same I and I + one so again for the same I and I + one so again for the same stuff I'll try for the odd lens string I'll try to expand it from the Ln RS I and for the EV l I in I + 1 now what the and for the EV l I in I + 1 now what the and for the EV l I in I + 1 now what the expand function is doing it simply is trying to expand that from lnr so I have that left I have that right I just simply try expanding which means okay if left and right are same characters then try for left minus one and right + one so if the left is more and right + one so if the left is more and right + one so if the left is more than equal to zero right is less than n and if they are same characters then try for left minus one and right + one left for left minus one and right + one left for left minus one and right + one left minus one and right + one try to expand minus one and right + one try to expand minus one and right + one try to expand that and ultimately I will have my M expanded by this Loop considering they are both valid and also I've not reached the end of my string any portion left hand or right hand then I can simply return my substring starting from this with the length of this because I have my left I have my right I know that I'm expanding it is a valid it later on it will check if it's a valid or not so I know one thing okay I know that okay I'm expanding so I just simply know one thing I'm expanding so I can simply go and check okay left plus one with the length of this length which is right minus left minus one then ultimately um I'll just simply go and check okay what's the length what's the string which is which it returned and ultimately if my odd length is more than maximum length then update my maximum string as odd string if the even length is more than my maximum length then upate my even string and that's how I can update okay whatsoever string either odd or even is for the index of f just update that with the maximum string and ultimately return that maximum string itself thus you are only using your o of end time and no extra space is being used because you are expanding from every index you are expanding from and that's how you can simply solve this last is the managers algorithm now again you saw there were five there were four follow-ups for the five there were four follow-ups for the five there were four follow-ups for the ex in problem itself so it is not even expected to solve this in an interview and it is not even for the interview itself this is like legit entirely a very big around 30 minutes will be taken to explain this algorithm itself the only benefit of this algorithm is that you can solve this in O of in time and O fun space although for this as it is not interview specific it is way out of the approach orally the bound of the interviews so if you still want you can just to watch algorithms Made Easy this video they have a great animation for this corresponding video and you will get the values like understand that if you want to understand although Al it's not at all cool thank watching again bye-bye and uh thank you so much we will bye-bye and uh thank you so much we will bye-bye and uh thank you so much we will continuing this series in which my make sure you have to make sure do these questions for placements because these are the questions which are most frequently asked by companies and this is not being yes it's actually in front of f eyes in last 6 months it's very frequent so for sure it will be asked bye-bye
Longest Palindromic Substring
longest-palindromic-substring
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`. **Example 1:** **Input:** s = "babad " **Output:** "bab " **Explanation:** "aba " is also a valid answer. **Example 2:** **Input:** s = "cbbd " **Output:** "bb " **Constraints:** * `1 <= s.length <= 1000` * `s` consist of only digits and English letters.
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
String,Dynamic Programming
Medium
214,266,336,516,647
12
hello guys welcome back to techdos and in this video we will see the integer to Roman problem which is from lead code number 12 it is an implementation based problem which is frequently Asked in interviews particularly in Amazon so before looking at the problem statement I would like to announce about the tech dose DSA live training program where you will be guaranteed the understanding of Concepts and it will help you prepare for your upcoming interviews in just three months which will help you maximize your offer if you want to know more about the course then you can WhatsApp take those on this given number and you will get the details let us now look at the problem statement this is a very straightforward problem in which you are given a decimal number which you need to convert to a Roman number representation the Roman notations which are given are corresponding to 1 5 10 1500 500 and 1000 which are IV xlcdm okay so this is mentioned in the problem now any number can be represented in the format of the Roman number but there is a catch to it now let us understand can we easily do it by the given notations so let us start representing from the number starting with 1. so let's say you are representing a Roman notation for one and that will be just a single I and for 2 it will be two eyes right it will be two eyes for three it will be three eyes but what happens if you get a 4 for 4 it is not three eyes but it is an I followed by a v when you write in this manner that is if you write an I on to the left side of V then this means that to the value of V which is 5 you are subtracting the left hand side value which is 1 and this becomes 4. this is the usual meaning now for 5 you simply write V right and what happens for 6 again for 6 or you will see that you write V followed by an I right then for 7 you write v i for it you write v i and I that is triple I but for 9 you don't write V followed by four eyes but instead you will write I followed by NX the value of x is 10 in the notation and writing an i to the left of it means that subtract value 1 from 10 and this becomes 9. so this is the usual meaning okay so you will see that even though these notations are given you will require one less value from the actual notation that should be in multiple of 10 so we will understand this let us first write it for 5 you will need 4 and what will be the notation of 4 it will be IV okay and for 10 you will need 9. now the notation of 9 will be I followed by X so you will see that five if you want to represent 4 then you will have to convert this 5 to the lowest 10th multiple so this will go to this I right because the lowest 10th multiple of 5 is 1 and also the lowest 10th multiple of 10 which is lower than 10 is also 1 that is why you need an i before this X similarly what we can do is if you want to see the previous number to this like let's just forget about this one zero okay so what should be the previous number it should be 40 it is not 49 right because we have already taken care of all the numbers in between 1 and 10 so definitely between 40 and 50 it will be taken care of but what about 40 in order to do that what is the lower multiple of 50 I mean the lower 10th multiple of 50 it should be 10 so this will be represented as XL now for 100 the previous one will be 90 because it is a multiple of 10. now what is the lower tenth multiple of 100 Which is less than 100 it is 10 right so it should be written as XC and similarly for this 500 the previous number not just the previous number in once but you see it is in multiples of hundreds it was in multiples of tens that's why I took the previous number as 40. now the initial ones were just multiple of ones that's why the previous number of 5 was 4 and the previous number of 10 was 9 but then from 10 onwards 50 and 100 were multiples of tens so we took uh the previous number to be 40 and 90 but then starting with 500 you see that 100 200 300 400 and 500 is coming so the previous number can be taken to be 400 and this can be represented with a CD notation and all the numbers in between 400 and 500 will be taken care starting from 1 to 100 right and similarly so what was the lower 10th multiple like the lower hundreds multiple of this 500 it was 100 so we used C before this D in order to represent 400 and similarly the lower 100th multiple of this thousand Which is less than thousand is again hundred so we can represent 900 which is the previous number as CM right so we need all these notations in order to convert a decimal number to a Roman number and I hope you got the reasoning why because in order to represent 4 I cannot write this I 4 times okay this will be wrong so in order to get the correct representation from whatever the question mentions you have to derive all the other notations as well right so I hope you understood why do we need this so this is the representation this is the entire list which you will require one four five nine ten forty fifty ninety hundred four hundred five hundred nine hundred and thousand and all these white numbers can be derived from the teal numbers right okay all these white numbers can be derived from the given notations so I hope you understood step one now there is another step involved which is about if a decimal number is given how do we know how to break it and represent it in the Roman notation in order to understand that first we have to understand if a decimal number is given how do we break in our usual Decimal System notation right so we will break always break in the multiples of as high number as possible so this is the rule okay now in the base 10 number system like our decimal number system whatever we use generally if you are told to break 58 135 into parts and let's say the notations allowed are 1 10 hundred thousand and hundred thousand then how will you represent there can be multiple ways to represent it you can write it as fifty eight thousand one thirty five into one that means one is occurring fifty eight thousand one thirty five times this is one notation another notation can be 5813 multiplied by 10 plus 5 into 1 this is another notation but you will see that out of all these notations the most accurate will be according to whatever notations are allowed it will be 58 into 1000 plus 1 into 100 plus 3 into 10 plus 5 into 1 this will be the most accurate result which we want right and how did we arrive to this how can we arrive to this we can arrive to this by dividing this entire number starting from the highest number possible and moving towards the lowest number possible Right so let's see an example where I will be converting this into the most accurate result and then you will be able to understand so remember the rules always try dividing in multiples of the highest possible notation if it's not possible with the current multiple we will move to the next lower multiple right so let's try this out so the highest multiple is hundred thousand so now try dividing this 58135 with hundred thousand can this divided no it cannot divide it right so we will not take this and since this is not able to divide it because the number is lower than the divisor D here is 100 000 and the number n is 58 135. so D is larger than n so it will not be able to divide it now what we do is uh if it's not possible with the current multiple that is the current divisor then we will decrease the divisor and we will go to the next lower multiple right so it is thousand now you check if you divide this fifty eight thousand one thirty five with thousand how many times will it take so it will take 58 times right so you can write 58 into 1000. now you try out with the reduced number what is the reduced number so since you have already taken out 58 into 1000 so the reduced number will be only 135 so will this 135 be divisible by 1000 no it will not be divisible by 1000 so we will move to the lower number which is 100 now is this 135 greater than 100 yes so it can divide it and how it can divide it will be only one time you divide 135 by 100 it will be only one time so 1 in 200 and once you write it like this you have to reduce this number and this will become 35 right now the number is 35 again 35 is lower than 100 so we need to move to the next lower multiple which is 10 again this will take 3 times so 3 into 10 and again this will be reduced to 5 now 5 is lower than 10 so we move on to the lower number one will divide this five in five times so 5 into 1 and there is no lower number so we will stop and this will be the correct representation right so this will be the most accurate representation according to the given notation okay the notation might change according to the question but this is what we had assumed and this is how uh you can do it so this is the method by division and this is the fastest method but there is another method which uh you can do by using subtraction now how you can apply subtraction to this so let's say the initial number was 58135 now this number is lower than this hundred thousand so you will move on to the next number which is thousand now 58135 is greater than thousand so one instance of thousand can be included and this can be reduced to fifty seven thousand one thirty five now again this 57135 is larger than this 1000 so again one another instance of this can be taken and so this can be reduced to fifty six thousand one thirty five and you can keep on reducing this byte subtraction in 58 times and it will result to 135 but division you can see that you can do it in just a single step and this is much faster than your subtraction so it is always preferable to solve this problem by division but I will show you the subtraction method which is very intuitive to understand and once you understand the subtraction method I think division is very easy to apply as well okay so let's take an example of 2856 and try using our notation that is our Roman notations in order to convert this 200856 to a Roman number so I have already explained you how to derive this entire set of Roman notations from the given set in the problem right that was the first step now this is the second step once you have derived it and you also have the decimal number try moving from right to left okay so try to follow this formula of first trying out with a larger number so our pointer is here at M which denotes thousand now you check 2856 is it greater than equals 2000 yes it is so you can write an m in our answer so this is the Roman notation right the answer is a Roman notation so you write one time m and you subtract a thousand value from it and this will become one thousand eight hundred fifty six again you check it in a loop is this 1856 greater than this thousand yes it is so you write another M and you reduce it to 856 now is this 856 greater than equals two thousand no it is not so you will reduce this pointer to the next one which is the CM now cm is 900 now you check if 856 is greater than equals to 900 no it is not so you again move it to D okay so this is 500 is this 856 greater than equals to 500 yes it is so you can write a d here and you can subtract 500 from this and this will be 356 is this 356 greater than equals to D no so you move on to the previous value c d which is having a value of 400 356 is lower than 400 so you again move on to the previous value C is 100. now is this 356 larger than 100 yes it is so write a c here and subtract 100 value from this again 256 is larger than 100 greater than equals 200 so you write another C and reduce it to 156 and again you need to do it one more time and this will become 56 and you add another C now you see that a 100 is actually greater than this 56 is less than 100 right so you move on to the previous value LC which is 90. again 90 is greater so you move on to the previous value which is L it is 50. now 56 is greater than equals to 50. so you can add an L here and you can reduce it by subtracting 50 from returns and this will become 6. now 6 is less than 50 so you need to move to the previous value again 40 is la is larger than 6 move to the previous value again 10 is larger move to the previous value 9 is larger move to the previous value you see that 5 is actually less than this six right so 6 is greater than equals to 5. so you can write a v here and reduce this 6 and you have to subtract it with 5 so this becomes 1. okay now this 5 is actually larger than this one so you move on to the previous value 4 is larger than 1 you move on to the previous value and this is one so you can write an I here and reduce this one and this will become 1 minus 1 0 as soon as you reach to 0 whatever notation you got is the Roman notation right so this is a subtraction process okay and this is the simplest and the easiest one to understand once you are thorough with this you can try out yourself with the division method let us now look at the code in this code you can see that the decimal number is sent and the notation I have just hard coded the notation you can also do that but in the problem you will see that m d c l x v and I are given but once you have solved this problem I don't think you will fail to understand this how to do this right so you can easily do it you can hard code it anyway and I have also saved the corresponding value so you will see that this entire array is in decreasing order so that I will be parsing through it from left to right you see that I have taken a for Loop and the initial for Loop is the position pointer which starts from the left hand side and keeps moving to the right from the higher value to the lower value the inner while loop will actually do the subtraction okay we'll actually do the subtraction as long as the number is greater than equals to the current value okay the current notation value and as soon as it decreases below the notation value we will go on to the previous notation value right as I had explained in the dry run so this is the simple code again if you are doing division there will be no need to do a while loop here and you can simply solve this by division in order of one time you do not need to use a while loop you can just use a division with the divisor and a divided by D and you will get a number X and these many times you have to repeat the given notation and uh you can append the string by forming the Roman string these many times like x times so first I will recommend that you need to try this out with the subtraction method and once you are good with this you can try out the division method I hope you were able to understand this video and you enjoyed it if you want to get the best quality interview preparation then do consider joining the tech dose live training program if you like this video then please hit the like button and subscribe to our channel in order to watch more of this programming video see you guys in the next video thank you
Integer to Roman
integer-to-roman
Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. **Symbol** **Value** I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: * `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. * `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. * `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. Given an integer, convert it to a roman numeral. **Example 1:** **Input:** num = 3 **Output:** "III " **Explanation:** 3 is represented as 3 ones. **Example 2:** **Input:** num = 58 **Output:** "LVIII " **Explanation:** L = 50, V = 5, III = 3. **Example 3:** **Input:** num = 1994 **Output:** "MCMXCIV " **Explanation:** M = 1000, CM = 900, XC = 90 and IV = 4. **Constraints:** * `1 <= num <= 3999`
null
Hash Table,Math,String
Medium
13,273
1,603
Hello friends, welcome to our YouTube channel, so today we are going to do a question of late code which is easy to design parking system, in this we have to design the parking system, okay it is very simple, people do not have to do anything much in this. Special okay so what design here you are parking lot by parking system okay d parking lot has three kid of parking space medium and small with a fixed number of stalls okay what is the meaning here what is the meaning of three types in parking system If vehicles are a power, then a big vehicle, either medium or small, is okay, so what do we have to do? If we have to design a parking system, then what will be constructed first here, it is okay for us, in which what will we pass, we will pass three things, medium mall which Parking system is class, these three things are there, we will insulate them, what will be the three, it will tell us in the initial, how many big vehicles can we have for big, how many medium vehicles can we have, how many small vehicles can we have, okay then what will happen? These people will add the method tomorrow, ok we will add it tomorrow and also tell you the type of tax cost, big is medium, big and medium is small, how will we know, they have given 123, if there is a forest, then the car will be damaged, if you are there, then the parking is medium. Will come in the lot if there is space in it, if someone has sent a Big car, then first we will check in the parking lock whether there is any space for Big, all the space for Big is over, okay, if the space is over, then block fruit. We will return otherwise what will we return? We will reduce the space of true and big by one number. Okay, so if I show you an example like they are doing this constructor yesterday, this one is fine. Here, what did they pass for big? It is done, suppose that we have five sellers, there is a place of heart, okay, there is a place of medium, and there is a place of three small, okay, now someone added the method yesterday, now here it has to be told the tax type is required one. Means big, you mean medium and three means small, so please suggest, we have made big and send it to the store. Is the bike of the request one big, is it a power, so first we will check how much space we have for big. Five means there are five places right now. If it is empty, it will remain. Yes, if it is Shakti, what will we do? Will we give Big [ __ ] a ghat with him? What will we do, will we tax and will return? [ __ ] a ghat with him? What will we do, will we tax and will return? [ __ ] a ghat with him? What will we do, will we tax and will return? Return, what do you mean brother, the car should be parked in your parking lot, Shakti, it will be parked. So we will subtract one number from Big because now one is filled. Okay, by doing this, BB will become zero and then we will check that if the request for one Big comes again, then now there is space in Big. If we will attend by fruit, then how was this total, was there anything special otherwise come, let us create a variable, okay, we have created a variable at the class level with one name, now we have mentioned zero in its details, okay then we People made it medium, it also has initial zero and then made it small, its size is initial zero, now what will happen first the constructor of the parking system will happen tomorrow, okay, then what will be the values ​​in the construct happen tomorrow, okay, then what will be the values ​​in the construct happen tomorrow, okay, then what will be the values ​​in the construct 1 0 means first how to take the test then 110 So this one is big, this one is medium, this is small, this is zero, okay, so what will we do, we will set the value that will be passed in this, so how do we write the class level variable in Java, this is big, this is equal. You are big, this is medium equal, you are medium, this is small is equal, you are small type will be passed. It is ok to understand, what will be passed in the switch, what can be done by type, what can be the type. 123 So if there is one, that means if it is a big vehicle, then we will check. Now Big ours is bigger than zero. If Big ours is bigger than zero then what will we do? We will give a pier to Big and also make a return row. Okay, this is how we will do it, how can I get a break now because otherwise then next time. No matter how it will be executed, brakes have to be applied. Okay, now if it is a medium vehicle, we will check the medium first. Okay, if the greater is zero, then the medium less people will make a minus and you will return whether the greater is zero or not. Now what do we have to do if any of these conditions are not satisfied i.e. conditions are not satisfied i.e. conditions are not satisfied i.e. if it is big if it is zero or medium if it is zero or if our return is nothing then @ if all if our value is passed. then @ if all if our value is passed. then @ if all if our value is passed. And one tax type, if its size has become zero, then what will we return? So what happened earlier also, if tax type is also passed, big is given greater, if it is zero, then big will be mined by one and will return true if supported. Do all the species of Big have been destroyed, the tax type has also gone here, all seven have been satisfied, see in Big equals you have become zero, so this condition is coming out, so what will we have to return now, water, so let's run it and see. So please like share and subscribe and if any confusion please comment thank you very much
Design Parking System
running-sum-of-1d-array
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the `ParkingSystem` class: * `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slots for each parking space are given as part of the constructor. * `bool addCar(int carType)` Checks whether there is a parking space of `carType` for the car that wants to get into the parking lot. `carType` can be of three kinds: big, medium, or small, which are represented by `1`, `2`, and `3` respectively. **A car can only park in a parking space of its** `carType`. If there is no space available, return `false`, else park the car in that size space and return `true`. **Example 1:** **Input** \[ "ParkingSystem ", "addCar ", "addCar ", "addCar ", "addCar "\] \[\[1, 1, 0\], \[1\], \[2\], \[3\], \[1\]\] **Output** \[null, true, true, false, false\] **Explanation** ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0); parkingSystem.addCar(1); // return true because there is 1 available slot for a big car parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car parkingSystem.addCar(3); // return false because there is no available slot for a small car parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied. **Constraints:** * `0 <= big, medium, small <= 1000` * `carType` is `1`, `2`, or `3` * At most `1000` calls will be made to `addCar`
Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.
Array,Prefix Sum
Easy
null
1,232
hello and welcome to today's daily lead code challenge let's begin question 1233 check if it is a straight line so you're given an array of coordinates I is another array X Y where X Y represents a coordinate of a point check if these points make a straight line in the X Y plane and some examples so we have points one two three four and so on these are all in a straight line because they have the same slope and the same y-intercept um let's look at another example here coordinates one two three four and right away we see that the slope between y 1 and 2 is 1 slope between two and three four is two so already this is a um this is a not a straight line and the criteria is because we don't have a same a similar slope between lines one two and two be between points one two and two three um okay I'm thinking well would it be enough to just measure assuming that the points are sorted could we just get away with checking if the slope is consistently the same between two consecutive points so between these two and these two would that be enough to um would that be enough to tell if a line is straight or not uh let's try do doing that we have uh we have coordinates the length of coordinates input array at least two meaning that we could calculate the initial um slope right away let's yeah let's do that the numerator is going to be what um let's have this no set the numerator is equal to coordinates uh one of one minus coordinates one two so we're subtracting the one the Y coordinate from second point from the y coordinate of the first point and now denominator is going to be the x coordinate of the second point and then the x coordinate of the first point and all of a sudden we have a which is the slope let's uh a X plus b we have a as the first point so a is going to be the numerator divided by the denominator and then let's have a loop that iterates through all pairs well not all pairs but consecutive pairs of points in the input array and checks if the slope is the same as what we have counted for the first one um we can actually do this in the loop I'm thinking so what if I have um what if I set the a initially to zero a initially two zero no I'm not gonna make it difficult I have access to the first uh I have access to the first two points so I'm just going to say that for I in range Len of chord minus one that would let me go through each of the points I would say that P 1.1 is equal points I would say that P 1.1 is equal points I would say that P 1.1 is equal to um coordinates of I and P2 is equal to coordinates of I Plus 1. and let's see now what do we do here well just the same thing numerator and denominator right current numerator is going to be uh P2 of Y minus P1 of Y current the denominator is going to be P2 of 0 minus P1 of zero and let's have the current a is equal to current numerator divided by Cur Dem if a does not equal occur a then return false and then if all else goes if this Loop executes correctly then we can return true uh let's run this and see if this is good and coordinates is not defined I'm this misspelled coordinates everywhere um coordinates and we seem to be good so what if I'm thinking that there could be a division by zero that's exactly what I thought so um all of you may know that a horizontal line has a slope of zero but a vertical completely vertical line has a slope of undefined and a slope of undefined is there because denominator when denominator is equal to zero U actually run into an issue where you can't divide this so if I'm thinking of having a condition in calculating our slope such that if denominator is not equal to zero then we do the regular um numerator divided by not denominator else undefined so what this allows me to do is conditionally set um slope current slope to undefined in the case where the vertical it's the slope is a vertical line so we could actually do the same thing here if Cur ve denominator is not equal zero else undefined and then if a does not equal current a return false let's try this one more time and this probably there we go however oh I'm seeing that there are way faster Solutions let's see if we can get away with doing something faster although so let's see what's coming faster so for all never seen it for all so this let's not do this map all x's and all y's um so he has a list of all x's and a list of all y's if Len of set what does this give us if Len of set x equals 1 or length of set Y is equal to one does that mean that oh he's checking if the line is completely vertical or completely horizontal because if they are all on One X plane or on one y plane then it would definitely be true else he is um you know I don't really see the okay let's look at this one maybe this one is a little bit hard easier to understand um coordinates so he's just finding the X and Y coordinates of the first and the second point and then four I in consecutive Theory if so this is to me this is the most obvious so maybe let's try re-implementing this a bit re-implementing this a bit re-implementing this a bit so what he's doing here is he's not he's no longer checking that the whole line is that the that all the pairs are the same he's only checking that the ones that aren't um the points that have not yet been calculated and for us that would be everything excluding the first two so I mean yeah for us that would be plus one and plus two but I'm not seeing a significant oh and this is obviously but this is not significantly faster although the idea is still the same they're not really using anything much more clever okay you know what I would say that intuitive and intuitive solution here would just be good enough so um and it seems like they're pretty uniform so okay uh I would say that this is a good solution um use this if we want and stay tuned for other submissions thank you have a good day please like And subscribe bye
Check If It Is a Straight Line
sum-of-mutated-array-closest-to-target
You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane. **Example 1:** **Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\] **Output:** true **Example 2:** **Input:** coordinates = \[\[1,1\],\[2,2\],\[3,4\],\[4,5\],\[5,6\],\[7,7\]\] **Output:** false **Constraints:** * `2 <= coordinates.length <= 1000` * `coordinates[i].length == 2` * `-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4` * `coordinates` contains no duplicate point.
If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value.
Array,Binary Search,Sorting
Medium
null
1,367
hey everybody this is away in this video we are going to solve a problem called linked list in a binary tree this is basically a lead good problem number 1367 in this question what we have to do we have we will be given a linked list and what we have to do we have to check that if this linked list exist in our binary tree or not for example here 4 2 and 8 is a linked list and we have to check that if this link list exists in a binary tree or not and if exist then we have to return true else we have to return false so here we have 4 2 and 8. so as you can see 4 2 and 8. this is this linked list exists in our binary tree so in that case we will return true so this is our question right so the question is pretty straightforward now let's try to solve this problem so what we are going to do we will be using link we will be using error list to basically solve this problem for example let's say here is our error list now what we will do we will check that if all the elements of this linked list exist in our binary tree or not because that is a very basic condition that each element of the linked list must exist in a binary if that's not the case it must return false in you know every cases if the all number doesn't exist in the binary tree right for example here is 4 if 4 is 4 exist in our binary tree yes we can see 4 is here and here so it exists so we will write 4 in our or add 4 hour in our list right now here our 2 now is 2 exist in our tree yes 2 is here and here right so we will fill our list with 2 right now next we have 8 here is 8 existing binary yes 8 exist in our binary tree here only so our first condition is going pretty good that is all elements of the linked list must exist in a binary tree right now here is our eight right now what we have to do just one thing and that is if there exists path between all these numbers of error list so here in this case as we can see there exists a path that is 4 then 2 then 8 so in this case we have to turn true that's obvious so ok let's don't go into that let's first fill our error list with the you know numbers that exist in our binary or not so for that what we have to do we have to first create our error list so we will type list of tree node let's call it storing list s-t-o-r-i let's call it storing list s-t-o-r-i let's call it storing list s-t-o-r-i storing list this is the name of our error list is new list right so here we have our global error list right now let's create a function that will fill our error list let us call it store to list public void store to list right it will have head of the linked list head then we have tree node renode root right now we have to define the base case that is if head is null or root is null then in that case simply return because we don't have to do not anything further if both of them is null and the other cases the main case that is if head dot val that is the value of head is equal to the value of the root dot val so in that case as you can see here 4 is matched with the sum of the node value that is 4 here so in that case we will add this value to the storing list so storing list dot add root right now we will recursively call the left and right subtree and do the same condition that is store to list which is the name of our function we are using recursion here then here we pass head and root dot left row dot left then root dot right same copy and paste here and this time root dot right okay so we are done with this function this fill this function will store the values in the error list right now what we have to do we have to check that if there exists a path between them or not right so let's write one more function that check that if there exists a path or not and this path is a public boolean it will return a boolean value and this will call a check sub path right it will have same input right as list node head then renode let's fast node this time not the exact route right now let's define the base condition if head is null so in that case return false because linked list our link list is empty return false and if node is null return 2 this time okay now if head dot val is equal to node dot val that is the value matches right the value matches then check for the left and right subtree that if there exists a path or not return let's copy this and in this we have to pass head dot next then because we have to compare the next node of the linked list at dot next and uh node dot left right node dot left or because our operator is because here we have like subtree one four two and eight so let's say here we have now it now two either exist left side or right side of the root it doesn't really matter because we have only have to check for the path that if the path exist or not right so in that case r and we will copy same again and this time it should be node.write and this time it should be node.write and this time it should be node.write okay so this is our base case and after that return false so this will simply check that if the you know these two nodes this function will basically check that two nodes have a path or not right now in the main function let's write some actual code so let's fill our uh error list that is we'll call this function store to list and we will pass head and root right this function will simply fill the error list with the numbers that are that exist in a tree right now what we have to do we have to uh traverse the list and check that if the elements have nodes have some path or not so for tree node let's call it element in a storing list let's write storing list right now we have we are searching in storing list and if we will call this function if check path sum between head and this element if there is a path between head and the element that is the current element that we are on in the storing list if there is a path then simply return true right else return false okay so what we had done okay first let's run this code okay there is some error that says cannot find a symbol sorting list storing list i guess there is a typo yes there is small l and this one again okay as you can see the solution is accepted now let's sum it okay we again have an error and this error says wrong answer now let's check where we are wrong okay here is our error and this error is if head is null then in this case we have to return true and when node is null we have to return false okay let's submit this again and let's see how it goes okay as you can see the solution is accepted and let's revise again so what we had done we had traverse the list and check that if element even exist in our tree or not and if doesn't exist then we have to return false and we don't have to check even further so 4 exist here and here then 2 that 2 exists here and here then 8 it also exists here right now if exist then store it in a array list so 4 to 8 is stored in the array list now we just have to check that if there exists a path between them or not right so this is the function stored to list this function will basically help us not help us this function will basically store the elements in the list if exist then it will store in the list and this function checks a path will basically check it use recursion it will check that if there exists a path between two node or not now in the main function or method here we have store to list and passed head and root this will simply store our you know error list which this will fill our error list with our desired nodes right now we will try we are traversing in our error list and if there exists a path between that element of the linked list and the current element or current element of the error list if there exists a path then return true else return false so that was the code so that's it for this video if you enjoyed the video hit the like button and subscribe to the channel for more coding interview problems see you in the next video
Linked List in Binary Tree
maximum-height-by-stacking-cuboids
Given a binary tree `root` and a linked list with `head` as the first node. Return True if all the elements in the linked list starting from the `head` correspond to some _downward path_ connected in the binary tree otherwise return False. In this context downward path means a path that starts at some node and goes downwards. **Example 1:** **Input:** head = \[4,2,8\], root = \[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3\] **Output:** true **Explanation:** Nodes in blue form a subpath in the binary Tree. **Example 2:** **Input:** head = \[1,4,2,6\], root = \[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3\] **Output:** true **Example 3:** **Input:** head = \[1,4,2,6,8\], root = \[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3\] **Output:** false **Explanation:** There is no path in the binary tree that contains all the elements of the linked list from `head`. **Constraints:** * The number of nodes in the tree will be in the range `[1, 2500]`. * The number of nodes in the list will be in the range `[1, 100]`. * `1 <= Node.val <= 100` for each node in the linked list and binary tree.
Does the dynamic programming sound like the right algorithm after sorting? Let's say box1 can be placed on top of box2. No matter what orientation box2 is in, we can rotate box1 so that it can be placed on top. Why don't we orient everything such that height is the biggest?
Array,Dynamic Programming,Sorting
Hard
2123
1,758
hey everyone welcome back and let's write some more neat code today so today let's solve the problem minimum changes to make alternating binary string another easy problem for us today we're given a string s which consists only of zeros and ones so it's a binary string and we want to make it such that it is alternating which means that every other character is going to be different so it's going to be 0 1 or it could be 1 0 so already we kind of notice that there's really only two possibilities so even if we were trying to Brute Force this it wouldn't really be an inefficient solution so if we're given a string like this 0 1 0 to make it alternating we have pretty much two choices we can either turn it into this or this so we can kind of just look let's first consider if we were to change it into this string well this is different we'd have to swap this to a one these are different we'd have to swap this to a zero these are also different so we'd have to swap three characters these are the same so we don't do anything with that one so we'd have to swap three characters to turn it into this string now what about the other string up here well these are the same don't have to do anything these are the same and these are the same we'd only have to swap this and this well not both of them we'd only have to swap this one into this okay so thinking of it in this way you could probably code up the solution with one Loop or if you wanted to do it a simple way you could even have two Loops one to check for this and one to check for the other but did you kind of notice something when we were going through this for the first string if we were to make it alternating like this we'd have to swap these three characters if we were to make it the other string we'd only have to swap this one that's not a coincidence because notice that these two strings are the literal opposites of each other this is opposite and this is opposite so in other words what I'm trying to say is if we only check how many operations does it take for us to turn this string into this string for example like if it's starting with zero how many operations would it take we found it only takes one operation now we want to ask how many operations does it take for this other string to turn it into this other string well we already know that it's going to be all the other characters in other words the length of this is four it's going to be four minus one character that we had to swap so it's going to be three characters for this other string that's a pretty small optimization so it's kind of just taking this from a two pass solution into a one pass solution depending on how you cat it up I think you could cat up into one pass even if you were checking for both of these strings but it's just a slight optimization it's not a huge deal I just thought it was worth mentioning because this problem is pretty easy anyway if you can code up the clever solution I'm about to show you right now you can probably code up the easier one as well in terms of time complexity it's going to be big of n we do have to scan through every character in the string but no extra space complexity that is going to be constant let's code this up so I'm going to have a variable which is Count it's going to be zero and this is going to be the number of operations if s were to start with zero and then when we return the result we're not necessarily going to return this count what we would actually return is the minimum of this count and the other count which is going to be the length of the string minus this count because that tells us how many operations if s were to start with one so this is the return value only thing left for us to do now is actually compute the count the easiest way to do it is one just iterate over the string obviously but to check if the character at s of I should be a zero or a one we could figure out a way to compare this to like the previous character or the next character but the easiest way is knowing that at index zero we expect the value to be zero at index one we expect the value to be one at index two we expect the value to be zero etc the pattern here is that for even indices we expect zero for odd indices we expect a one so that's what I'm going to use that's the Assumption I'm making so for us to check first of all is this index even or odd modding I by 2 this tells us it's odd in the else case we know the index is even now that we know that at an odd index we expect the value to be a one so if the value is not one if it's actually equal to zero then we know we should increment the count by one cuz we have to perform an operation here I could put this in like an if statement uh increment this by one but if you want to get kind of clever you can combine these into like a Turner operator so I'm going to do this and in the else here we'd add zero so it's again not like a big deal you don't have to write it this way if you don't want to I'm just kind of used to doing it this way and in the El case we're going to do pretty much the opposite here so we'll add one we have to make an operation if we were expecting a zero but the character was actually a one so this is the entire code let's run it to make sure that it works and as you can see on the left yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out NE code. thanks for watching and I'll see you soon
Minimum Changes To Make Alternating Binary String
distribute-repeating-integers
You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not. Return _the **minimum** number of operations needed to make_ `s` _alternating_. **Example 1:** **Input:** s = "0100 " **Output:** 1 **Explanation:** If you change the last character to '1', s will be "0101 ", which is alternating. **Example 2:** **Input:** s = "10 " **Output:** 0 **Explanation:** s is already alternating. **Example 3:** **Input:** s = "1111 " **Output:** 2 **Explanation:** You need two operations to reach "0101 " or "1010 ". **Constraints:** * `1 <= s.length <= 104` * `s[i]` is either `'0'` or `'1'`.
Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to be assigned to this number.
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Hard
null
781
all right cool 781 rabbits and forest in the forest each rabbit has some color some subset of rabid possibly all of them tell you how many other rabbits have the same color as them those answers are placed and in the way we turn the minimum number of rabbits that could be in the forest for example you have some sub cement so to enter what yeah this is some like 20 surfing there's a tube a percent of one could pop your same color say right that's the first index okay so did so okay so three Rapids tell you how many rabbits have the same condom the first rabbit said one other this is gonna be like five lines of code or very tricky five lines of code type of question but - was p5 okay I know about this is a tricky problem okay I mean I think maybe not maybe I'll start some ruse which has some of them is being hint in this example and that's what I've been kind of looking into over so dentists one that means well - I think we that means well - I think we that means well - I think we could well first of all to compress all the answers to get into a hash table with the number of being the thing and then I think you just do some math on that number maybe yeah okay let me play around with that let's say for I think maybe that's sounds like it's like a really I only given out describe it to be honest it's just such a weird but like example well for now we're just going to keep track of the numbers and then now for key and okay I figured that's a cleaner way to do this - it's a that's a cleaner way to do this - it's a that's a cleaner way to do this - it's a big time where I'll use may be right over and so now you have I don't even know how to describe to you is using keys but okay so it knows how you count as you don't count that key like this is a second ordered so now let's say there's the same number then it matches each other so it's kind of some kind of matching the same number thing is what I'm trying to do here so in this case if dance is we match two of them and just two then we matched three numbers so okay so we want to match keep us one okay that's just to me so just you could count keep us one okay well that's the name just put over a number of pairs so it's not even pairs per number of same color Rapids and that's a terrible name okay basically number so that's the number of pairs first one we want the ceiling of this which is test I think okay so that was one and we've it is two then they'd only returns one and there's 322 I guess that's fine so it's like a sort of a greedy type thing and then we saw two secret so you know the number x plus one okay more like that maybe see if it works first okay yeah Yolo summit okay cool wow that actually worked I mean this is a brainteaser one so I don't know I mean it's one of those things where like I feel like you give me the same problem tomorrow I might not get it right well like I'm gonna take me like a long time to get it right excuse me sorry the idea here is that if there's one other rapid color for your number that's an answer you match them with that number plus one so like for example well one you want to there's only two parts of people with or two possible rapid the same color and they both enter one and it's two that means the two other Rapids so that possibly three rabbits that are the same or for each pairing so it's more than doing that like you have an answer that's like I don't know five ones then you have three pairs and so forth and then you just round it up and I think that extends to whatever the number is so like here if we had say twelve tens then there have been 22 I guess or something like that or 20 maybe 22 yeah so that's kind of the idea I don't know yeah the palm of these pointees is like I said is that I don't know if it's I could solve these deterministically you know and in the same way like I think you know sometimes I get lucky I'm like I yeah that's clearly the way to do it and then some days I'm just I'm having a good day and I cannot fall back on my phone of Mentos and I'd be like okay this is you know and in this particular case it's very specific excited I don't know there's a little brain teaser II I don't know if you could practice this particular palm on it then if someone gives you something exactly the same so I don't know how much while you I would place on this problem there it is a fun brain teasers fun problem not a program well I'm not a CS problem but necessarily anyway it's a logic problem but yeah I mean I guess it's fun the code I mean it's twelve lines of code with a lot of spaces I don't think I could improve that much more maybe I mean maybe I couldn't in this where I was better I was having trouble kind of figure out upon myself but okay cool but this is basically just rounding up in a weird way Queens number okay cool uh yeah let me know if y'all wanna
Rabbits in Forest
basic-calculator-iv
There is a forest with an unknown number of rabbits. We asked n rabbits **"How many rabbits have the same color as you? "** and collected the answers in an integer array `answers` where `answers[i]` is the answer of the `ith` rabbit. Given the array `answers`, return _the minimum number of rabbits that could be in the forest_. **Example 1:** **Input:** answers = \[1,1,2\] **Output:** 5 **Explanation:** The two rabbits that answered "1 " could both be the same color, say red. The rabbit that answered "2 " can't be red or the answers would be inconsistent. Say the rabbit that answered "2 " was blue. Then there should be 2 other blue rabbits in the forest that didn't answer into the array. The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't. **Example 2:** **Input:** answers = \[10,10,10\] **Output:** 11 **Constraints:** * `1 <= answers.length <= 1000` * `0 <= answers[i] < 1000`
One way is with a Polynomial class. For example, * `Poly:add(this, that)` returns the result of `this + that`. * `Poly:sub(this, that)` returns the result of `this - that`. * `Poly:mul(this, that)` returns the result of `this * that`. * `Poly:evaluate(this, evalmap)` returns the polynomial after replacing all free variables with constants as specified by `evalmap`. * `Poly:toList(this)` returns the polynomial in the correct output format. * `Solution::combine(left, right, symbol)` returns the result of applying the binary operator represented by `symbol` to `left` and `right`. * `Solution::make(expr)` makes a new `Poly` represented by either the constant or free variable specified by `expr`. * `Solution::parse(expr)` parses an expression into a new `Poly`.
Hash Table,Math,String,Stack,Recursion
Hard
736,785
1,095
so hey guys welcome to my Channel today lead code problem is found in mountain array okay it's a lot of description let me explain you this shortly okay uh they give a mountain array what it means by Mountain are like in mountain you have to go up then you find a Peck and then you have to come down just like that in Array like you can see 1 2 3 4 5 like you are increasing right you are going up to the mountain or the to the peak okay like one then two three then four then five now you reach the peak because after five you have to come down right like 31 okay so this is called a mountain ARR and so they give you a Target value and we have to find the index where the target value is like three in this array like three appears at index two also index five right we have to return the minimum index okay the minimum index was two so the minimum index is what two so you have to return to so how we can solve the problem by seeing this array you can say okay I will Travers through the array first we found the element we return the index but think about it U it's a hard level problem you can't solve the problem by just iterate through it right so what we can do to pass the test cases right uh think like that okay from 1 to till 5 okay it's a sorted the let's Che like 1 2 then three then four then five it's a sorted array okay now from 5 to 1 it's also a sorted array but in reverse order okay so if somehow I can found this peak I know the for this peak the left part is a sorted array in ascending order the right part is in what descending order right so for this Pak value like when we find a Pak value or the index of this Pak value okay we can run a binary search to it left part as well as to his right part so as well as it's right part and we try to find this target if we don't find this target we have to return minus one let me show you the code so you can understand it very easily it's a very simple code actually let me show you the code so this is the python code and I uh take the length of this array and I set a left pointer at one and right pointer at n minus 2 why I set a left pointer at one and right pointer at n minus 2 let's check like the left part is what one like zero index and the most right part is what one so it's not a peak right it's never going to be a peak like for Z 1 one for one two they are not going to be the peak okay so Peak uh is always in somehow middle right it's not in the most right part or most left part okay so this one and this one never going to be Peak so I don't consider them so I start L as one and the right pointer as n minus 2 like from this two to this two our like from this two and up to this three is our search P okay we run a binary search in this okay now we run a binary search at this okay now check the conditions like how I know we are in left part or right part think about it now if I am in this left part at three suppose I'm at three just check um let's check uh the element before this three is less than that and element after this is greater than that okay so here you can see the element mid minus one is less than the element mid also the element is greater than the element m okay m + 1 is greater than the element m okay m + 1 is greater than the element m okay m + 1 is greater than then we know we are at the left part now I at three so my left element is less than three and my right element is greater than me that's why I have to increase my search space in a right side now I have to search in this place right okay so I increase my M as I increase my L as M +1 and now to the increase my L as M +1 and now to the increase my L as M +1 and now to the opposite like if I am at right side like I'm at this three now think about this the left child of this three is greater than that and the right child of this three is the left element is greater than three and the right element is what less than three in this condition like this condition the left element is greater than the mid and the right element is less than the mid okay so in this case like I'm at three so I have to what I have to do what I have to check in left side so that's why I reduce my right pointer to M minus one and else part like I'm at five right so my left pointer is what is less than me also my right pointer is what less than me so if they both are less than me if that means the El's case I know this is my Peck point right so I break this while loop and store that mid value as pick then now we have to check its left part as well as the right part and then if we don't find anything we will return minus one so this is all about this problem so thank you all that's all for today
Find in Mountain Array
two-city-scheduling
_(This problem is an **interactive problem**.)_ You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `mountainArr`, return the **minimum** `index` such that `mountainArr.get(index) == target`. If such an `index` does not exist, return `-1`. **You cannot access the mountain array directly.** You may only access the array using a `MountainArray` interface: * `MountainArray.get(k)` returns the element of the array at index `k` (0-indexed). * `MountainArray.length()` returns the length of the array. Submissions making more than `100` calls to `MountainArray.get` will be judged _Wrong Answer_. Also, any solutions that attempt to circumvent the judge will result in disqualification. **Example 1:** **Input:** array = \[1,2,3,4,5,3,1\], target = 3 **Output:** 2 **Explanation:** 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. **Example 2:** **Input:** array = \[0,1,2,4,2,1\], target = 3 **Output:** -1 **Explanation:** 3 does not exist in `the array,` so we return -1. **Constraints:** * `3 <= mountain_arr.length() <= 104` * `0 <= target <= 109` * `0 <= mountain_arr.get(index) <= 109`
null
Array,Greedy,Sorting
Medium
null
787
today we will solve another graph problem here you are given a bunch of source and destination and what is the fear of flying a flight between those cities so let's say this is the graph so here uh there is a direct flight from 0 to 1 and its cost is 100 similarly uh there is a flight from 0 to 2 its cost is 500 and we have a flight from 1 to 2 and its cost is 100 and it's given as a pair of three numbers source destination cost so using this you can form this graph so this fare denotes uh the distance if you look in terms of the graph terminology these cities denote the nodes or vertices and this existence of flight between two cities denotes the edge and the price of that flight denotes the distance or the length of that edge so these are given and you are given a source so source is 0 in this case and you are also given destination so you know the source you know the destinations but you have a condition uh you have to take at most k stops so there may be direct flight maybe that is the cheapest but maybe that indirect flight is more cheaper for example if you want to go from 0 to 2 direct flight cost 500 a flight which texas halt at 1 costs 200 100 plus 100 but there may be that there are more nodes here and that four five hops and ultimately you reach 2 is even less than 200 but the condition is that number of hops should be at max k so that is the constraint so uh you may straight away think that it's looking like a uh shortest path problem like that extra case there also we are given a source we have a notion of directed graphs and all the edge weights are positive just like the flight prices are positive but there we are only calculating the minimum distance here we are not calculating the minimum distance so in dijkstra if you remember uh we are calculating uh updating the distance level gradually so when we find a better path we update that but here that constraint k does not allow us to reach the optimum solution but you have to stop once you reach k hops so let's say let's look at an example so if you run dextra here and a is the source so its distance level will be 0 and everything else will be infinity so what we do we pick the minimum element we add the source to a priority queue and then we pick the minimum element or the top of the priority queue in this case mini min priority key or min heap so this will be picked and then you look at its neighbors and so in order to reach a you need zero hops because this is the source and zero price also then we look at its neighbors are b and d both have infinity level so from a we can reach them using ten and five prices so we compare whether we got a better price or not so obviously five is less than infinity so we make it five and also hop of one since the hop of the node from which we came was zero we add one to its hop so we reach d this is not hop but uh this is a kind of edge you can say one edge we took hop one hop denotes two edges so from a to b and b to c so here it will be one stop so k will be one in this case so edges will be one more than the hop so here let's this denotes the number of edges we took one here also we got a path of length 10 from source which is less than infinity so we update it and again one edge is counted next this is popped from the queue and b and d are pushed into the queue so b is pushed with a distance of 10 and hop of 1 and then d is pushed into the queue with a distance of 5 and edge of 1 this is strictly 1 less than the k due to this region so these two elements are in the queue now priority queue so we will pick the minimum so this is the min hip so this is the minimum d is the minimum so pick d out so let's strike it out now we see that we look at the neighbors of d so the neighbors of d are e so its minimum distance is 5 so this distance will be finalized and when we pop we also compare have we reached the destination if we have reached the destination so when we pop something from this queue the minimum that is the final uh level of that node so d is finalized so let me color it a was finalized when we popped out now d is the minimum so these distance is final from the source so when we pop out we also check whether we have reached the destination if we have reached the destination and this length is final and this is well within the k then we return it so d is not c so we continue so we look at neighbors of d are e so 5 plus 2 7 and hop will be one more or number of edges sorry two edges that means one hop so we insert it into the queue e seven and 2 so here maximum number of edge can be k plus 1 or 2 so next time when we pop out element having a edge of 2 we will not look at its neighbor because all its neighbors we will go from this node will have 3 edges and we can have take maximum 2 edges so we have inserted e into it then what is the next neighbor is c and its distance will be 14 and again two edges this and this 14 and again two edges this and its next neighbor is b so let's although b is already here but we will keep inserting so if whichever is the minimum b that will be picked first so whatever is the shortest distance within that limit will be uh figured out so b here it's 8 so we update it if it was more than 10 we would have not pushed it but we got a path of 8 and it's well within this bound that is 2 edges so we put it 8 2 and there are no more edges so we stop next we pick the minimum from this minimum is this 7 that is e so we look at the neighbors of e uh we will compare if it's the destination it's not destination then we see how many edges are there two so we know that i cannot look at its neighbors because that will add additional edge so we do nothing with e next we look what is the so let me mark it finalized next we see which is the minimum 10 14 8 so minimum is b so we pick b again it has b is not the destination and the number of edges is 2 which is more than which is equal to this maximum limit so we cannot look at its neighbors going to its neighbor will add one more edge so we do nothing with this b next minimum is again b this one so we pop it out so b's minimum is 8 but the path that will go to c will not be the shortest path but will be shortest within this bond so uh next we picked this b 10 1 so this is less than maximum number of edges or k plus one less than k plus one so we look at its neighbors are c d but d is already finalized although you can add it but it will never get picked uh it will get picked but it will never get processed since we will put it with a edge of two so we can optimize our solution so that we don't insert a vertex again if it's finalized but let's insert it for now so let's insert d and this is 10 plus 2 is 12 and number of edges is 2 and the other neighbor of b is c uh which we will insert again so c will be this is 10 plus 1 is 11 and number of edges will be 2 so now we are done with b now what is the minimum here 14 12 and 11 so we will pick 11 c so let's strike it out so we popped c with 11 and 2 and we see whether this is the destination yes this is the destination and we return since whenever we find the destination we return so return 11. so let's see that the minimum shortest path from a to c is of length 11. within this condition what is the global shortest path would be this a to d to b to c let's count the distance a to d is 5 then d 2 b is 3 then b to c is 1 so 5 3 8 plus 1 9 but here we have taken two hops or three edges so this is not valid what is the next one you can come to a to d to c this is just one half but its length is 14 and a to b to c is 11 and that will be the minimum under this condition and which we have correctly returned here so let's write the code for this in c process and python so let's build the adjacency list first which will be a vector of vector so the outer vector will be of length n uh where one space will be for each of the n vertices so let's take an example let's say we have a simple graph let's make it 0 start from 0 to n minus 1 and this is 100 this is 50 this is 10 this is 20. so how we will represent it here n is 4 vertices are there so we will have a space for all the four and what are the adjacent vertices of zero it's uh one and two so we will reserve a space for one and two if it's unweighted we don't need to store the weight but since it's weighted we will store the neighbor and how far it is from this node zero so one is at a distance of hundred two is at a distance of fifty then what are the neighbors of one only one is outgoing which is towards the 2 so we have 2 and length is 10 from 2 there are there is only one edge so it's 3 and 20 and from 3 there is no outgoing it so this will remain empty so this is a vector of vectors so this is a vector here so this is a vector of here its size is fixed two lengths so either you can keep another vector or a pair so vector of pair of intent so it's it may look complex but it's not that complex if you look it look at it so this outer vector will be of size n this will vary depending on how many so this vector will be of size number of neighbors or outgoing edges from a given vertex which we pick from this outer vector and again within that the length is fixed to each so if it exists it will have a length of two so let's write it in the code vector of pair of int and int this we will call it as adj for adjacency list and then let's build it so for vector of int flight so flights is itself a vector of vector and each l each element in this has three components source destination and price so adj f0 this will be the node source destination and f2 will be the price or the distance so we have built the adjacency list now we will keep the priority queue and each element will be a vector and container is a vector of hint and the comparator we will use the default greater comparator so how this greater comparator works is that it will simply compare integers can be compared but if it's a vector of integers then uh it will compare the first element of those vectors so let's say a vector has 50 and 4 and the second vector has 10 and 100 then first vector is larger since the first component is 50 here and in there it's 10. so it will compare based on that and here we will keep the first component as the distance level so it will automatically keep it sorted based on the distance we don't need to provide a custom comparator you can also provide a custom comparator if you are not putting the distance in the first component of this element of priority queue let's call it q and we will push the source into it so 0 is the distance that is the first component based on what the comparison will be made then src is the source which is given to us and k plus 1 which will denote number of edges which we had seen that will be one more than k or the stops while q is not empty pick the element vertex which with the minimum distance and then remove it from the priority queue so the first component top zero will be the distance level and second will be the actual vertex level so let's call it u and last one will be the k so here i am using small k it should not be com confused with the k that is given to us which is capital k or we can also use edges here e to denote edge since this is actually the number of edges so let's call it e and if dst that is destination which is given to us is same as the current uh this node that we popped out then we return its distance level that is d else if e is more than zero that is we can add one more edge to it one or more edges to it if it's zero that means we cannot add any edge so we cannot look at its neighbors so if it's more than zero then we will look at its neighbors that is pair int all the neighbors v of u q dot push first is the distance level so it's d plus whatever is the distance of the this element plus v dot second and next is the level of the vertex level of the neighbor which is the first component so here we are storing the node and its distance so second is the distance for first is the node itself and we will allow one less edge to it so here it's e minus one so when we pop this element out we have reached here we using one more edge so one less edge we can afford so we have done e minus 1 and then if it doesn't return in any of these cases that is there is no path using a k hops from source to destination in that case we will return minus 1 maybe there is a path from source to destination but it takes more than k hops for all the paths then we return -1 paths then we return -1 paths then we return -1 and let's run it so it gives runtime error in some vector allocator and so we are accessing it without so let's make it of size n and this also should be cool and answer matches so let's submit and the solution is accepted in c plus now we will look at the python solution so we will build the adjacency list so it will consist of key and key will denote the vertex or the nodes and it will con for each key we will have a value of list which will hold the adjacent nodes so let's look at all the elements of flights which is source destination and edge or the price so we have built the adjacency list we will use the priority queue so this is a list and we will append it to it source so now source is in only in the priority queue now we will use the heap functions which is heap queue dot heap pop and pass the queue and no need to call the pop it does both in one step d u e if you use the destination return d if it's not then check if we have more edges left to add if we can add more edges then add it so look for all the neighbors v of u and then so looks like there is some indentation issue here okay we will discover that so he q dot he push q then these values uh d plus v dot second is v one and v dot first is v zero and e minus one so there is some indentation issue that means there was some error here so it's p and let's add this and let's see if it picks the indentation yes it picks looks like it's fine now it works so let's submit and the python solution is also accepted
Cheapest Flights Within K Stops
sliding-puzzle
There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`. You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _to_ `dst` _with at most_ `k` _stops._ If there is no such route, return `-1`. **Example 1:** **Input:** n = 4, flights = \[\[0,1,100\],\[1,2,100\],\[2,0,100\],\[1,3,600\],\[2,3,200\]\], src = 0, dst = 3, k = 1 **Output:** 700 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. Note that the path through cities \[0,1,2,3\] is cheaper but is invalid because it uses 2 stops. **Example 2:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 1 **Output:** 200 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. **Example 3:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 0 **Output:** 500 **Explanation:** The graph is shown above. The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. **Constraints:** * `1 <= n <= 100` * `0 <= flights.length <= (n * (n - 1) / 2)` * `flights[i].length == 3` * `0 <= fromi, toi < n` * `fromi != toi` * `1 <= pricei <= 104` * There will not be any multiple flights between two cities. * `0 <= src, dst, k < n` * `src != dst`
Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move.
Array,Breadth-First Search,Matrix
Hard
null
252
Hey hello there today I'm looking at the two meeting rooms question the first one is 252 meeting rooms so we got up a bunch of different meetings each habits on starting 10 times so the input is a list of tuples we want to determine if I can attend all of those meetings so since we are good person so if we decided to attend the meeting we sit there for the entirety of it you know take notes provide feedbacks I'd be a good person so we have to sit there for the entirety so if there are two meetings that are overlapping with each other maybe even a slightly overlapping in terms of the time we would have be able to go to both of those meetings so we have to give up one so then this question basically translates to detective there are overlaps so obviously they're the blue first solution is to check all the pairs of humans meetings and see if they overlap but that's not how humans normal human being would do if we are in that kind of situation what we would do is to pull up the calendar app and just to scan the meetings from based on the time order what do I have in the morning what I have you have to know what I have in the tomorrow the reason for that is there's the tomorrow's meeting is never going to be able to have any sort of conflict with the meetings I have today unless I'm having oversee multinational meetings so I have to sacrifice my you know long time otherwise I would just sort of my meetings in the time order and to see if there are conflicts in the adjacent two meetings so that's pretty much how we gonna solve this we're gonna solve them sort of meeting based on their starting time and then do an second pass to check the adjacent to means to see if the second meeting starts before the first meeting has ended so that's the only possible overlaps if we resort all those meetings based on their starting time so a sort and a linear second path so the time complexity is going to be dominated by the sorting part which is going to be n log n if we do it in place sort it's going to be a constant space so let's cut this thing up it's a pretty simple question so we're gonna sort this from the beginning to the end of course and the comparator is that for two meetings we're going to sort by their beginning starting time so that's the sorting part then we check the adjacent meetings so if the current meeting we are looking at has a starting time that's actually earlier than the previous meetings ending time we gonna that means we couldn't attend at least one of those to return false otherwise we're just going to update these previous meetings and time to be this one so we need to initialize this to be something really small yes if we don't early return inside this for loop that means there is no conflicts we can attend all of those meetings in the end we return true so that's for this question so let's look at the second one 253 meeting room 2 we still got a bunch of meetings they all have their starting diet end time but now no real changes we are not no longer going to those meetings but we sort of like a office manager we try to have people to grab all those conference rooms they need to host their meetings but we want to organize this in a way such that the number of room required is limited to the minimum as possible maybe we are charged by the number of meeting rooms we use every day so for the incentives we want to minimize the number of total number of rooms we used it for to satisfy our employees meeting requirements so how we go about to do this just think of if you really are this kind of office manager person people come to you and they say I'm about to have a meeting start you meet effectively immediately and they were ends in one hour would you do what would you do it would go about and see there are kind of empty rooms that's available and just have that have the person to occupy that room so this leap actually leads to the reasonable solution just we as the office manager which is kind of at anytime there is a new request for duration to use the meeting room immediately are we gonna do is just the check do we have any kind of available room if we do have one we just let the person to occupy that and we note on when the room is gonna be available again so that we can use it for some other team some other meetings if there are no room that's available we're gonna grab a key and open up a new one to this person so basically we've gotta have a ledger or in our mind we keep track of the current and number of rooms that we open and allow the employees to use for meetings and when there are new Cresta coming we try to check if they're any kind of available room and if there are we're just gonna have the employee to occupy that room so the minimum number of conference room is just the number of rooms we number of keys that we grab to open the locks to a lot of people to use it so to be efficiently to be able to efficiently find out which room is available is the part that's going to be it's going to be crucial to this problem because if we do linear scan to check the ledger which meeting starts at the what time which meeting ends up what and use that to figure out can I have the guy to go to that meeting role that's going to be a little bit we see so instead of doing that we're gonna use a priority queue so the top element the gatekeeper can be the meeting room that's gonna be it's gonna be the earliest available meeting room so all we need to do is to maintain that whenever there are new repress to coming in we're just gonna check the new requests to starting time with the earliest available room if the new request is a starting time is earlier than the earnest available rooms so if that's the case we'll definitely need to open up a new loan so that's how we saw this yeah so it's just going to use a priority queue to keep track of the rooms based on their earliest available time and we're going to process the requests based on their solar order of their starting time yeah so that's a pretty much it a the time compacted it will be to multiply by n log n the reason being that we sort all those meetings based on their starting time so that's a login and for the you know prior to kill stuff whenever there is a new request for me we're gonna iterate over all those we all those meetings so it's in multiplied by something and each time if we do have to do some kind of insertion and on Q and D q4 prior to kill the complexity is log n so that's n log n another n log n in the worst case so to multiple to sorting that's n log N and the priority queue scanning through the meetings iterating over the overall the meetings and to the potential on QT q operation that's another n log n so the total time is two multiplied by n log n for space we at most keep track of the number of meetings in the priority queue that's when in the really unlucky case all the meetings just happen at the same time and at the same time so they're all gonna be occupying their own meeting rooms that's the case when we have a linear in space yeah so that's a pretty much it yeah so let's cut this up we're gonna borrow this sorting part because this shared part from that prior question and everything else happening is gonna be different priority so for C++ we have different priority so for C++ we have different priority so for C++ we have the type the container type we're using a vector of integers the stuff that we put on the priority queue is only going to be the end time and time for the meetings because the end time is the available time for the room again it's the time that the room will be available again so we're gonna use the mink you mean priority queue so the gatekeeper the top the front element on the private key is going to be the early in the room that's gonna be earliest available again so if there are new meetings coming in we just compare that thing so it's actually a little bit tricky is that the priority queue here is by default system it's a maximum so it's the comparators less and it's implemented as maximum Q maximum priority Q so for that reason if we want to have the product a supercilious priority Q to be the main priority Q we have to do a greeter comparator so that's pretty much the only tricky part here so then we're just gonna iterate over all this meeting requests and what are we gonna do is to check do we have sorry do we have a meeting room available or potentially available to us so that's the priority Q is basically going to be the meeting rooms that we grab the key and opened let it be available to the employee for today so if it's totally empty if it's not empty with meaning that we have already opened some room that's being prior occupied that can potentially be freed up we're gonna check if this newly request the meeting is a starting time and it's after the it's after equal to after the first available meeting role so if that's the case we can free up that room and use that room for this part of this meeting otherwise or just so basically here we are saying that the meeting has got the first available room we clear it up so that the new meeting can occupy that room so for that we push the end time to that room if we don't trigger this that means we either have no that pretty much means that we don't have available room so we have to open up a new room so the priority queue size will grow larger in the end we were just returned the part of the size of the priority view yeah so that's a pretty much the question using prior to queue let's see okay what's the problem okay it should be this all right yeah very slow again I'm not sure why but yeah the time complexity as you can see here the sort is n log N and we iterate over all of those meetings in each generation we can potentially needs to do this pulp and push so both log n so that's another ill log in so it's potentially 2 multiplied by n log n the space is the size of the priority queue that can potentially be linear with respect with all the mean in the new meeting numbers so that's this question using priority queue right
Meeting Rooms
meeting-rooms
Given an array of meeting time `intervals` where `intervals[i] = [starti, endi]`, determine if a person could attend all meetings. **Example 1:** **Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\] **Output:** false **Example 2:** **Input:** intervals = \[\[7,10\],\[2,4\]\] **Output:** true **Constraints:** * `0 <= intervals.length <= 104` * `intervals[i].length == 2` * `0 <= starti < endi <= 106`
null
Array,Sorting
Easy
56,253
141
Good Morning America today we are going to solve the daily leak code challenge question 141 linked list cycle this is a easy question and you could have a read through it I already took a look at the question and the solution for this problem can be easily solved with two pointers and the Floyd's algorithm oh this ain't it no that is not it or it's called the hair and Tores algorithm cycle detection or Flo's cycle detection algorithm whatever it's called it has so many names and yeah you could read into the explanation I'll leave this Geeks for geeks Link in the description but basically it's done with two pointers we have a fast pointer and a slow pointer and the fast pointer moves twice as fast as the slow pointer and at any point if the fast pointer is equal to the slow pointer then we have a cycle or return true and we need to have a way to break out of the loop and that is to check if the fast pointer is not null and the fat pointers next is not null so let's quickly code this so we need two pointers fast and slow and we'll assign them to the Head pointer and now we need a while loop to continuously check and the loop will be if the fast pointer is not no and if the fast pointer is next is not null so while fast and fast. next then fast equals fast. next slow equals slow. next so the fast pointer moves twice as fast as a slow pointer so we move slow pointer once and we move fast pointer twice and then we check if slow equal goes fast then we return true and if this wall Loop is no longer valid then we will return false and that is basically the Floyd's algorithm hang on I might have missed something here fast equals slow equals head while fast and Fast that's next slow equals slow down next fast if slow equals fast turn true turn false okay bam there you go thank you see you tomorrow peace out
Linked List Cycle
linked-list-cycle
Given `head`, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**. Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** false **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Easy
142,202
1,462
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 daughter's I'm coding they've been explanation near the end and for more context there'll be a link below on this actual screen cats of the contest how did you do let me know you do hit the like button either subscribe button and here we go cute we call scheduled for so this one was also kind of straight for it the prerequisite and the course schedule name might lead you to think and that's what I was thinking initially to do sometimes I am a table logical sort because well that's what a lot of these problems are right but it but the first thing that I did was that you give me a lot of queries so I just want to make sure that n is good enough and it's not the best and a hundred and once I got a was like this is a topological sure this is just curly thing right and I was thinking well that's just all pairs like every pair can you for every vertex can you get to another word text given a prerequisite right and they only tells you that the prerequisite grab-ass tells you that the prerequisite grab-ass tells you that the prerequisite grab-ass no psycho no repeated graph so what I end up doing what I end up implementing is this album called wall Shores album and basically I create an adjacency matrix and here right now I'm actually looking at the inputs because I wasn't sure which direction is going well and what I mean my dad is but a goes to B or B goes to a as the prerequisite actually pry didn't really matter but that's what I was spending my time on you I was looking at examples just to make sure but I was like why it really could have just given one example I would make my life happy but uh but some excuse me some days you're just a little off and I guess that's what happen here they're basically the prerequisites list just their edge list this allows me to populate the adjacency matrix and then now I just use Warshaw album it's kind of like Ford washers album but it's just war sure because this is not you this is what is core answer of kosher and as you can imagine it because in the graph it uses something called the transitive property and I mean that if a implies B and P implies C then a implies C right and what shows album is what you use to find the transitive closure of this graph and then I was like okay I have to do anything funky no I guess I just have to put it in an answer way because it's just boolean anyway and then I spent some time which is maybe a little bit sad as well just double-checking the answers like just double-checking the answers like just double-checking the answers like one by one and I really wish that they you know have a checker for you for example cases but one test I submitted it was good I was ready half cool cute two-week course schedule for there are a two-week course schedule for there are a two-week course schedule for there are a total number of end courses oh yeah so this one I spent some time so I spent about three minutes or less than three minutes on this problem so I spent some time with this problem just trying to figure out what the prerequisite pairs are because it actually doesn't and I guess here it tells you here but I was trying to look forward in this statement which one is which like given a prerequisite peer is it the first number that depends on the second number or the second element that depends on first template and it's kind of sticked in here but I know I trouble reading it to be honest but the idea here is that you have all these pairs and then our prerequisites and then later you have to do queries on them right you see whether there's a prerequisite and the idea that I use it's called the forward wall show album and basically what it does it also helps for shortest paths but in this case I guess actually it's not the Ford warshall algorithm it is just a wash or anyone because this is the boolean version of it where we're basically if it goes basically it takes advantage of the transitive property meaning that in this case for example in example do we well it actually but basically if a has a prequel prerequisite of B &amp; B but has a prerequisite of B &amp; B but has a prerequisite of B &amp; B but has a prerequisite of Z C then a has a prerequisite of C so to transfer the proper age generally and from dad you could use the war shows album that it up there you go google it's a you could say a boolean version of the floyd-warshall salim that came and a floyd-warshall salim that came and a floyd-warshall salim that came and a little bit earlier yeah but I did first when I saw this problem take a look at the ends and it's a hundred so I knew that a hundred Cube would be fast enough and you know there'll be a lot of queries all these curves are or one look up and adding it to their way as opposed so I did not have I do not worry about wedding time I don't have to sing any good 100 and this is n cube for very obvious reasons and n of square space also for obvious reasons yeah but this is for well sure this is war shows album specifically and it is pretty straight for it well it's pretty straightforward application of it but do you know I'll have a link somewhere so that you can learn more about war shows album Oh
Course Schedule IV
list-the-products-ordered-in-a-period
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 `ai` first if you want to take course `bi`. * For example, the pair `[0, 1]` indicates that you have to take course `0` before you can take course `1`. Prerequisites can also be **indirect**. If course `a` is a prerequisite of course `b`, and course `b` is a prerequisite of course `c`, then course `a` is a prerequisite of course `c`. You are also given an array `queries` where `queries[j] = [uj, vj]`. For the `jth` query, you should answer whether course `uj` is a prerequisite of course `vj` or not. Return _a boolean array_ `answer`_, where_ `answer[j]` _is the answer to the_ `jth` _query._ **Example 1:** **Input:** numCourses = 2, prerequisites = \[\[1,0\]\], queries = \[\[0,1\],\[1,0\]\] **Output:** \[false,true\] **Explanation:** The pair \[1, 0\] indicates that you have to take course 1 before you can take course 0. Course 0 is not a prerequisite of course 1, but the opposite is true. **Example 2:** **Input:** numCourses = 2, prerequisites = \[\], queries = \[\[1,0\],\[0,1\]\] **Output:** \[false,false\] **Explanation:** There are no prerequisites, and each course is independent. **Example 3:** **Input:** numCourses = 3, prerequisites = \[\[1,2\],\[1,0\],\[2,0\]\], queries = \[\[1,0\],\[1,2\]\] **Output:** \[true,true\] **Constraints:** * `2 <= numCourses <= 100` * `0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)` * `prerequisites[i].length == 2` * `0 <= ai, bi <= n - 1` * `ai != bi` * All the pairs `[ai, bi]` are **unique**. * The prerequisites graph has no cycles. * `1 <= queries.length <= 104` * `0 <= ui, vi <= n - 1` * `ui != vi`
null
Database
Easy
null
1,802
hi friends uh welcome to follow up let's have a look at problem 1802 maximum value at a given index in a bonded array this problem actually is a standard application of binary search so here we are going to explain the thought process first we are given three positive integers in integer and Max of sum and we want to construct an array nums uh here it emphasizes that it's zero indexed so we want the array to be satisfying the following conditions first the length is n and the index I the not at index so for at every index so the number num's I is positive and the neighboring element has a difference less than or equal to 1 in absolute value so and also the sum of all the elements does not exceed Max sum so also we want to maximize the element as a gaming Index right so we want to return the numps index of the constructed array so here are two examples so in the first example so at index 2 here we have two right so here the array is one two one so the sum is 6 is equal to the given Max sum this is a valid one and the return value is 2. so if we set this value to be 2 actually for the element at index 1 we can set it to be one which is also good so this is the first example for the second example the output is three so you can actually try to construct one valid array so now the constraints for the problem are the following first n is bonded below by one and bounded by the maximum and then bonded by 10th power on them and the index is inbound so this is just for consistency so with that stage we are ready to explain the idea so here actually if we have practice the allowed problems a lot of problems on binary search actually once you see this problem statement basically you can have a fitting on how to use balance first here so here first we are going to transform the problem to be the following so we want to set max key such that the list in Array at index give here so its value is key and also we want it satisfies that the sum of the array is bounded above by the max sum so if we transform the problem into such a statement so this is a standard binary search pattern so here the question is how to check if we can construct the valid list in Array right valid in the sense of this bullish items so in one sentence we can set the array at index to be key and then we try to decrement the value by one recursively in both sides of the index uh if the value is positive we just set it as it is otherwise we set the value to be 1. so once we set the values actually we could easily compute the result and then we just need to compare the computed sum s with the maximum sum if s is less than or equal to the maximum it's good so means that we can construct valid uh let's in Array otherwise we cannot construct valid and array so once we realize this point and then we can basically run a standard binary search Paradigm so here in order to make it more clear let's further elaborate the process so here let's assume we have index 2 and N is uh four that's first not specify the maximum so if we have a 3 at index 2 right so then this one here none so we can because of this difference requirement we can set it to be two the reason we set it to be smaller than this value is that we want the sum the total sum later is bonded by maximum so we set this to be 2 and then we set this one to be one right so here we decrements by one that's the two so we get such one such a array so the sum is eight for example if you have a maximum that is 10 so this is the valid one but if you have a Max sum it's that is 7 this is not a valid one right so here if we have this one this is two then we decrement by one so we're going to get one but we cannot further decrement because we already meet one and we need the numbers to be part relative then we can set all the Press ones to be 1 right same for here so here we set it to be one and if we still have further indices to the right we need to set those indices to be wet and in this example the sum is 5. if you have a Max sum that is 7 for example so this is the value one and if you have a radish sum maximum sum that is 4 this is not validable meaning that if I set this to be 2 this number is too large I cannot construct a valid array so um this two paragraph paragraphs basically explains how to verify if given a value key at the index can we construct valid array right if that's possible then we want to mix the key as large as possible so here is our plan so first I'm going to write a Boolean function to produce monotonicity so this is a needed for binary search right we need certain monotonicity so here I'm going to call this function fulfill so it accepts uh four arguments so this I naught is the index you can think of it as index and it will be the length and the max sum as its name suggested will be the upper Bound for the sum of the of a valid array so K is the value we are going to set at the index and not right so the in plain English this function checks if we could construct valid length n array with the value at index nodes to be K and the sum is less than or equal to maximum then what the problem says or requirements is to fetch the max key such that this function is true right or just a see this is true then this key is a desired return so here before we write its code let me make one more comments it's actually easy to notice that given n and Max sum if we set this element too large then due to the absolute difference requirement for adjacent elements then the array sum would be too large actually can exceed the maximum sum that's why we want to find the largest possible still making this fulfill function right so if we have already purchased the above sort process writing the code is sort of routine so first I'm going to register the utility function to produce monotonously this basically is using a 3D method or in a greedy manner so here I left let's define fulfill so it accepts K we want to set the value at index and not to be key and this is the lens and this is the max sum all right so the return will be a Boolean right so the meaning is here right so now let's look at the function so here basically we want to set that to be K and then set the values compute the sum and then compare with the max sum so here we need to play with the indexing right so let's first initialize the value at the very beginning zero right so we are going to compute the sum from the beginning up to index a node and then we compute the sum from anode up to the end of index then this way we compute twice the value at I naught then we're going to decrement by K after we add the two parts together so let's look at the detail first if K is greater than I naught right this greater than or equal to 1. so this means that we can decrement to the left to set as K minus 1 Q minus 2 up to K minus and nodes right in this case the left part sum starting from index 0 up to index and node will be so this is the beginning one at index zero and this is the one at index uh and not and then we multiply the number of terms that is I naught plus one and then we do into the division by two right otherwise so if this is already non-positive then so if this is already non-positive then so if this is already non-positive then we want to set some of them to be uh one so basically what we have is one part is from 1 to K rate and then all the other terms is said to be wet so from one to key there are key terms right so let's first compute the sum of this part as 1 plus K times the number of terms integration by two then from index 0 to node there are in total I naught plus one terms and there are K terms said to be 1 2 of 2K then all the odd terms are set to be one so that's this part and not plus one minus k so this is the left part including the value at in index and naught so similarly we can compute the sum from anode inclusive up to the end so notice that to the right how many terms so the index will be n not plus one and the ending at n minus one so the number of atoms to the right of the index and also will be n minus one minus nodes plus one then Plus One Rate so this number is nothing but n minus 1 minus and not so now let's look at the counting first if k is larger than this number of terms is greater than or equal to 1. it means that we can set the values of the red di by recursively decrements of K value by one so at the end index and management is still positive in this case the result so or the sum of this part will be the last term that is e and minus nodes minus one so then we are going to so this one term so we're going to cross this one this is the value at index a node then we're going to multiply the number of terms that is uh n minus naught right so you can contact this left to the node there are I noticed atoms in total we have enter in atoms so we the to the right and including I naught we have n minus n of terms so then we divide by two right let's see this is the first term right and this is the beginning term at uh I naught this is the term or the value we set at index and minus 1 then times this one into the Rhythm by 2. Otherwise so we want to compute uh K terms to be value 1 2 of 2 K and the other terms are set to be one so the results will be something like this so 1 plus k uh times key into division by 2 plus because we have n minus N Out terms in the rate and then their K terms are said to be one Optical in other terms are said to be one so this block computes the sum from the beginning index up to index and not inclusive and this block computes the sum starting from index anode to the end so this way we compute we use twice the value at index and out then we are going to do this one minus k so the final state of this result variable will be the sum of the array we construct on the error right so now we just need to return if the sum is bounded by Max sum if so we see that if we set the value to be key at the index node or we can do such a thing then the question is to be the second step so we want to find Max K such that this function as true so here in the we want to use this one because this is the gaming Index right so for above we just need to use I naught for the convenience of reading so now let's run the binary search so the first step is to determine the search range so low and high so low will be at least one because we want all the numbers to be positive the high will be the max value right so we're going to use max of norm or actually this will be better Max sum right so this one term will be already equal to the max sum largest number of some a lot and then we are going to do the shrinkage right so this is the search space or search range and then the shrinkage for the shrinkage that's because of this if low is less than high strictly here so we are going to do the shrinkage because here we are going to I'm going to shrink from larger to smaller the reason is that if it's too large so this function will be false right so I'm going to do high minus High minus low inter division by 2 right so if fulfilled so I'm going to change this to the mid and the index is the argument to pause and this in right and this maximum if this is true it means that we can construct valid um array using this mid as a value so in this case we are going to set low to be mid so notice that this we are writing so as a as the value low right it always makes this function true so otherwise so if this is not I'm true it means that the mid is still too large so we're going to set High to be mid minus one so here we have to be made minus one because mid actually makes this function false right so this way we're going to return low at the verb and very end because low also always make this true uh this is the full uh this forms a full solution format to this problem so now let's first do a test yeah it passes the first example now let's look at the generic case yeah that's about it for this video so before we end the video Let me give a quick remark on this on the term complexity so here basically the fulfill function is basically o1 right once you give me the key and not n and the maximum we can give a make a judgment so the main time comes today is for the number of cost of this function so is it because this is band research this will be logarithm 2 and at this value right so let me comment here logarithm 2 of this Max sum actually minus 1 right so this but up to a constant so we can assume that the maximum is very large compared to one so this will be the temp complexity overall so with that said that's the end of this video thank you
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
410
hello friends now less of the blade or a large sum problem there's a statement given ray which consists of non-negative given ray which consists of non-negative given ray which consists of non-negative integers and an integer M you can split array into m non-empty continuous sub array into m non-empty continuous sub array into m non-empty continuous sub arrays write an algorithm to minimize the largest sum among these M sub arrays let's see the example we are given the 7 2 5 10 8 we want to supply to this array into two parts and there are through calculation we can know that sir if we simulated this array into 7 2 5 and can eight we will get the minimum largest sum between this M sub arrays which is 18 so how to sing about this problem to be honest I cannot relate relates as this province your binary search but the optimal solution of this Robin is actually binary search so if we are given a hint that we can use binary search how to you thing about it last thing about the situation that we can use a baños research that is we have such we have a search branch and there are the elements should be sold here so for this question how do you find the search range last thing about it we are given this array what is our minimum pieces if we split it should be 1 right we do not actually splitter we just let the whole array ends or suburb so the minimum species is 1 what about the maximum pieces we can treat every elem as one suburb so basically this array can be see like the like is a five sub-arrays right every element is a sub-arrays right every element is a sub-arrays right every element is a sub array so in this case it should be and is the elements in the numbers so respectively what's the largest isang what a minimum of the largest are among these M sub arrays if we only see it as one suburb than the minimum largest zone between these unsub's should be the sum of the whole numbers right the same if we treat every element as a sub array the largest sum the minimum lattice on between the sub array should be the max elements in the numbers so this is our searches slope it actually should have been the max thrones or max to the sum of the numbers but how do you do binary search we can do like this we are even a upper limit which means we can split this array into pieces but the concern is that of the largest asam the largest stop between the this the sub arrays cannot or exceed this value and we see if we're given tis a constraint how many pieces can we sublated this array into if we can split this array into like we want to capture the pieces right if the piece is greater than M which means the largest sum is too small we should mmm we should make this value larger and then try to make the pieces uh less oil cozinha em so let's do it hope you can understand my poor English so first our gets the site of the numbers and as I said that we need to calculate the maximum we initialize to zero and we also need to calculate some initial to 0-2 and there we iterate so initial to 0-2 and there we iterate so initial to 0-2 and there we iterate so the numbers are read right every time updates as our max value max and the current number and a we accumulate the number to the south so now we have the two bunk which low is the max and I will be the Sun you know we do the binary search low equal less than the height refers to casimiro video value should be the low plus the high minus low over 2 and we want to see how many pieces that can we split it we call another function numbers and there's a constraint is that other erase sub arrays cannot there some cannot exceed this middle and we see how many PC can we get if the pieces is greater than M which means they're some it's qu small right there I mean the limited to small so we will we Uppercross these limits so low where you got your middle class 1 in for the pieces les oiseaux gender m which means a de campagne so very long so we just let a higher me go to the middle finally we just are returned this law actually low post slow in Highness is correct because low in the end low equal to the Hat so okay so less employments of these split of we'll use the numbers and there's a there will be the largest system right so we will return the PCs at least the pieces will be one right so we do noticeably split each and the temporary son alpha is equal to zero then we iterate this number array if the temporary son plus these numbers is greater than the largest solution is either you exceed so we just left so the temporary some people choose a number at the same time we let the pieces plus because easily we master split them we can't just penalty's number into true the such if another case we just appended this number to the temporary son finally return how many pieces can we get hopefully you can understand this binary search solution see you next time
Split Array Largest Sum
split-array-largest-sum
Given an integer array `nums` and an integer `k`, split `nums` into `k` non-empty subarrays such that the largest sum of any subarray is **minimized**. Return _the minimized largest sum of the split_. A **subarray** is a contiguous part of the array. **Example 1:** **Input:** nums = \[7,2,5,10,8\], k = 2 **Output:** 18 **Explanation:** There are four ways to split nums into two subarrays. The best way is to split it into \[7,2,5\] and \[10,8\], where the largest sum among the two subarrays is only 18. **Example 2:** **Input:** nums = \[1,2,3,4,5\], k = 2 **Output:** 9 **Explanation:** There are four ways to split nums into two subarrays. The best way is to split it into \[1,2,3\] and \[4,5\], where the largest sum among the two subarrays is only 9. **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] <= 106` * `1 <= k <= min(50, nums.length)`
null
Array,Binary Search,Dynamic Programming,Greedy
Hard
1056,1192,2242,2330
1,670
hey everybody this is larry this is me along with q3 of the biweekly contest 40 design fun middle back q uh hit the like button hit the subscribe button join me in discord let me know what you think about this farm i think it's a really cute problem and as usual this these problems require a bit of um figuring out what the invariant is and then variant is something that doesn't change after you do one of these operations and for me the way that i thought about during the contest was that okay we have to push something to the mid and we have to pop something from the mid so the easy way for me just to think about it was just to have two cues right but even having two cues there are a lot of things that we have to kind of maybe not live but a few things that we have to consider which is what is the invariant that we're trying to hold with two cues right for me and this is why i took so long in this problem is thinking about that problem so i have two cues or decks in python and my invariant is that um the left cue is always going to be at most one less than the right q right so either they're equal or the left is one less than right um so why did i want that um i want that so that you know so let's just say we have something like you know one two three on the left and then four five six on the right so there are only two scenarios right one is uh when they're equal and then when we want to get the mid we get it from the left side right here right and then the other cases let's say we have odd numbers well in here then when we pop the mid when they're not the same we get it from the right side right so that's basically how i think about those cases and then once i do that um i basically after i do everything i just make sure that doesn't wear and holds which is that the left and the right has the same size or the left is once more than the right and once you do that once you figure out that variant all the operation all the operations um will follow through you just have to kind of make sure that's the case every step of the way um so for example push one is easy you just push it and that's why i have a function that a helper function that i call fix terrible naming for sure but what fix does is that it goes over the two cases right one which is if the left is bigger than the right um then we pop one from the left and then we put it to the right side um and if the right side is uh bigger than the left by more than one then we take it from the right and push it to the left uh this is kind of similar to um the rowing median problem if you're familiar with that with two heaps but that's basically the idea that i kind of dealt with um and yeah looking at front now that we have this fixed function that does this fix um then you know we can do this along the way and sometimes and i actually sprinkled it everywhere because i wasn't sure if i could keep on needing it and you know it affects performance a little bit and we'll go over the complexity of this inner psych but that's basically why um so push one you have two cues you can think about what push one is you just push it to the left key um and that's it and then you fix to make sure that variant still holds afterwards uh push middle as we said um it doesn't really matter which one you push because the fix function will fix it for you um so you just have to push in one of the middle ones uh i just chose the left one by for fun it doesn't really matter uh you could as long as you push it to the back of the left one or the front of the right one the effects function would fix it for you uh push in the back is also similarly trivial because once you um push it to the uh you know on the right side you know it'll just fix it for you right just push it at the way and then the pop fonts are interesting now right so you have to check that you know if there's no elements that means if the left and the right are zero then you negative one i some of these cases i just made sure that for myself uh because i am not when i implement this during the contest i was to be honest really not confident and i spent a lot of time uh testing this during the contest which is what it took the bulk of the time and you could watch me during the contest for that to kind of see that how i test this as well and to visualize it so i could at least have some confidence because every long end is five minutes and i don't want to get into a thing where like i'm fixing one thing and then fixing like five things right and then it ends up being like a terrible contest but um but yeah so for popping front i if there are no elements negative one if there's a left um and we know that we don't have to check that the right doesn't have any elements because as i said then wearing is that the idea they're the same which means that they both have zero elements or this or the left has zero elements and the right has one element right so we just check to see if the left has zero and if that's the case we take it from the right and we pop uh we should actually also fix this but i think this only ha but we don't even need to do the fix because this only happens if the right um has only one item and the left has zero item because of the invariant and we know that everything to be true then this will just be zero items otherwise uh for me i just popped it from the left and then have it fix itself afterwards i don't even think i need this one to be honest but i am i sprinkle them liberally because these are cheap and we'll go with the complexity and how much these cost later um but yeah pop middle is a um okay let's do the pop back first because it's also easier or more obvious uh and you can see what i did here is that i actually tighten up the code that i don't even need to check here because uh on the pop back the right is the element that has the extra elements so if obviously if there are no elements you return negative one otherwise you just pop one from the right and then we fix it afterwards to basically balance the left and the right uh and before just in case i don't think it's necessary to be honest but i just kind of do it there uh and then pop middle is the fun tricky one which is then you know we go over all the cases right if the no items return negative one we talked about this should be straight forward uh otherwise we make sure that the existing reverend holds again because we do it at the end every time i don't think this is necessary but i like to be careful especially on contests because sometimes you rather that you don't have to prove things um than wasting five you know getting a wrong answer getting five minutes right um and then the other case is okay so the only two cases as we said in this invariant which is that there yiko the eco again we already talked about this we pop from the left and if they're not decoded that means that the right has one more element so you pop it from the right um and then we fix it in variant after that um i think technically you don't actually need to because this is this ensures that it runs to be true but again i just like it's almost free so i keep doing it especially given that this at most a thousand cores it's gonna be fast enough okay let's talk complexly right so uh so this one it's a little bit weird i wrote it as a while loop just because i wasn't i was too lazy to prove it so i knew that this was mostly true but this could be actually written as an if statement because if you keep on if the invariant is true and you only make one change this can only be one thing our place right so yeah so this fixed uh function let's go over this is going to be o of one because at most you're popping one item and that's gonna be all one and then pushing it to the other queue right so you have two cues you're taking one element and then pushing the other cube so and obviously both these things cannot be true even but even if it was both can be true uh you only do like two operations for each element so this is gonna be o one right so now knowing that this is o of one um we can kind of look at it that way right now push left we know that this is of one because we just push one item so and this is also one so this is all one uh same reason this is all one because all these are all one operations same for pushback uh same for all these things and you could kind of go for these yourself as well which is that all these are true that these are over one operations and these are all one operations so all in all together every chord is going to be o of one and you can't really do better than known ones so that's all i um and yeah and space of course is going to be of n where n is the number of items because again you have to store the items so you cannot be so that is the lower bound you cannot do better than that so in terms of space total is going to be o of n per operation is going to be o of one you could say of n for or foreign operations um but yeah that's all i have for this problem feel free to watch me uh attempt this problem live during the contest and you can kind of see how i do the testing as well uh usually to be honest i don't do that this much testing um but this one it just feels like there could be a lot of weird uh off by one so i really wanted to make sure to be confident um but yeah you can watch me sell it live during the contest now push what is middle just um hmm okay that's five when did you put it this also needs some really bad well this will be annoying foreign you it's not that's not the case it's okay i just wanted my confident about to be honest that's not good enough let's see come over test case this is really hard to construct a text test case yeah i thought that would happen okay yep this isn't even divided i'm fixing anyone um oh wait let's see it's such a annoying thing to test for one okay um good that's good okay it doesn't work go to okay did i miss one yeah okay uh hey everybody uh yeah thanks for watching uh let me know what you think uh ask me questions because that's the only way i'm gonna know how to answer them in the future uh hit the like button hit the subscribe and join me on discord and i will see y'all next fall bye
Design Front Middle Back Queue
patients-with-a-condition
Design a queue that supports `push` and `pop` operations in the front, middle, and back. Implement the `FrontMiddleBack` class: * `FrontMiddleBack()` Initializes the queue. * `void pushFront(int val)` Adds `val` to the **front** of the queue. * `void pushMiddle(int val)` Adds `val` to the **middle** of the queue. * `void pushBack(int val)` Adds `val` to the **back** of the queue. * `int popFront()` Removes the **front** element of the queue and returns it. If the queue is empty, return `-1`. * `int popMiddle()` Removes the **middle** element of the queue and returns it. If the queue is empty, return `-1`. * `int popBack()` Removes the **back** element of the queue and returns it. If the queue is empty, return `-1`. **Notice** that when there are **two** middle position choices, the operation is performed on the **frontmost** middle position choice. For example: * Pushing `6` into the middle of `[1, 2, 3, 4, 5]` results in `[1, 2, 6, 3, 4, 5]`. * Popping the middle from `[1, 2, 3, 4, 5, 6]` returns `3` and results in `[1, 2, 4, 5, 6]`. **Example 1:** **Input:** \[ "FrontMiddleBackQueue ", "pushFront ", "pushBack ", "pushMiddle ", "pushMiddle ", "popFront ", "popMiddle ", "popMiddle ", "popBack ", "popFront "\] \[\[\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[\], \[\]\] **Output:** \[null, null, null, null, null, 1, 3, 4, 2, -1\] **Explanation:** FrontMiddleBackQueue q = new FrontMiddleBackQueue(); q.pushFront(1); // \[1\] q.pushBack(2); // \[1, 2\] q.pushMiddle(3); // \[1, 3, 2\] q.pushMiddle(4); // \[1, 4, 3, 2\] q.popFront(); // return 1 -> \[4, 3, 2\] q.popMiddle(); // return 3 -> \[4, 2\] q.popMiddle(); // return 4 -> \[2\] q.popBack(); // return 2 -> \[\] q.popFront(); // return -1 -> \[\] (The queue is empty) **Constraints:** * `1 <= val <= 109` * At most `1000` calls will be made to `pushFront`, `pushMiddle`, `pushBack`, `popFront`, `popMiddle`, and `popBack`.
null
Database
Easy
null
334
and today we are going to talk about longest triplet subsequence in this particular example one two three can be one of the longest triplet subsequence or it can be one three five or it can be one four five anything for this matter but the whole question is how do you find out the idea to find out is like we keep a variable called First with Max and second with Max and we iterate through all the element and keep replace if the value whatever we store it here if it is bigger here then replace with the smaller element in this particular case take one check whether f is bigger than one yes in this particular SF is bigger than replace the position then move on to the next variable check f is bigger or not no it's not bigger in this particular case then move on to the second variable then Check Yes f is bigger S is second variable s is bigger than replace with the position then move on to the next question So currently it's three check f is bigger or not no f is not bigger then move on to the second variable check s is bigger or not no in this particular case no then the third variable is actually three whenever you find variable third that means we have find out the first two variables already that's the idea behind it take this example okay let's take this example two one five zero four six okay first variable we keep Max second variable we keep Max two first come and check with variable f is bigger then replace 2 move on to the second variable one check f is bigger yes f is bigger and then replace with relay value then move on to the next position check f is bigger or not in this case no because we have 5 here then more the second variable check Phi is s is bigger than 5 or not uh yes then replace it and keep 5 and move on to the next position 0 check f is uh bigger than f is bigger than 0 or not yes it's bigger than replace 0 here then move on to next position four check f is uh bigger than 4 or not no in this case no then check the same variable with second variable s is bigger than 4 or not yes it's bigger than replace with 4 then move on to the next position and check EF is bigger than 6 or not no this then move on to this variable s and check whether s is bigger than 6 or not no then the third variable is 6 we found 0 4 6 and this is the increasing order then be written true this is how we solve this problem thanks for watching
Increasing Triplet Subsequence
increasing-triplet-subsequence
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`. **Example 1:** **Input:** nums = \[1,2,3,4,5\] **Output:** true **Explanation:** Any triplet where i < j < k is valid. **Example 2:** **Input:** nums = \[5,4,3,2,1\] **Output:** false **Explanation:** No triplet exists. **Example 3:** **Input:** nums = \[2,1,5,0,4,6\] **Output:** true **Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6. **Constraints:** * `1 <= nums.length <= 5 * 105` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
null
Array,Greedy
Medium
300,2122,2280
142
welcome to my Channel today let's solve another lead code problem 142 English cycle 2. so continued with the English cycle 1 so cycle 2 is more difficult than cycle one so basically the problem is giving also like that we are giving a linked list and there's a cycle inside a cycle and return the index position of the cycle so this position is designed inside the algorithm so if there is a cycle we're gonna find this cycle here the position is one but for us we just need to fight the pointer for example this is the head dot next if header dot next is the point for the entry point of the cycle then without gonna return the pointer for this number two nod yeah now let me go to the Whiteboard first and then go to the code Editor to finish the coding so basically we are giving something like this yeah so we are giving something like this we have a and b point so B is the entry point so we are going to find this basically we are going to find this entry point Yeah so basically we are going to find this B entry point but how should we find it so according to linked list cycle number one we are going to use the fast and slow pointer to fight the cycle so if we have a fast pointer and slow pointer the first pointer always moves faster than the slow pointer so the first pointer moves two steps and the slow pointer moves One Step so if this D is the point where the first pointer and through pointer meet so this D is the midpoint and this B is the entry point we just need to fight this entry point B so how it goes so yeah so a b is L1 with Define a b as L1 it is a the starting point to the entry point yes and the BD is L2 is the entry point to the midpoint so it's L2 and the DB is X so we have a circle the circumference is C so C is the circumference and the DB is the distance from this D to B here yeah and so when they meet the slope pointer goes yes should be like this it will be a b to b d yeah so L1 plus L2 and plus M times C so this means when they meet we don't know how many Loops the slope pointer goes but we give a value of M so M times C so C is the circumference yeah similarly the first pointer goes L1 here and L2 here and plus this X and also Plus uh yeah here I forgot to add also plus this L2 and here also need two plus a L2 yeah because after plus this x the first pointer should also process this L2 and then plus the N times say so on is another integer C is the circum circumference so it means two times the slow pointer equals to the distance of the first pointer so the first pointer should L1 plus L2 plus X Plus L2 so here I collected yeah my error yeah and plus this n times the C so according to this formula we can get L1 should equal to X Plus n minus M times the C yeah and here we set k equal to n minus M so L1 should equal to X Plus K times C so K should always be bigger and equal than zero and K is at integer because K is how many Loops the first pointer or slow pointer goes but here K is the difference of the loops yeah but according to this K we can uh we can find the case would always be more than equal than zero because if K is less than zero for example the L1 should equal to x minus c yeah so if K is -1 we set a minus one but any is -1 we set a minus one but any is -1 we set a minus one but any negative value is okay so it means this x minus c x is here but the circumference is bigger than x so this means x minus C is less than zero and L1 is less than zero but L1 should always be a positive value it should always be more than zero yeah so here means the T cannot be less than zero the case would always be bigger and equal than zero yeah so if the k equals to zero it means one a goes to B and here this from this point from the where they meet so here it means D will go to B if it goes to one Loop yeah if it goes to many Loops so here K is always if it is more Loops it means it will go from one loop at another loop but no matter how many Loops it will finally go to the entry point B to meet with this point a and here according to they are going and also they are going to the distance so it means they can use the same speed to meet yeah now let me go to the code Editor to finish the coding it should be even more yeah easier than that it will be clear when you see the code yeah as I said I will Define two pointers the slow pointer and the first pointer so the first quarter and flow pointers should be pointed to the hand and first of all we're gonna attack where they will meet so while the first pointer exists and first dot next because here the first pointer will always move the two steps and slow pointer moves One Step so the slow pointer should equal to slow dot next and the first pointer should equal to fast dot next yeah so here the first portal goes two steps two times more than the speed of the slow pointer so finally they will meet at some point inside the circle yeah so if flow equals to fast it means they meet what are we gonna do we're gonna use a while loop to tuck so while the head is still from this point while the head not equal to uh to the slow or fast yeah here I will use the slow because I will move slow faster One Step but here if I use the fastest the first should also move one step but it's not the meaning of the fast yeah so here this is why I will use this slow so the head shoulder moves One Step head dot next and the slow should equal to slow dot next yeah so if the head not equal yeah so if the head equals to slow it means they finally meet at the entry point at this entry point number two yeah so we're gonna return the head or the slow yeah it means we're gonna find a value but what if we didn't fight with such gonna return noun so if we identified so this is the whole Loop yeah if we find a point it means at this slow or head we can return that yeah but if we didn't fight with us gonna return none because this is the return yeah if we didn't fight it there's no cycle it means we're gonna return a noun now let me submit it to Sag if it really works foreign yeah as you can see it really works and it's pretty fast now let's analyze the time complexity as I said the according to link delays to cycle one it's a neat if they finally meet that time complexity will be oh because the first pointer will always move the two times then the speed of the slower pointer it means that it will finally meet but the midpoint it will not go infinitely it will go inside and the fat border go to the next Loop and then they will meet so here is all but after that the slow pointer made Moves many steps the slow pointer from here may move the many Loops but the entry point from the head to the entry point it will only go this distance is L1 so the algorithm is also o n so on is the number of the node inside yeah thank you if you think this is helpful please like And subscribe
Linked List Cycle II
linked-list-cycle-ii
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**. **Do not modify** the linked list. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** tail connects to node index 1 **Explanation:** There is a cycle in the linked list, where tail connects to the second node. **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** tail connects to node index 0 **Explanation:** There is a cycle in the linked list, where tail connects to the first node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** no cycle **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Medium
141,287
304
hello everyone welcome to coding decoded my name is sanchez i am working as technical architect sd4 at adobe and here i present day third of june lead code challenge the question that we have in today's range sum query 2d immutable so here in this question we are given a matrix a size m cross n and we need to identify the sum of this element that lie inside the rectangle starting from row one column one up till row two column two so this question is based on the concept of dynamic programming and to all those who have been associated with the channel from quite some time might know that we already solved this question in the month of may 2021 i have clearly explained the dp algorithm in this video also coded live for you guys this question is a difficult question in case it comes in an interview and you have not solved it in the past it will be difficult for you to come up with the approach in the first go itself so i would urge you guys to kindly go through this video the like says it all the comments says it all awesome explanation here last explanation of showing the matrix made it more clear so guys do give this video a shot and i promise you will get a good hold of the underlying concept if you are interested in more complicated question than this one then you can go out for green um query mutable so this question is based on the concept of segment trees if you are not aware of segment trees of never seen a question on segment trees then go for this video here i have clearly explained the algorithm how segmentry operate in general and i promise you're gonna love the solution up this is just one video through which segmentry will become your strength so i'm attaching both the links in the description below it over to you guys do check them out also apart from this i hope you guys are aware of coding decoded data section and algorithm preparation sheet i have added important questions along with those questions i have marked the difficulty level and the chronology order in which we need to solve if you have an interview scheduled very soon then this coding decoded as the division sheet is for you guys so if you go and open each one of them you will see that here i have provided us with the basic template that gets applied in all such questions for example let's take bit manipulation in order to understand the underlying concept of bit manipulation the first video is for you then you need to revise more such questions shoot for the easy ones first then medium months followed by the hard one a similar kind of trajectory you will also see in backtracking template so the first question provides you with a template that gets applied to all the questions of backtracking in general the following questions are marked in terms of difficulty level starting from medium to hard similarly in all such questions of dynamic programming tries monotonic stacks lighting window and matrix graphs as well so if you have an interview scheduled then treat this sheet as a revision sheet to get a good hold of the concept as well as gain confidence that you are ready for the interview let me just call it interview ready sheet with this let's wrap up today's session i'm attaching all the links in the description below and in case if you have any doubt understanding any question or if you want to ask anything from me in general please feel free to drop a message on the telegram group or the discord server of coding decoded both the links are stated in the description too with this thank you
Range Sum Query 2D - Immutable
range-sum-query-2d-immutable
Given a 2D matrix `matrix`, handle multiple queries of the following type: * Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. Implement the `NumMatrix` class: * `NumMatrix(int[][] matrix)` Initializes the object with the integer matrix `matrix`. * `int sumRegion(int row1, int col1, int row2, int col2)` Returns the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. You must design an algorithm where `sumRegion` works on `O(1)` time complexity. **Example 1:** **Input** \[ "NumMatrix ", "sumRegion ", "sumRegion ", "sumRegion "\] \[\[\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]\], \[2, 1, 4, 3\], \[1, 1, 2, 2\], \[1, 2, 2, 4\]\] **Output** \[null, 8, 11, 12\] **Explanation** NumMatrix numMatrix = new NumMatrix(\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]); numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 200` * `-104 <= matrix[i][j] <= 104` * `0 <= row1 <= row2 < m` * `0 <= col1 <= col2 < n` * At most `104` calls will be made to `sumRegion`.
null
Array,Design,Matrix,Prefix Sum
Medium
303,308
427
hey everyone welcome back and let's write some more neat code today so today let's solve the problem construct a quad tree so we're given a square Matrix maybe something like this one so it's n by n and we actually want to convert it into a tree but not just a regular like binary tree actually a quad tree where every single node in the tree will have four children except of course for leaf nodes maybe like this one doesn't have any children so in this case our node is going to look something like this where it will have a value in this case I think values are just going to be either 0 or 1. it'll also have a field to indicate whether it's a leaf or not and will have four pointers for each of the four children where each of the four children will have a spot actually and this brings us to what we're actually trying to accomplish with this grid so given a square grid like this one the root is not going to correspond to any of these cells our root node of our quad tree is not going to be any of these cells but the four children of each of these roots are going to correspond to a quadrant of this grid so actually the root node can kind of be thought of as the entire grid and then it will have a child for the top left portion of the grid so think about it if this is an N by n grid how are we going to define the top left quadrant probably it's going to be n divided by 2 in height and N divided by 2 in width so that's how we're going to define the dimensions and we'll have one for the top right one for the bottom right well bottom left and one for the bottom right and recursively actually for each of these quadrants we can break that up as well you can see they've kind of Illustrated that to us over here on the top right you can see this one is broken up into quadrants as well so recursively that's what we're going to do for each of these squares we're going to recursively break it up again and again into quadrants until we can't do so anymore maybe we get to the individual cells and then for each of those individual cells we actually will be able to fill in a few more of these fields we'll be able to fill in that value so for this grid cell it'll be a one for maybe this one over here it'll be a zero and each of these of course will actually be a leaf so we'll need to set Leaf to true but there's one last shortcut where sort of required to take which is that think about this quadrant over here all of the values are one so we probably don't need to break it up further when we have a node we can kind of just prune this that's usually the word that's used which is basically to take a shortcut here and say that since all of the values here are one we don't need to take this quadrant and actually bring break it up we don't need the children we can say that this is a leaf node and all the values are going to be one anyway so we can just have a node like that so taking this entire thing the resulting tree would look something like this where we have a root node and then each of these four quadrants this is maybe the top left I'll kind of color code them orange will be for bottom left red will be for bottom right and then for top right I'm gonna make it blue because this one actually we can break up into four more quadrants top left is orange top right is white bottom left is blue I'll use like a purplish shade bottom left is blue and bottom right is purple so this is what the tree would look like breaking this up because this one corresponds to this we don't have to break it up any further the way we would know that is probably by running like a loop over this portion of the grid to see that all the values are the same so we don't need to recursively break that up any further the last thing is just a bit of math on how we're actually going to Define these quadrants we know that in terms of Dimensions if this is n this whole part then this part is going to be n divided by 2 and then when we take this part and then break it up into this portion well that's going to be n divided by 4. so basically we'll be taking whatever value we have and dividing it by two each time to get the dimensions at least to get the positions though because we know that these two have the same dimensions but the positions are different this one let's uh to keep it simple let's define each of these quadrants based on their top left position so for this one it's always going to be the origin let's say 0 but for this one over here it's going by the row and the column the row here is going to be the same but the column is basically going to be n divided by 2 plus the origin column so it's going to be 0 plus n divided by 2 to get the origin for this guy its column is going to be the same as the origin but its row here is going to be the row from here plus n divided by 2 and lastly to get the origin over here well the top left of this quadrant at least will have to get the row of the original plus n divided by 2 and same for the column we'll have to say column plus n divided by 2. so that's the bit of math now in terms of time complexity in the worst case let's say the grid Dimension is n our tree we're going to have four nodes in the worst case every single time and we're going to keep breaking this up recursively now let's say the dimension here was n well we're going to divide it by 2 every time so here we're going to get to n divided by 2 down here we're going to get to n divided by 4 and we're going to keep doing that until n is equal to one so the height of this is going to be log n now in the worst case we'll have like a leaf node for every single position in the grid so the total number of leaf nodes we could have is going to be N squared so you might think that's the time complexity but you also have to remember that at each level in the tree we are iterating over the entire tree because think about it when we have the original grid and then we break it up into four quadrants we have to check this quadrant do they have all the same values we have to do the same thing for this quadrant the bottom right quadrant and the bottom left quadrant so we have to do that here so the time complexity of that is also N squared and doing the same thing at the next level will have smaller quadrants but we'll have to still do that in the worst case for every single one so every single position in the entire grid that will also be another N squared so we're going to have log n levels in this tree for each level we're doing an N squared operation so the overall time complexity is N squared times log n in this recursive so solution so now let's code this up okay so like I said I'm gonna do this recursively so I'm going to define a DFS we definitely want to pass in the dimensions of our current portion of the grid and we also want to pass in the top left coordinate so I'm going to say row column that's what these stand for I'm going to pass in the top left using these two coordinates we know our main base case is that if all the values are the same so let's try to figure that out I'm going to have a variable which I'm going to call all same I'm going to set it to True initially and then I'm going to create my nested for Loop to iterate over the entire Grid it's a square grid so it's pretty easy to iterate over just have to have a nested for Loop going n times and we want to know is the top left position of our grid of our portion of the grid that we're checking at row column coordinates equal to the next position in this grid we're just trying to iterate over our current portion of the grid which is n by n so to get the coordinate of the next position we're going to say rho plus n and column plus n so if all the values are the same then we don't really want to do anything but if we find any pair of values that are not the same then we will set all same equal to false and then break out of this Loop once we have either iterated over the entire portion of the Grid or broken out of it then we want to check if all same is still true then that's our base case that means we have a leaf node now what is the value of the leaf node going to be that's the first parameter that we pass in it's going to be the value in our grid at the top left position because all of them are the same and next is it a leaf node yes this is going to be a leaf node and then we pass in the four children they're implicitly going to be null anyway so for a leaf node that's what we would want so we don't really have to explicitly say that all of them are null we can just implicitly assume that now you might be thinking this is the base case where all of the values are the same but what about the base case where n is equal to one well we don't have to explicitly Define that case here because actually that's going to be covered by this piece of code anyway so we don't have to worry about that this is our only base case we can think about it like that at least so otherwise we know n is not equal to 1 and all of the coordinates are not the same value so we're going to set n equal to n divided by 2 integer division in Python and then we want to recursively run DFS for each of the four children nodes so for the top left we're going to run DFS we're going to pass in our new n value that we just computed over here and we're going to pass in the row and column since it's top left it's going to have the same top left coordinate as the one that we're currently at but I'm going to copy and paste this because now we're going to get to top right which is going to be a bit different the row is going to be the same for the top right portion but for column we're going to add to it the new n value that we just computed which is half the length of the previous n value so this will give us the top right coordinate so this will give us the top left coordinate of the top right portion of the grid now I'm going to copy and paste this and do it for the bottom right and bottom left so just to rename these now bottom left is going to be the column staying the same but the row is going to be different we have to add n to it we're going to go half that distance and bottom right is going to actually be updating both of the row and the columns so we already have column plus n and for row we're going to say row plus n now we have the result of the four children which we need because now we're going to create a node for the current coordinate that we're at and we know it's not a leaf node so the value that we give it doesn't really matter I'm going to give it a zero you could give it a null if you wanted to it doesn't really matter and for is leaf I'm going to say false we know it's definitely not a leaf because it has four children and these are the four children of that node so let's pass them in top left top right bottom left and bottom right make sure you pass them in the same order that they have defined up here and this newly constructed node is exactly what we're going to return so let's do that and now outside of this DFS we need to actually call the DFS and what we're going to pass in for n is of course going to be the dimension of the grid and for row column we're just going to start at the origin which is 0 that's going to be our top left coordinate so now let's take this and run it to make sure that it works oh whoops I had a very dumb typo sorry about that here we're not adding n we're adding the I and J that's the whole reason that we're iterating over the grid because we want each of those coordinates I'm really sorry if this was confusing now that we've run it you can see that yes it does work and it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neetcode.io it has a ton of free out neetcode.io it has a ton of free out neetcode.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
Construct Quad Tree
construct-quad-tree
Given a `n * n` matrix `grid` of `0's` and `1's` only. We want to represent `grid` with a Quad-Tree. Return _the root of the Quad-Tree representing_ `grid`. A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes: * `val`: True if the node represents a grid of 1's or False if the node represents a grid of 0's. Notice that you can assign the `val` to True or False when `isLeaf` is False, and both are accepted in the answer. * `isLeaf`: True if the node is a leaf node on the tree or False if the node has four children. class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; } We can construct a Quad-Tree from a two-dimensional area using the following steps: 1. If the current grid has the same value (i.e all `1's` or all `0's`) set `isLeaf` True and set `val` to the value of the grid and set the four children to Null and stop. 2. If the current grid has different values, set `isLeaf` to False and set `val` to any value and divide the current grid into four sub-grids as shown in the photo. 3. Recurse for each of the children with the proper sub-grid. If you want to know more about the Quad-Tree, you can refer to the [wiki](https://en.wikipedia.org/wiki/Quadtree). **Quad-Tree format:** You don't need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where `null` signifies a path terminator where no node exists below. It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list `[isLeaf, val]`. If the value of `isLeaf` or `val` is True we represent it as **1** in the list `[isLeaf, val]` and if the value of `isLeaf` or `val` is False we represent it as **0**. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** \[\[0,1\],\[1,0\],\[1,1\],\[1,1\],\[1,0\]\] **Explanation:** The explanation of this example is shown below: Notice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree. **Example 2:** **Input:** grid = \[\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,1,1,1,1\],\[1,1,1,1,1,1,1,1\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\]\] **Output:** \[\[0,1\],\[1,1\],\[0,1\],\[1,1\],\[1,0\],null,null,null,null,\[1,0\],\[1,0\],\[1,1\],\[1,1\]\] **Explanation:** All values in the grid are not the same. We divide the grid into four sub-grids. The topLeft, bottomLeft and bottomRight each has the same value. The topRight have different values so we divide it into 4 sub-grids where each has the same value. Explanation is shown in the photo below: **Constraints:** * `n == grid.length == grid[i].length` * `n == 2x` where `0 <= x <= 6`
null
null
Medium
null
1,980
Hello Everyone, our coding question today is Find Unique Binary String. Now in this question, what is given to us and what do we have to do? First of all, let us understand. Okay, in this question, we have been given a string array, which means its name is the names of that array. Its name is numbers but the data type stored in it is string. Okay, string data type is stored in this number. Okay, now inside this we are given that if like this array of ours stores a unique binary string, binary. What is a string? It means some string which is made by using only row and one. Okay, so we have n unique binary strings stored in this moist jar. Okay, now the n binary strings are there, their size is also n. It would mean that if there is an array, it is of two size. If the names array is of two size, then the elements present inside it and their strings present in it will also be of two length. Okay, as we can see, its size was two. So only strings of two lengths are present in it, its size is three elements are present because the size of this array is three, so strings of three lengths of three sizes are present in it. Binary strings are present. Okay, now first of all, we are like if When we write the L statement, we write it like this, we write if condition will come here, if part here, all the if's, whatever you want to run the code here, the if's will be there and then we write else part right, we write it like this. But we can also write it in one line, they are by using ternary operators, okay by using ternary operators, we can write it like this, so how do we basically use ternary operators, what happens in it that we like if the if with brackets This is the condition which is in the brackets, first of all, we write that if the value of this comes in one or zero, then it is okay, so we have written an int, here we have written an int, then it is okay, then the most First comes our condition, now I am just telling you a syntax, now let's remove it from here too, I am just telling a syntax, okay, first comes our condition, after writing the condition, we put a question mark and then here But when we write that if our condition which we have provided here becomes true then this part here will return that first part will return that before the semicalculus if it becomes false then the second part will return OK then we have if We have written the L statement in a single line, here our condition has come, what will be the condition and its output, if the condition is satisfied then what should happen if it is unsatisfied then what should happen comes after the question mark, it is okay if the condition is satisfied. So the thing that is before the colon gets run and if the condition is not satisfied then the thing after the colon gets run. Okay, now we are going to use it in our question. Okay, so now first of all. What we have to do is to find such a string and remove those which are not present in it. Now we can do this thing that which is 0 and hence which is its one element, we have taken its first word first meaning first letter. Now because in this If it is a string then we will say first letter. Okay, if it is a binary string then it is a number. But if it is a string then its first character is its first character. We will defer our answer to its first character. Okay, as we have its Ar, we see one. Let me explain to you what I am trying to say, inside this, I want to say inside this, which will be our string, which will be our final string, like we are given in the question, like here we have 0 and 10, okay, so here. Like this string of ours is present 0 and 0, this is our string present, we have OK, so if we defer the first character of our answer to the first element of our answer, that means if our first string If the first character is one, then we have kept the first character of our answer as zero, okay and we will get our answer from the second character of our second string which is present. Let's defer the second character of , which means again zero, defer the second character of , which means again zero, defer the second character of , which means again zero, if it is one then it is zero, if it is zero, then it is one, then we have a unique string which is neither of these two, meaning that the first one is our The first element of our answer, we have deferred it to the first element of our array, and the second element of our answer, we have deferred it to the second element of our answer, right? So in one way, everything became different that it became different from this and this became different from this, so if our first element of our answer and the first element of our input are not the same, then both of them are the same. Can't be and we did the same for second also, which was our second element, we made it differ from its second element, so both of them will not be same, right, so here also row zero has come, so this and this. It's different, okay, then let's try to write the code using this thing. Okay, so now we come to our code. As I told you, we will use the ternary operator here, so here we will use the same. Let's do it and show you how we will write our code in it. Okay, so first of all, our int result will come here. Okay, sorry, string result and we have put that in mt string now. Okay, now we have run a for loop. Okay, we have run a for loop. Run the loop and we traverse this numbers array in aa e0 aa less numbers dot size aa plus okay now we will store in our res here pay plus sorry ars in plus equal to what does this mean ars plus equal to means What is R equal to R plus something, whatever we will write next, okay, so here we have written it in short form R is equal to, now we will use our ternary operator here that if then our which is in the numbers. The element which is present at the position in our names is the element which is at the first position, the element which is present is at its zero position, its is also at its zero, sorry, its is also at its position, meaning the first position of the first element, first of this string. First position because as I told you in the previous question that we can treat a string as a character array, so we assumed that it is a 2D array, so first of all it is a string, it is a part of the entire array, meaning. Part of this entire array is this string 01 And this string of 01 is this 01 is part of the entire array Only zero is the first element Okay, so we looked at the first element of this entire array and the first element is also the first unit first character. Look at only if it is equal to zero then we will add one to our ars. If it is not equal to zero then we will add zero. Sorry, there are characters around them too because ya are around them. Also one and zero will come, we will add it and after that we will return our ars ok now we run it once and check it is run and we submit it, this is our submission also, now what did we do in it That we had kept an MT string first, then when our names are at rectangle position, if then it is equal position at rectangle position, if then it is equal to zero, like here, if then it is equal to zero, if then it is equal to one, then we wrote zero. So if it is equal to zero, then one will be appended there. This string is coming in. If it was equal to one, then the false thing would have been run, then zero would have been added to the right, as if it was zero, meaning whatever it is in that position. I was present, there was zero, so it became equal, okay, if it became equal, then the condition was true, the thing before the first colon would have been run, if it had been false, then the thing after the colon would have been run, okay, so do you understand? If you don't understand yet, then let's dry run it once and see it. Okay, now let's see it once by dry running it. Now this is the thing. Okay, let's dry run it and see it. If we like, we see this part only now, we Here we block the color, sorry, we block it's okay, let's see how it is running, let's see our first example. First of all, in our first example, we see how it is working. Our value was 0, this is it's okay. So let's write it down neatly, how will we write it, so first of all, here our first element of this array is 0 and the second element is 10. Right, so we have declared one MT string, which is this array, okay. Once we enlarge it a little bit, which is our Ars, we have declared it as an MT string, okay, so there is nothing in Ars also, after that we have Ars, this Ars plus is equal to two is equal to Ars, we like here. We have written r p itu so it is equal to our ars equal to ars plus this thing is complete ok so what we have written above is just its short form it is just the same thing ok so now what are we doing in it now let's see. First of all, we go to the rectangle position, meaning, first of all, we have its size, like here we have put a for loop, so it will run from zero to the size of numbers, so what do we have, first of all, this is the zero position. And this is the first position, so first of all we have gone to zero position i0, it means i0, okay, we write here i0 is i0, ours is okay, so after that we went to numbers, so this is our numbers. By going inside this name, we reached its zero position, that is, zero position is fine, we reached its zero position, we reached zero position, after that at that zero position, we checked that it is also at zero position. So what does it mean, we can treat this string like I told you in the previous question that we can treat this string like a character array. Because our string is provided, then we can treat it like a character array. Right, so we can treat it as a character array. If we treat it like, then what will be the first element of this string, what will be the zero, what will be the th element, i is zero, right now, first of all, we have gone to i, sorry, we have gone to i, when we have come to this block, only now. When we went ahead of that, what is this character at the zero position of this string, Ro, then we saw that Ro is lying here, so the value of this whole became zero here, 0 is equal to 0, Ro has come to zero. If it is equal to then the true thing should be returned Right so what was the true thing before the first colon So here in RS at this time we have here in Sorry RS now at this time we have stored one Okay because the condition is true If it is done, then the true part is run. Now after that we go to the next iteration, then I got changed. Okay, so after becoming one, here the numbers became one, so the numbers reached the first position, then it reached the first position. In this he checked who is present at the first position, who is at the zero position, who is one or not, who is present at the zero position, and who is present at the zero position, who is present at the first position, then what is present at the one, zero. Again we checked that only zero is present at this aa, then again the true condition will be run, again one has been appended inside it, so one has come inside the aar, again that is why our code is running, our code is because We have deferred our answer from the first position of the array which is present at the first position, and we have deferred our answer from the second position of the second, so it is not even equal to it. If I can, we are returning only one unique string. Right, I guess you all must have understood and now you can ask questions yourself, so thank you everyone.
Find Unique Binary String
faulty-sensor
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "00 " would also be correct. **Example 2:** **Input:** nums = \[ "00 ", "01 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "10 " would also be correct. **Example 3:** **Input:** nums = \[ "111 ", "011 ", "001 "\] **Output:** "101 " **Explanation:** "101 " does not appear in nums. "000 ", "010 ", "100 ", and "110 " would also be correct. **Constraints:** * `n == nums.length` * `1 <= n <= 16` * `nums[i].length == n` * `nums[i]` is either `'0'` or `'1'`. * All the strings of `nums` are **unique**.
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
Array,Two Pointers
Easy
null
20
hi guys so in this video we'll look at valid patent essence problem so this is a very classical and very typical of a stack problem so let's see what the problem description is so we're given a string and the string is such that it only has characters such as those brackets and we have to determine whether the string is valid or not now what are the conditions to determine that so couple of conditions that are open brackets must be closed in correct order and open bracket must be closed by same therefore brackets so let's look at those examples and we'll get more clarity so if you look at the first example each open bracket is closed by corresponding or respective closing bracket so obviously the string is valid true now if you look at the second example there are a couple of opening brackets and then there are a couple of opening curly braces and similarly respective side there are couple of curly closing braces and couple of closing brackets so the string is valid and the third example is there are a couple of opening brackets but there are no respective closing brackets there is a closing curly brace but there's no opening curly brace so obviously string is invalid so we need to likewise have code such that we can identify whether each string is valid or not so it's a very easy problem let's go to the white board let's look at the approach and then we'll come back and look at the code okay so to solve this valid parenthesis problem we'll take these two strings as our base cases and we'll see how we can use stack to solve the problem so let's look at our first example so this is our string open brackets opening curly braces closing curly braces and closing brackets so what we'll do is the moment we find a opening bracket what we'll push our respective closing bracket in the stack and then when we find a closing bracket or we look in the stack and we say is it matching or is the stack empty kind of comparisons and then we'll figure out whether it's valid or not so let's actually do it and let's see how it goes so let me just have a stack simple stack let's assume this is a stack so when we find this opening bracket what we do is we push our respective closing bracket in the stack when we find this again opening bracket we push one more closing bracket in stack when we find this opening braces we push one more curly braces closing curly braces in stack and likewise one more closing curly braces so now we are at I here so we pushed four items in stack and we compared four strings and now we find a closing bracket so when we find closing bracket what we do is we do stack dot pop and we compare it with the current characters so if it matches we keep continuing so we do stack dot pop and we compared with this so it matches now this is gone right we did stack dot pop so next we'll check this is a closing bracket so will again do stack dot pop and we'll compare so again this is gone same thing we'll keep doing stack not pop and compare stack dot pop and finally one string is done we see if stack is empty then we say yes string is valid if stack was not empty or if some of the condition didn't match this a string is invalid so let's look at an invalid or example and then we'll understand more so similarly let's have let's draw a stack okay so now opening bracket opening square bracket open square bracket so a stack would become closing bracket closing square bracket so when we are here we pass these four characters so now we hit a closing square bracket so what we'll do is we'll pop from stack and we'll compare so it matches again second closing bracket so we'll pop from stack and it matches now we hit closing curly braces so we try to pop but when we pop we find a closing bracket which does not match so we say this string is not valid it's invalid so straight forward stack problem or let's see how actual code looks like for this algorithm okay so this is the final code pretty much similar to what we discuss on the whiteboard so we just iterate through all the characters in the string array and for each type of opening bracket what we do is we push the respective closing bracket in stack and then once we hit a closing bracket type of thing what we do is stack empty or if stack dot pop doesn't match the character we say shrink is invalid return false so that's simple is it and once we successfully parse all the characters and all the string and if the stack is empty then we say shrink is valid so I've threes three simple strings so let's run it and let's see what the output is so yeah they go so first two are valid as we discuss and the last one is invalid so there you go that's the final code so hope you guys liked the video if you learn something new give me thumbs up any feedback any suggestions or let me know in the comments and then subscribe for more videos
Valid Parentheses
valid-parentheses
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. 3. Every close bracket has a corresponding open bracket of the same type. **Example 1:** **Input:** s = "() " **Output:** true **Example 2:** **Input:** s = "()\[\]{} " **Output:** true **Example 3:** **Input:** s = "(\] " **Output:** false **Constraints:** * `1 <= s.length <= 104` * `s` consists of parentheses only `'()[]{}'`.
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
String,Stack
Easy
22,32,301,1045,2221
1,930
hi everyone today we are going to solve the little question unique lengths of three parenthalamic subsequences so you are given a string s Returns the number of unique palindorms of length 3 that are subsequence of S note that even if there are multiple ways to obtain the same subsequence it is still only counted once a polynomial is a string that is the same words in the backwards so subsequence is so we have example so Ace is a subsequence of ABCDE because ABCDE has all characters like Ace and the same order so a and c and e so let's see the example so you are given a b c a and the output E3 because uh the three polynomic subsequence of lengths 3 are like a b a and a c a so that's why output is three okay so let me explain with this example you are given a b c a d and uh I believe this question is much easier than you expected and first of all we initialize the two variables one is a result variable with zero so this is the return value and a unique character so in this case you need character in the string is like a b c d and we try to find each character from beginning and the from last so let's try to find a so we find a at index 0 here and uh from the last we find the a here so now we know that we make sure that we can create a three paranormic subsequence between if we make this area unique because we already have both sides like a and a same characters so just make this area unique so that we can get the three paranormic subsequence so to make this area unique we use like a set so in this case so unique character is a b c so there is a 2B so but uh if this area if we make this area unique so output is ABC so that's why we can create like a b a c a so in that case we get a three uh unique uh palindorm subsequence so update the result variable to three and uh Okay so let's try finder B from beginning we find the here and from the last we find here so in that case um try to make this area unique but it's already unique so I think easy to understand so from this area we can get a unique uh palindorm a like a one palindolome so Bab that's why I output is now three plus one is four and uh how about I see from beginning we find the C here and from the last we find the C here and it's same in that case uh we can't create a palindrome string so we don't update the result variable and how about the from beginning we find that D is here and from the last we find the D here and the same things there's no space so we can't create a polynomial strings so we don't update the result variable so that's why in this case output should be 4 yeah 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 result variable with zero and get the unique character from string so unique equals set and S and start looping for character in unique and then first of all try to find a unique character from beginning and from the last so let's call from the beginning let's call it start index so equal s dot find C so this is a such uh character from the beginning and uh let's call the end index this is a from the last and equal s dot if we find the specific character from the last we can use our find C so this is like a search such a character from the last index and after that if start is less than n in that case we can create a length 3 palindrome subsequence so let's press equal and the length of unique characters between start and end so set and the s dot plus one column and so y plus 1 because in Python this number is included so but we need a between start and the end so that's why we need to add plus one and then this number is not included so that's why I just put end here so 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 26 of n so 26 is a number of alphabet because uh potentially so unique this unique has 26 characters so that's why uh this photo possibly executed like a 26 times and we start the character in the string so that's why uh order of 26 of n and there's space complexity is a actually same 26 of n because uh this unique variable has potentially 26 characters so that's why so let me summarize step by step algorithm okay so this is a step-by-step algorithm okay so this is a step-by-step algorithm okay so this is a step-by-step algorithm of unique length 3 parindoramic subsequences step one initialize the result variable and get the unique characters from input string step two start looping find each unique character from the beginning start index and the last end index if start index is less than and index try to make unique characters between start index and Indian and index and the account lengths of unique characters so I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave your comment I'll see you in the next question
Unique Length-3 Palindromic Subsequences
maximum-number-of-consecutive-values-you-can-make
Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**. A **palindrome** is a string that reads the same forwards and backwards. A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. * For example, `"ace "` is a subsequence of `"abcde "`. **Example 1:** **Input:** s = "aabca " **Output:** 3 **Explanation:** The 3 palindromic subsequences of length 3 are: - "aba " (subsequence of "aabca ") - "aaa " (subsequence of "aabca ") - "aca " (subsequence of "aabca ") **Example 2:** **Input:** s = "adc " **Output:** 0 **Explanation:** There are no palindromic subsequences of length 3 in "adc ". **Example 3:** **Input:** s = "bbcbaba " **Output:** 4 **Explanation:** The 4 palindromic subsequences of length 3 are: - "bbb " (subsequence of "bbcbaba ") - "bcb " (subsequence of "bbcbaba ") - "bab " (subsequence of "bbcbaba ") - "aba " (subsequence of "bbcbaba ") **Constraints:** * `3 <= s.length <= 105` * `s` consists of only lowercase English letters.
If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.
Array,Greedy
Medium
330
225
hi in this video i'll show you how to implement stacks using queues so just really quickly a stack looks something like this and if i add values i get 1 two and then three so if i want to pop a value i have to pop out the last value i've added okay while in a queue i just keep it open-ended and if i add i just keep it open-ended and if i add i just keep it open-ended and if i add numbers one two and three if i want to pop a value i would have to pop out the one down here so this is a stack and this is a queue a stack behaves in last in first out while the queue behaves first and first out and the question is how can we make this queue behave like a stack well how can we make this queue look like a stack well if you think about it when i pop out the number i should get three and i shouldn't be getting one in order for it to behave like a stack so one thing i can do is i can swap the order of this by popping this and adding it here so because the queue goes in first out while this one is last in first out as you see here three goes straight here and then if i'm going to pop this two go straight here and then if i pop this one goes straight up here so now this queue here behaves exactly like a stack which is basically what the question says implement stack using cues so here is a cue so now if i'm going to look at the value of the top in the stack i'm gonna in the queue sorry if i'm gonna pop a value i'm gonna pop three which is the correct one as it shows if it was a stack if i'm gonna pop the next value it will be two and then in this case it will be 2 because in q the numbers from the bottom go out first while in stack it's the numbers on the top the question here says using only two cues but actually with this implementation we can do it by only a single queue we don't need two cues for this so let me show you how to write the code for this so we implement the queue we say self.here we say self.here we say self.here like that so now we have um oh yeah sorry collections dot dq so we're using the python implementation instead of building it from scratch and then as i demonstrated the first thing you can do is append the value to your queue so if we have our q here what you've done now let's say it's the value number one so if this is your queue and let's say this is your stack and now you've added one okay now if you're going to add a second number let me show you how the code behaves so for the range i just use underscore to demonstrate that it doesn't matter we don't need the x so i'm going to iterate through the length of the queue -1 -1 -1 and i'm going to append these values to whatever pops out of the queue so if i imagine this queue right here so i'm going to pop this one and reappend it but it doesn't make sense of course if you just have one here but let's imagine you have a queue that has number two and number three again so let's say you have a stack that looks like two and three and if you call this function pop in a stack you should get three but in a queue you're gonna get one so you wanna get a three so what you can do is this function does right here so self dot q dot pop left it's gonna pop this left and it's gonna append it to the queue so it's gonna go straight boom right here and then in the next one it's gonna pop number two and it's gonna go right here then it's gonna pop number one and number one is gonna go right here so now when you call in the actual pop you're gonna get number three which is the equivalent to what you would see in a stack and the same with the top so this is basically it you have now added values and now if you want to pop you can just return soft here pop left and if you want to see the top then you simply look at q0 q index value 0 and if you want to check that it's empty just return not learn self.q so if this has five not learn self.q so if this has five not learn self.q so if this has five then obviously this is not empty so then here it will return false otherwise it will turn true let's run this and we get some invalid syntax yes self let's try one more time more oh yeah that should have been minus one sorry and there we go this is how we implement a stack using cues thanks for watching
Implement Stack using Queues
implement-stack-using-queues
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`). Implement the `MyStack` class: * `void push(int x)` Pushes element x to the top of the stack. * `int pop()` Removes the element on the top of the stack and returns it. * `int top()` Returns the element on the top of the stack. * `boolean empty()` Returns `true` if the stack is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a queue, which means that only `push to back`, `peek/pop from front`, `size` and `is empty` operations are valid. * Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations. **Example 1:** **Input** \[ "MyStack ", "push ", "push ", "top ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 2, 2, false\] **Explanation** MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `top`, and `empty`. * All the calls to `pop` and `top` are valid. **Follow-up:** Can you implement the stack using only one queue?
null
Stack,Design,Queue
Easy
232
1,314
hi everyone so let's talk about the matrix block sum so you're giving an environmentary an integer k so you have to return a metric a new match would be honest based on the integer k so you can actually graph the element based on i minus k two i plus k j minus k to j plus k so this is the sum of the range based on the k right so what does that i mean what uh what does that mean right so i'm gonna say one two three four five right this is original measure and definitely we are not going to modify this metric because we will continue updating our new metric based on this value right so i'm going to have a new metric and definitely right this is going to be the final like final block final uh measure you want to return but you do need to have an another metric which store the current sum right so if you want to sort of store the current sum at this cells right this is definitely going to be one right and i'm going to change another color this is fine right but how what happened for here if you want to store the number from your top left to bottom right so your top left is nothing the bottom right is here right so from here to here so this is a metric from here to here so this is zero this is the right and this is one this is actually two actually this is three in this case right now uh again uh for this cell right you want to store the value from top left to bottom right and these are all zero and these are one this is three and you plus three which is six right and then you do the rest of it this is going to be five right one plus four right so top left to bottom right and this one top left to bottom right so this is going to be what uh 9 10 12 right and then so on right definitely right and then this will be the final i mean the total sound of the metric that you will uh they will store right and then when you want to return the metric based on the k right and then you are definitely what uh i'm gonna just grab some example and you'll be able to understand quickly so give this guy credit so if you want to grab this one and grab this little metric and then but the problem is we are using the sum we're using the summation to uh to get a final solution for sure right so um i'm going to get what i'm going to get the total so if you want if you go up this cell right it's going to be the total sum and then you want to subtract this one right you want to try this one and definitely you want to subtract this one right because you want to get this red block right and then you subtract twice for this cell right you have to add one back right and this is how it is right okay and if you notice this is definitely a typo r1 c1 r2 c2 for sure this is r and i'm going to talk about this when i call it so don't look at this but look at the diagram if you notice if you want to subtract the cell from here and here right you don't want to go from r1 c1 right you want to say r1 c1 minus one this is c1 minus one right and this is r1 minus 1 l1 minus 1 right so this is what this is pretty much the solution all right so let me stop putting and back to here right so okay so if you store the value i mean one more thing you have to notice if you store the value you can actually go on your current sum metric so this is three this is five right so three plus five is what eight plus 5 is 13 so this is supposed to be 13 right but this should be 12 right this is because we add this twice so we add this twice right one you add one twice so you can substitute by one which is twelve right so uh let me do uh one more thing uh one more example i mean one more cell for sure so this is six this is twelve six plus twelve is what 18 minus three 15 plus 6 which is what 21 am i right 21 uh yes i mean this should be correct 21. and then this is the final solution for sure and then uh and then you'll do and then you'll keep doing and then you'll return the metric based on k right so uh for this one this is sum to the metric and then you have the anonymity i'm going to call resort next week you will get the value this value based on the sum metric right so this is why these are not equal but these are equal right and all right too much talking about here is it so in learning go to metal land i'm going to go to madrid and i need to create a some metric send this song equal to new beginnings plus one and n plus one right and i need two drivers um uh for 2d map right uh i made it for it and i need to do the sum at i plus one j plus one right i'm starting from index one starting for index one for the sum starting next one but i need to grab one i need to grab the top left to uh i mean sorry um the little square measure based on top left to bottom right so this is going to be what you add your top your eye your left and then you subtract the top left right all right so you might forget what i mean right so imagine this is to d right and you want to calculate this song right you want to add the top you want to add a left and then this and then you add twice for your ad twice for this one right this is because for this one the 2d sum this is the song of this right and this one is on the list right so you add twice for this cell right so you need subtract for this one and then you need to add the current math current map at this position all right so it's going to be net high j plus sum and then this is going to be y i plus 1 j plus on i j plus 1 right so imagine your i and j is starting 0 right so this is 1 0 1 subtract sum will do right and then you will get a sum of a metric and then you need to have a return value which is result new ink and this is definitely going to be m by n for sure right then you will return result right so you need favorites click on you can from j lesson and j right all right now uh we need to get the r1 c1 r2 c2 right so r1 c1 is definitely going to be based on k right so if you reach through the constraint right so this is constraint so i want to grab the little uh valid uh block in the matrix so it's going to be r y equal to what so the maximum uh is either zero or positive number right you can have a negative value for the metric right so this is going to be maximum method max is either 0 over or i minus k n minus k right same thing for c1 method max j minus k right and then you have r2 equal to metal mean and then this is going to be based on what the match is the size of n and size of m right but if you want to get a hollow bond right i plus k is all about and then you will get i minus 1 and this is i plus k and this is for c 2 equal to method i mean n minus one and then g plus k right and then this is what this is the index based on zero right we started from zero and then you go through the n but we need to get the index based on the uh based on the sum all right so i would just want to making sure these are the value based on could be subtract and then i was a result i j the result at i j is definitely starting on zero right is equal sum of r two c two right so if you want to get uh the self for this one right so this is total sum for the sum right you need to subtract this one and this one right so you need to subtract sum r2 and then c1 minus one so y is minus one c one is this one right if you say r2 c1 you are getting this value for the song right and then you take this entire sum um and then take the subtraction by this right but we want to get this one not different so it's going to be r2 c1 minus one and for this one this is going to be what r1 minus one c2 right so again sum r1 c 2 minus 1 right and then if you notice that this is like i mean you subtract twice for this right so you add one back right and then use the plus sum and then this is going to be r1 minus one c1 minus one if you notice c1 right here r1 right here and this is r1c1 right so if you want to add this fact it's r1 minus one c1 minus one and this is solution this is the solution so let me run the code and then hopefully i don't make mistake like i do all right i found another mistake so this is r2c minus one right so r2 c minus one is right here and this one is r1 minus one c2 and i make a typo right here sorry about this oh one minus i want my s1 c2 and then here we go so let me run a call again all right i pass the test all right let's talk about timing space this is going to be a space all of n times n and this is going to be a time of n times n and then represent what and represent the end of the math and represent the uh length of the measure doubling right so uh this is gonna be the solution and sorry for the mistake like i just uh i'm probably just ignoring what happened when i typed this but i found another mistake and i apologize and i will see you next time bye
Matrix Block Sum
matrix-block-sum
Given a `m x n` matrix `mat` and an integer `k`, return _a matrix_ `answer` _where each_ `answer[i][j]` _is the sum of all elements_ `mat[r][c]` _for_: * `i - k <= r <= i + k,` * `j - k <= c <= j + k`, and * `(r, c)` is a valid position in the matrix. **Example 1:** **Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], k = 1 **Output:** \[\[12,21,16\],\[27,45,33\],\[24,39,28\]\] **Example 2:** **Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], k = 2 **Output:** \[\[45,45,45\],\[45,45,45\],\[45,45,45\]\] **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n, k <= 100` * `1 <= mat[i][j] <= 100`
null
null
Medium
null
103
hey guys welcome to the channel this is wagga we're going to do another question in question is number one zero three binary tree zigzag level or the traversal right so we have a binary tree you're supposed to return it in zigzag level order what that means is um we add the we start off with the root and then we start if the root has children we start by adding the right um the right node and the left node and if the and when we come to the next level the level after that if they have children we start by adding the left node and then the right node so in this case where we have 3 9 20 15 and 7 we have three then we add 20 and nine as their own level and then afterwards we add 15 and seven as their own level after that right so our answer should be 3 29 15 and 7 right what we should do in such a situation we could use a dq right and a d in a dq we can add um items from either the front of the rear the left and the right so or the back and the front right so for example if we come here and we create this situation what we could do is um if we have our array we have uh the array is going to be just going to be basically not already the tree is going to be 3 9 20 15 and 7 like so and we could create um an array of levels where we collect um at eq of levels where we collect every single level and um another thing we could have is a result already right so a result array and um depending on whether the zigzag flag we could have a flag maybe zigzag depending on the flag we decide um where we're going to add the children of a nude to an array right so for example um if we have uh the case of having our tree we have our tree which is 3 20 19 59 7. um we add the first thing we do is uh we append to our queue in this case um we append it to our queue we could have uh a queue here and we append to a queue our route we say maybe three and after that we pop the three and we put all the children into a level right so we put every all the children in the level and then um progressively add them to our queue depending on whether the flag is right or is true or false basically right it's pretty straightforward and it's um i think easier understood when you actually put it in code right so we could start off the first thing we could do is we could have a sanity check right we just checked that everything is as it should be you could say if not root and what we want to do in this such a situation we want to return an empty array right we return an empty array like so and then afterwards we create a results array and the results array is just going to be empty like so and afterwards we get the cube and the queue is just going to be collections and we could say dot eq dq like so right so we have our q over there and then we have our flag we could call it zigzag and our flag is going to be set to false and um if it is false we start with the we start by appending the left child right if it's true we start by appending the right child right so depending on what um what is what whether the flag is we're going to append to our queue depending on the quality of the what the flag is and then obviously we're also going to have to flip the flag at some point right so basically that right so what we do is um we have to flip it at every single level right so we could have a we could have we could start off by appending our route right so q dot append and what we want to append is going to be our route like so right and the next thing we need to do is we could have a while loop well there's something in our queue we could have a level we would put we could create an array to hold our various levels that you can add them together and the first thing we check is we loop through the length of the queue and for that we say for underscore in the range and the range we want to look at is the length of the queue and of course we start off with the queue having our route which we just appended right and we check if we check the flag if zig let's just pull it correctly if zigzag what we want to do is we want to first um remove the node in our queue and then append to the levels um append to our level uh the nude the actual nude and then add to our cue the children and this is the order we're going to write add them we're going to add the right children and then the left children and we're going to use the append left method right like the first thing we do is um we pop what is in our queue which in this case if we're starting is the root right so we say node dot node is going to be q dot pop right and after we pop it what we want to do is um we want to append to our level the value of the node right so we say level dot append and what we want to append then the value of the node right no do it well like so right and then the next thing we do is we check whether or not um the node has the arise child because the zigzag is true in this case so we check whether the node has the right child like in this case we add 20 and then nine right so the first thing we do is we say um if node dot right does it have a right child right if it has a right child what we want to do is we want to put to the left of our queue um the node's right child right so um what we do in such a situation we come here and we say um q dot append and what we want to append the left right so we want to append left rather we want to append left and we want the right child right no dot right like so and after that we check if it has a left we say if node dot left and we append q dot append left and what we want to open left we want to append left the left shell right so we say no dot left like so right else that is zigzag is false like on this third level right what we do there is um the same thing we just um we first pop our node um we say node equals q dot pop left right we remove um our on our queue right um we remove the uh we pop it on the left right we remove it from the left side right and after that the next thing we do is we append it we just do the same thing here we just append the value of the note that we popped off right so you could copy this line copy come and paste it here like so right and it's a bit it came with a bit of space in it so we just append that value like so and afterwards um we check if it has a left and we put it on the right and we do the same for the right so we say if let's just type it out if node dot if node.left what we want to do is we if node.left what we want to do is we if node.left what we want to do is we want to append q dot append and what we want to append is um the node.left and after that the node.left and after that the node.left and after that we want to check if node dot write and what we want to append is um q dot append and we want to append the right so no dot right like so right and afterwards after this two have run the next thing to do is just put everything put the level into our result right so for that we come and say after the if checks have run through we just want to put that specific level to our result we could say results dot append and but we want to append the current level right like so and then afterwards we want to set our zigzag to the opposite of what it is right if it's true it's false if it falls it's true like um over on the other channel i use 50 ui in this case it would be a toggle switch if you know swift right if you know swift ui right this is basically a toggle switch right so we say if a zigzag is going to be not zigzag right the opposite right and finally the next thing we do is um outside the while group we just need to return our result like so right we make a few corrections to a few typing errors and we make sure that our res and our zigzag the flag are on the four level of the loop right and after that we run our code and if we run our code and we submit it should be accepted right so basically it has been accepted and um the time complexity is obviously going to be oven because we go through n nodes and the space complexity is going to be um of n because we create structures that are potentially as large as um the list that uh as large as the tree right will have as many elements as the tree has notes so potentially that so yeah so it's oven so thank you for watching subscribe to the channel and i'll see you in the next
Binary Tree Zigzag Level Order Traversal
binary-tree-zigzag-level-order-traversal
Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[3\],\[20,9\],\[15,7\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-100 <= Node.val <= 100`
null
Tree,Breadth-First Search,Binary Tree
Medium
102
84
Hello hello friends in this section we are going to discuss about how to find largest rectangle in history from this problem like and complexity more simple definitely subscribe problem element representative will withdraw all eggs subscribe in a reader that it is injured gram out of bus required for middle Of the best possible benefits and subscribe this channel please subscribe it zil99 Video subscribe And subscribe The Amazing and bass exams for back to wishes in the midnight maximum area On The Amazing Possible Rectangle Video plz subscribe and subscribe the Channel subscribe and subscribe the Video then subscribe to I Will No Doubt Hai Ya Swarna 8th Maximum Area Swift Now Its President Direction Adhere and subscribe The Video then subscribe to the Page if you liked The Amazing subscribe The Amazing Update Delete That It's Not Possible To Include All The Best Complete Well Yasmin Rectangle It's Only Possible To Include Short But Complete Winners For Using Difficult Video subscribe The Amazing Mode On This Portion Is Not Included In The Area Along With Name Benefits Total Subscribe Like Subscribe Video Subscribe Now Quid A Left Side Observed S One India's subscribe And subscribe The Amazing Maximum EDDY Possible Money From All The Best Subscribe Total Number of Votes 12345 Topics Must Subscribe Updates subscribe The Amazing 600 Not Updating Maximum Area Subscribe to my channel by pressing subscribe button and click like button. Do in this program aga in a program in the first impression were 1000 dabir Video Subscribe Noted for its eyes and [ Subscribe Noted for its eyes and [ Subscribe Noted for its eyes and Liquid West Indies Cigarettes Update Will Do Subscribe The view that indicates that guy benefits electronic prohibition a lot for the time it Channel Subscribe in a Reader Subscribe will continue playing with logic and finally Bigg Boss but did not to leave one interaction with back to identify the subscribe and subscribe the to a group o You can track what is the fastest bar and reduce its value only when needed S It's Possible You'll Find Channel Subscribe Channel Will Take Only Will Attract Attention For Subscribe Maintain A Great Kar Accused Points Element Current Element Loop Element Subscribe To Bottom Iteration Repeat Jis Ronit Yonik Top Element Will Take Subscribe Zaroor Chalenge Ise Zaroor Vid D Only Will Not Work In Verses Point Confirmed Element Assistant Vice President Value In Turn Will Start In Text Intended To Calculate Area Idly Intake Quickly Not Develop It's A Zinc Provide Competition Will Divine Subscribe Miding 15 Minutes One Point Element Subscribe button click that when formula for calculating air chief always calculate the area from every friendship day element value deposit bar person flight attendant - Subscribe - Subscribe Now Subscribe Ungli By Considering Half-Half If Subscribe Five Video 98 Intact Why 12th Part In A Demonstration Dash Liquid Detergent Subscribe Prohibit Reaction Subscribe Element subscribe Video That Religious Person Lead Pair Difficult Hour 404 - Page Not Stop Acid Attacks - Calculate Area For Forming An Agriculture Space Update Comment Person Again Welcome President For The Validity Extension Idi 6 Point Element Intake 4.3 Inch Idi 6 Point Element Intake 4.3 Inch Idi 6 Point Element Intake 4.3 Inch Android - Tags Page 10 - subscribe and subscribe to Calculate Area Now Half Label Wishes Updated Amazon Subscribe Don't forget to subscribe on Thursday Subscribe 505 Element 8.55 Malik Subscribe 505 Element 8.55 Malik Subscribe 505 Element 8.55 Malik Current Affair 150 - 151 Subscribe Cr Current Affair 150 - 151 Subscribe Cr Current Affair 150 - 151 Subscribe Cr Faltu From A Rectangle And This Calculate Area 20 Do It Rectangle 10 These Great Content On Subscribe For Latest Updates Width Idi More Elements Subscribe Video Subscribe Adhar Rectangle Benefit Qualification President 2552 Calculate Maximum Egg Fried Idli Interior Subscribe Mid Day That Declare Mukeriya Variable Will Affect Maximum area indefinable that declare a variable to keep track of the intellect will love this is quite zero-valued or a zero-valued or a zero-valued or a whole lot element exit an MP3 all the current element and detergent talk value that happy stock dot mt or input alarm set the pick the latin Quarter Current Value Pimps Us Strong That And Continue With Next Generation In Noida Authority Limited Sale 10 Top Element Value Important Elements Understand And Calculate Area Cons Withdrawal Will Stop Equal To That Papa Let Calculate The Regional And Area With Top Veryval Input Dash Laptop Multiplicative And Subscribe To Hai Otherwise It I - Puneet Author Top Otherwise It I - Puneet Author Top Otherwise It I - Puneet Author Top Person On Channels - What Member Formula One Piece - What Member Formula One Piece - What Member Formula One Piece Calculate Area Minutes With Maximum Area In Difficult Minutes Update Develop Active That Not Be Done With Attractive And The Video then subscribe to The World Stage Not Empty Pocket Element And Calculate Area Exact Copy Pacific Courier The Final Years And Returned Is For Time's Sorrow Search Open Return From Friends Ability Alarm Comment Specific Disease Of Inputs Are Which Celebs Headed Home Subscribe To
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
137
hello friends today we will look at lead code problem number 137 and it's part 2 of single number or version 2. so here the question is that you are given an array of integers and every number occurs three times but one of the numbers occurs just one time so you have to find that single number and it's version 2 because there is a version 1 of single number where the problem is quite simple every number occurs twice and one of the number occurs once so sit there if you do xor of all the elements you get that single number but here the problem is slightly more tough because every number occurs three times and one of the number occurs one times so if you do xor of all the elements so let's say a occurs three times and b occurs three times and c occurs one times so you know that a x or a will always be zero and zero xor anything will be that because in xor if both the bits are one then it's zero if both the bits are zero then also it's zero so if you take a xor a these first two will make it zero and zero x or a is a so three times is same as single time so it does not help here so we will look at a few solutions so first will be more intuitive and then we will look at a more elegant solution where we will use xor so first we will do it without using xor so let's say in our array we have numbers so we are not bothered about uh what actually it's in the decimal because every decimal is internally represented in binary so it would be more easy to look in binary in order to visualize so let's say this is the first number the second number is also this and there is a number 1 0 1 and again 1 0 so you see this one zero occurs three times here and this number occurs just one time so we should return the value of this so uh the idea is very simple and you can even anybody can solve it so let's say we are dealing with integers and the number of bits used by integers is 32 so we can have an array of size 32 and this 32 denotes the 32 bits to represent an integer so all of the integers in this list will have 32 bits some of the bits will be set some of the bits will not be set so here we iterate for all the numbers of this array and what we do we uh first we look for all the first bits of all the numbers so we can have a loop here for i equal to 0 to 32 so this is not order of n this outer loop this is just constant 32 denoting 32 bits so first we will look at right most bit or least significant bit so i is 0 so we don't need to shift anything so we will do end with 1 so one is you if you remember zero everything is zero the least significant bit is one so if we do end with any number then everything will become zero except if this bit is set it will be one otherwise 0 so if this is set then we add ar 0 plus or air i in this case so in this way we will count how many numbers have this first bit set and here instead of just adding 1 to it we can also store modulo of this modulo 3 because whenever it occurs 3 times we have to reset that or you can do everything in the end also so let's say now you have the count of all the bits so here it will be 1 here it will be you see this bit occurs three times this occurs one time and this number is other way here i am storing in i so zero so you can think of it as one but for visualization let's keep it here only and then 1 and then 4 so now if you take modulo 3 this will be 1 this will be 0 this will be sorry 1 for modulo 3 is 1 so we get 1 0 1 which is the required result so first let's solve write the code for this in lead code then we will look at the other solution where we will use xor so we initialize it with zero so we look for all the bits so initially when i zero we are looking at the right most bit and then we will iterate for all the numbers so num right shift zero is nothing but the number itself but when we want to look at this uh second digit from the right we have to shift everything to the right and then again do xor with one or we could have left shifted one also then uh again right shift so in fact we don't need to do that we need to do this just one operation now we have the count of all the bits so result equal to result or bits i so whatever bits are left in this bits the count we are adding it to result we are building result out of that so this bits if you look at this array its binary representation we are converting that binary to decimal and we will return that and let's run it so there is some error here okay it's n not number so this solution works so let's go ahead and submit it and it's not that good the runtime let's try to submit again so the same solution if you try a few times timing will vary and here you can see it's better than 70 percent so this is quite good not that bad so now we will look at the other solution which is using xor so here the idea is that we will keep our two variables once and twos so once will hold so we will iterate through all the numbers of this array and after each iteration once will hold the bits which have occurred once for example when we just visit the first number then these bits are two and four these have occurred once and none of them have occurred twice because we have not even looked at two numbers so at the end of one iteration this should keep one zero and this should keep zero so this is after first number then we move here then uh none of the bits have occurred once because this has occurred zero times this has occurred two times zero times two times so one should hold zero and two should hold one zero because this width has occurred zero times this bit has occurred two times and this twos keep track of that so whatever bits have occurred two times these will be set to one here then in the third iteration uh we have to see which has occurred once this has occurred twice so this would be zero this has occurred once and this has occurred three times so it should also be zero so three times is equivalent to zero for us we only need to find the number which occurs once so we have to reset everything uh if it occurs three times and then uh what should be the value of twos so this bit has occurred twice this has occurred once so it should be zero then third bit has occurred once so this would be zero this has a cut thrice so this would also be zero and finally uh one should hold this one and this has occurred three times so it should be zero this has occurred once so it should be one and this has occurred four so it should be one so this ones will hold uh the bits of this number once will be true for the bits which has occurred once four times seven times and so on and this two should occur should be set when it's two times five times eight times and so on and if we have anything three this is same as zero so in the end when we have iterated through all the elements this once will be the value that we are interested in so how we can do that so let's run through an example so we will initialize this once and twos with zero so initially they are zero so we have remaining 28 bits also but since here for our example it's four it would be easier to visualize with just four digits and twos are also zeros because we have not started looking into the array at the moment now what we will do we have to iterate for all numbers so let's say these are stored in nums array so we will have so after each iteration this invariant is true that this once hold uh the bits of ones are set for the bits which have occurred one times four times seven times or we will think of it as just one time also these are all equivalent to one and this has occurred twice so when we encounter a new number what we would like to do so whatever is stored in two let's say third and fourth bit are set to one in this second and third so this means that these bits have occurred twice and now i have given i got another number which is let's say b3 b2 b1 b0 i want to keep track of what digits have occurred what bits have occurred twice so what we will do so some bits should have occurred once so in once some different bits should be set so whatever bits have occurred once and those bits are if present here then the exact same bits will occur twice so let's say uh bits b0 and b3 has occurred once and uh these were 0 in ones so b0 and b3 had occurred once but if b0 is also set in this new number n then its count will be 2 because this had occurred once and it's also set here so it should be included in the value of 2 so what we will do we will take 2 or once and n is the new number so uh whatever bits were already set into they will remain there and some new bits will be added with the help of ones but after this line you will see that some bits uh in two was one already but uh it's it has been added here because of this so uh this bit will still remain one but it has occurred in fact thrice because this bit was present in this new number so in two also it's still one it should have been zero so now two contents are two and three the bits which have occurred twice and thrice both so we will get rid of this soon first let's see how once will be updated so some bits have occurred once and one is keeping track of that so if we do xor with new number so this new number has some bits set so those will become uh unset here if it was already present in one because those bits had occurred once and these are also present in new number so now it has occurred twice so we don't need to get rid of that and this xor will exactly do that but uh in once uh if some bits has occurred twice let's say this b3 has occurred twice so it was 0 in this one but this b3 was present in the new number n so this is in once and this is in n we are looking at b3 so this can be zero due to two reasons in once either this width has occurred zero times or this bit has occurred two times so if this bit has occurred zero times then correctly now it holds one that is one times but if this bit has occurred 2 times and it was so that's why it was 0 in once but now this bit is present in n so this will become 1 so now this once holds all the bits which has occurred once or thrice so this two now contains all the bits which has occurred twice and thrice and this once contains all the bits which has occurred once and thrice so what is the common among these two the common is the bits which have occurred thrice so we can have another number thrice and this will be two and once so the common of these will be the bits which have occurred thrice and now we get rid of this thrice from both two and one so what we will do two equal to two and not of price so the bits which have not occurred thrice we do and with that so that thrice bits will get chopped off similarly for once equal to once and not of thrice and finally we will return that once so let's write the code for this so let's run it so this works so let's go ahead and submit it so again this works and you see that your time is better than our earlier solution uh most likely because this here we are doing modulo a number of times and these operations are generally are not cheap here we are not doing any of such operations we are just playing with and or xor not these kind of bitwise operations so it's giving very good result here so i hope you understood both of these solutions and we will see you in some other question of lead code
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
1,901
hello everyone and welcome back to my channel algorithm HQ today I am going to write the code and also explain you the algorithm for this find a peak element second problem which is there in lead code so let me give you all a small overview of this problem we are given with a matrix with M number of rows and N number of columns now our task is to find an element for which the elements 1 above one below one right or one left are smaller than this element also note that there can be multiple Peak elements in The Matrix and we can return position of any of those elements now let's understand this problem by considering the first example given in the first Example The Matrix given is 1 4 3 and 2. now the element 4 is a peak element because all of its neighbors are smaller than this that is 1 and 2 are smaller than this element and there are no elements above or at right same is true for this element 3 which is also a peak element in this case for now I can think of two approaches to check for the peak element in the Brute Force approach we will go to each and every element and check for all the neighbors if they are smaller than the current element in another approach we will move to the element which is greater than the current element and will not stop until we find an element for which all of its neighbors are lesser than the current element now let's go and understand the algorithm we'll take two pointers I and J initialize both with zero then we'll use a while loop to iterate over the Matrix while I is less than total number of rows and J is less than total number of columns now we'll consider the element at Matrix ing and check if there exists an element at left right below or above which is greater than the current element if true we'll move to that particular element by incrementing or decrementing I or J according to the Direction otherwise current pointers I and j i o answer as we'll always find a peak element but need to return an array even after the loop ends so we'll return an MDI now let's do a dry run over this as I and J both are 0 we are at this element one we'll check if there exists an element at right as there are no elements above or at left so we'll check if there exists an element at right which is greater than the current element so yes there exists this element 4 which is greater than 1 so we'll move to the right direction by 1 by incrementing J we are incrementing J because we are moving one column ahead then we'll come to this element 4 and we'll check if there exists any neighbor which is greater than this so no so for this case 0 comma 1 is our answer that is I comma J now let's go and write the code we'll take these pointers I is equal to 0. and J is equal to 0. then we will use a while loop while I is less than Matrix dot length and J is less than Matrix 0 dot length is the number of columns now we'll start checking if element at left that is I comma 1 that is I minus 1 is greater than or equal to 0. and element at left is greater than the current element which is I comma J F true then I will be decremented by 1. else if J minus 1 is greater than equal to 0. and tricks of i j minus 1. is greater than the current element I J if this is true then we'll move to J minus 1. else if I plus 1 is less than Matrix dot length so I plus 1 comma J is greater than the current element I comma J and this is the case when I is equal to I Plus 1. analysis J plus 1 is less than Matrix 0.10 that is the total number of Matrix 0.10 that is the total number of Matrix 0.10 that is the total number of columns and Matrix of I J plus 1 is greater than Matrix of I comma J that is the current element then field increment J by one else we create an area answer with I and J and return this answer now after coming out of the loop we will return an empty array uh I missed this semicolon here sample test cases are passing and the code is running successfully thank you very much everyone for watching and please don't forget to like the video and subscribe to my channel also please tell me in the comment section if I have to improve on something or if you guys want me to solve any other problems on any other platforms that's it for the video bye
Find a Peak Element II
equal-sum-arrays-with-minimum-number-of-operations
A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom. Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`. You may assume that the entire matrix is surrounded by an **outer perimeter** with the value `-1` in each cell. You must write an algorithm that runs in `O(m log(n))` or `O(n log(m))` time. **Example 1:** **Input:** mat = \[\[1,4\],\[3,2\]\] **Output:** \[0,1\] **Explanation:** Both 3 and 4 are peak elements so \[1,0\] and \[0,1\] are both acceptable answers. **Example 2:** **Input:** mat = \[\[10,20,15\],\[21,30,14\],\[7,16,32\]\] **Output:** \[1,1\] **Explanation:** Both 30 and 32 are peak elements so \[1,1\] and \[2,2\] are both acceptable answers. **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 500` * `1 <= mat[i][j] <= 105` * No two adjacent cells are equal.
Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.
Array,Hash Table,Greedy,Counting
Medium
1263
304
hi everyone welcome to the loophead today in this video we will be solving june deetco challenge and the question for today is range sum query 2d immutable the question is medium tagged and it states that given a 2d matrix handle multiple queries of the following type calculate some of the element of matrix inside the rectangle defined by its upper left corner row 1 column 1 and lower right corner row 2 column 2. implement the num matrix class num matrix end of matrix which initializes the object with the integer matrix in some region in row 1 in column 1 and row 2 in column 2 returns the sum of the element of matrix inside the rectangle defined by its upper left corner row 1 column 1 and lower right corner row 2 column 2. so we would be given a matrix a 2d matrix in which we would be given two indexes that is the upper left corners indexes and lower right corners indexes we have to find the sum of all the elements that are falling within this these indexes so in the first example as you can see the input is given in the form of num matrix some region now this sum region would be taking four parameters that is uh the starting index of the um sum of the region and the ending index of the sum of the region that is the starting index of upper left corner and the ending index of lower right corner so um here in the first example this is the matrix that we would be given as shown in the image and the sum of region function is called and it is called for 2 1 4 3 that is the index at 2 comma 1 and 4 comma 3. we have to find the sum of all the elements that lie within 2 comma 1 and 4 comma 3 that is at 2 comma 1 we have this 2 then we at 4 comma 3 we have this in the last row and the last second index of the column we have this 0 so all the elements within this rectangle that is 2 0 1 and 0 3 0 we'll have to add these elements and return it so our answer should be 2 plus 1 plus 3 and all the 0 also so uh it would return 2 plus 1 which is 3 plus 1 which is 4 plus 1 which is 5 and 5 plus 3 which is 8 so in our first case the answer would be 8. now for the second region we have 1 2 that is starting from index 1 and ending at index 2 so at 1 we have 6 at 2 we have 0 and the rectangle formed is this one 1 2 1 and 2 so all the elements are 6 3 2 and 0 we have to sum it all up and it would give us 6 plus 3 plus 2 plus 0 which is 11. so the next answer of this region would be 11 and the next some reason that we wish to get is 1 2 4 that is the element present at 1 comma 2 which is 3 and ending at 2 comma 4 which is 5. so the rectangle formed is this one 1 2 1 3 1 4 2 3 2 4. so all the elements are 3 2 1 0 1 5 adding them up we have 3 plus 2 which is 5 plus 1 which is 6 plus 0 is 6 plus 1 is 7 plus 5 is 12 hence our answer for this region would be 12 and hence it is here so how are we gonna approach this problem the first approach that you may be able to come up with is that we may start from the upper left corner indexes and start adding all the elements until we reach the lower right corners indexes so like uh we'll use two nested loops like we'll start traveling from the row until we reach the max column that is the desired column and we just end up adding up all the elements until we reach the last index of the lower right corner so once we reach and we return the sum that's the basic knife approach but in order to optimize it or like in order to pass all the cases uh we need some more uh like better solution for this so we are going to break this problem into sub problems that is we would be um traveling from column one to column two in each row like we have to travel row wise and calculate the sum of each row from starting from column one and ending up at column two and uh the resultant sum would be the sum of all rows we have been traveled through so um let me visualize what will be happening over here what if we had this 1d array in the form of the first row of this example let us say so um the cumulative sum at each index would be something like at the first index it would be 3 only because we have nothing and now 3 plus 0 is 3 again 3 plus 1 is 4 then 4 plus 4 is 8 and at the last we have 10 so this is what we have came so far so it would be like before 3 we have nothing so uh it would end up at being added as 0 so whatever we wanted the sum of these three columns what we will do is we will take the sum of all these elements starting from the first index to the expected column index and just subtract the starting column like uh we have to start from the first uh sorry the second column so we will just subtract the first column sum from all the columns sum and we will get the result so like here till this uh index we have the sum as 8 and the first index is summed up to 3 so 8 minus 3 is 5 this is what we wanted 0 plus 1 plus 4 is 5 this is what we'll do for each row let me just take you to the code for this so um we'll be having m n as the length of matrix which is the row number of rules and length of metrics of 0 which is the column number so we'll declare an array uh with all elements at zero and the number of rows would be one greater than the actual number of rows present in the initial matrix so this is zero for j in range of n plus one or i in range of m plus one will travel to each um element and just update it with the cumulative sum of each row so for r in range of m plus 1 and for c in range of n plus one will change self dot vp of r e and one more thing we have to start it with one because we have to keep the first row and first columns element to be zero only so we'll start with one and now it will be l dot bp of the previous element that is row remains constant and column is the previous one plus matrix off since in the matrix we have zero based indexing uh so we'll just have the element previous element in the matrix so this should do the work and yeah um let us see whether it works or not and before that let me just zoom it in and see so uh we have this uh let me just print what actually is happening in the so print um uh yeah so we are getting cumulative some at each indexes so yeah this is pretty much better than what we have thought okay so now we call this matrix and now we'll do the actual summing up okay so we'll write the function for the sum region okay we'll just complete it so we'll be having the current sum as zero and we'll start traveling for each row so for i in a range of row one plus one since in the dp array we have the shifted accumulator sum towards the uh one based indexing kind of thing so we'll be traveling it from row one plus one and we could i could have written row two plus one but since the range does not include the last element because it has to be row two plus two and we'll be summing up out plus equal to self dot bp of i and it would be column two plus one because this is the last index that will be traveling minus self dot bp of the elements that we don't have to include so this will be um sorry i and column one and we just have to return the output and this should pretty much do the work i guess yes so this is our code and this should work for all the test cases let us submit it and see whether it works or not and the time complexity for this would be o of n plus n okay so um we have submitted this and uh this should work for all the test cases i guess and our daily challenge has also completed but instead of this we can also do this in complexity so the approach for that would be instead of just summing it for a particular row or for each row we would be cumulatively summing all the elements until that row as well as the column like we would be cumulatively summing rows as well as column for a particular index so to do that we will just manipulate some code over here so we just add self dot dp of r minus 1 and see and we'll have to remove the overlapped element so it would be self dot bp of r minus one and c minus one that is uh if we are at six so the overlapped element here would be three like we'll have we'll be removing this uh above row and the column and also the um overlapped element that is present at the row just above it and the column just before it so uh this would do the work let us try to print what it does and let me just comment it out and see what is the output for it okay so um it is giving us what we expected so this is the cumulative sum over row as well as the column now in order to get what we are expecting as our answer uh we will have to write red on um self dot bp or first we will call it for row two plus 1 which is in the dp and column 2 plus 1 and we'll remove self dot dp of the next row or the current row and the previous column which is column one and also remove self dot dp of row one and column two plus one and at last i'd be previous overlapped element because it has been removed two times so it need to be added once so this is row one and column one so it should work let me just see it um and yes again um it is being accepted so this is a solution of one time complexity let us try submitting it and let me just zoom in to the code so that you are able to see it clearly so um yeah so what we did over here is we just did this thing we added dp of our mini that is dp the element present in the dp array in the previous row and the same column and removed the overlapped element because it has been added already once so while creating the dp we have to remove the overlapped element and while summing up we have to just uh add it again because it has been removed twice so um this is done and now let us submit it uh it should be accepted because this is a one time complexity and it does give us the right answer and yeah see the run time has reduced and this is how our code works and let me just zoom in so that you can see the whole code this is our code and we have done our third day lead code june challenge if you like this video hit the like button please subscribe and share with your friends until next video stay tuned thank you bye
Range Sum Query 2D - Immutable
range-sum-query-2d-immutable
Given a 2D matrix `matrix`, handle multiple queries of the following type: * Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. Implement the `NumMatrix` class: * `NumMatrix(int[][] matrix)` Initializes the object with the integer matrix `matrix`. * `int sumRegion(int row1, int col1, int row2, int col2)` Returns the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. You must design an algorithm where `sumRegion` works on `O(1)` time complexity. **Example 1:** **Input** \[ "NumMatrix ", "sumRegion ", "sumRegion ", "sumRegion "\] \[\[\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]\], \[2, 1, 4, 3\], \[1, 1, 2, 2\], \[1, 2, 2, 4\]\] **Output** \[null, 8, 11, 12\] **Explanation** NumMatrix numMatrix = new NumMatrix(\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]); numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 200` * `-104 <= matrix[i][j] <= 104` * `0 <= row1 <= row2 < m` * `0 <= col1 <= col2 < n` * At most `104` calls will be made to `sumRegion`.
null
Array,Design,Matrix,Prefix Sum
Medium
303,308
763
I am in office amazon friendly this problem create partition but if there will be then prostate gland party subscribe and subscribe not present in the meeting at Chittor Fort but slide subscribe and subscribe The Amazing busy schedule fixed when LED notification subscribe and subscribe the Channel subscribe Who is the special of Tamil Nadu when the skin takes over the last leaf subscribe like and subscribe to agni puran kunwar and support to arvind solanki like share and subscribe the sudhir 123 45678910 subscribe 123 456 subscribe Thank you friends that on the day of CBSE, the husband again came to the lead, till the morning of JHKLPILO, subscribe the channel 1234, fix a pipe 600, 11123, Shyam, 1080, will start OK subscribe The Channel subscribe And subscribe The Amazing That And Insted O King That Not Interested Channel Subscribe My Channel Like and Subscribe My Channel [ My Channel [ My Channel Subscribe To A Subscribe To A Subscribe To A Real Adversities When 1981 Test Match Khel He Swayam Updates Normal Person Ko Subscribe Must Subscribe To Jo Koi Jis Zameen Se Zameen 131 honge den to end wa subscribe this channel like and subscribe to ki masjid coming after wave quantity ok subscribe my channel don't forget to subscribe don't forget to subscribe don't forget to subscribe volume has been increased to maximum ok so not been appointed so First House Come To Do Subscribe My Channel Subscribe Egg Subscribe To Ki Calculator Map Tumhe Sunidhi - Calculator Map Tumhe Sunidhi - Calculator Map Tumhe Sunidhi - Positive A Follow Back To My Channel Subscribe Must Subscribe Our Channel Like This Kal Subah Bank Wahi Arth To Nadu Avneesh Avighna Oil And Oil subscribe and subscribe the Video then subscribe to the Page if you that Suji Research Studies Survey Research Claims No Deposit subscribe The Video then subscribe to the that you Important Temple Path Loot Subscribe Now School Subscribe Channel Subscribe Voice Mail well wishes ok no if you liked The Video then subscribe To My channel subscribe to ki and jewels main apne department ali posted hai So sit in the report, the norms, improvements to improve were to fold in the eyes, not with native with boys, subscribe my channel, aap pipe laga do hai na puja looter simply ise don't thing worry subscribe to that with air intake and intact but traffic Ok good night thank you That Raghukul's physical new update was walking I have returned to make you a ranger and Drishti She is a diabetes patient and subscribe - 1800 - 1800 - 1800 The The The world must now be acting way Note for channel Subscribe This is not Absolute to aay please the walking and language ok no problem related question SDO letters video [ question SDO letters video [ question SDO letters video please subscribe to o madam date fix hai ₹ 5 mein ₹ 5 mein ₹ 5 mein aapne subscribe Video Please subscribe and subscribe the Channel Ko subscribe kare ek tara mude work And Destroy Your Feet Step Complete The Time Presidents And Subscribe Thank You For Watching Video Subscribe To
Partition Labels
special-binary-string
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
String,Recursion
Hard
678
1,023
hello hi everyone welcome back to the channel so today in this video lecture will be solving this problem camel case matching so this is yet another problem in the trial series which is a medium problem so let's read it we're given an array of strings queries it contains strings and a string pattern we have to return a Boolean array answer where each element in the Boolean array the ith element is true if the ith query matches the pattern otherwise it is false a query word matches the pattern if we can insert a lowercase English letter letters to the pattern so that it equals the query you may insert each character at any position and you may not insert any characters so let's better understand the problem statement using an example so let's take this example you can see that here we have queries Fubar test football frame of force feedback pattern FP now the pattern is FB means let's go let's check the very first string which is Foo bar can I construct this string Foo bar using the pattern which I am given the pattern is FB I need to insert this double o and this AR after B these are the set of characters which I need to insert between these characters which we are given so we can see that the foo bar can be generated like this so let's understand it better so we are given the pattern given as FB and we need to construct F double o b a r so F and B are capital so what I can do is in this pattern I could insert this double o plus b then I can insert this a r okay this will give me full bar okay that's what we are given it matches the pattern if we can insert lowercase English letters to the pattern so that it equals the query so we simply inserted these lowercase letters into the pattern and it Sim it equals the query this was the query let's take the next word is foobar test so it is 4 bar test f b and t there are three characters which are capital observe the pattern we do not have capital T here that means this capital t is missing which is present here in the query means we can't insert lowercase letters we need to insert an uppercase letter to make this FB equal to 4 bar test I require this capital T which is not here and inserting capital t is not allowed so that means will return false for this type of query let's see the next query it is football so for football it is T capital or small T is small okay foot ball again we can construct this because we have two capital letters f and B and which matches with the letters which are which we are given in the pattern that means in this pattern just add this double o after f then add B and after B add a Double L and that is going to give me foot ball correct let's go for the next query which is frame buffer f r a m e capital b u f e r and FB is this like the pattern is FB can I create this string from this pattern yes insert r a m e after f then add B then add u f e r after B this will give me frame buffer fine so let's take the next which is force feedback capital f o r c e f e d capital b a c k so we have two Capital F's and one capital B so we can't create this string okay so you got the idea what I'm trying to do here so let's see how we can solve this problem you may have got idea that it's easy all we have to do in this problem is like we're given a pattern the pattern given is FB just create the try corresponding to this pattern so create a try corresponding to this pattern so root f then B now we have created the try corresponding to this pattern which we are given so insert it into the try and for any string in the query array let's take football this football what I want to check is if I if the characters if the uppercase characters all of the uppercase characters in this query string are present in this try fine that's all I want to check if all of the characters present in the query are there in the try like here in this case f is here F matches here B matches here that means in the query all of these characters are present that means this query can be constructed otherwise it cannot be constructed so that's all we have to do in this problem okay just iterate over the query string like start from the F start from F check if it is there in the try so start traversing from the root node do we have f as a child of root yes we have so move to this f move to the next character which is zero do we have sorry which is O do we have o as a child of F small o no we do not have okay we do not have o as a child of f now here I will check now here I know that o is not present this o is not present now I need to check whether the character which is not present as the child node for this F is an uppercase character or is a lowercase character if it is a lowercase character then that's fine move to the next character but if it is a uppercase character and it is not present as a child node for the F that means we cannot construct the query string but here it is lowercase so we just move to the next character which is O do we have o as a child of f no now move again to next character which is T do we have t as a child no T is also not present as a child now we move to B do we have b as a child for f no we do not have b as a child of f that like we have b as a child of f here we can see that b is a child of F that means we have b as a child of f so move to this child and now move to the next character which is a like is a child for b no it is not there now check we check if a this a is a capital letter or a small letter it is a small letter so it doesn't matter whether it is present or not we just have to care about the capital letters so we move to L is it present as a child of B no check if it is a capital or small it is small so we do not care we move to again l is it present as a child for b no it is not present is it capital no so we do not care fine that means we conclude that this football can be constructed from this from the pattern which you were given which is f b fine so let's take an example where we cannot construct a string let's take that type of example so let's take this example which was Fubar test let's take this example Foo bar test now here we observe that we find F we move to F because f as a child of root we move to F we do not find these small O's we simply skip them we do not have to check them into the try because we do not expect them to be present in the try so we move to B we expect B to be a child for f and it is there okay so we again skip this AR we don't expect them to be there in the try so we check for this capital T do we have capital T as a child for b no we do not have but we do expect it as a child of B because this is a capital letter and we must have capital letters we can't insert capital letter we can just insert these small letters so that means we return false for this type of string you got it that's how we're going to solve this problem and I hope you got it rest is simple just take the pattern create the corresponding try and now into the search function of the tries just implement this type of search function we are where we are just sensitive about the capital letters so we find a capital letter we check if it is present in the try that's good if it is not present then we return false right from there okay so let's see so let's just see the implementation part so this is the solution class we have insert function we have search function and this is the camel match function which returns this type of Boolean array so let's calculate the size of this query queries array let's create a vector Bool of the same size initialize it with false then okay this index I will be used to iterate over this res array to store the results so before that insert this pattern into the try so here in this insert function um okay so but before that let's just implement this try node so we have two things in the dry node since we also include capital letters so we can't take a array of 26 children so we have to take a map so we'll take a map try node let's call it children okay now also take a Boolean variable is n to Mark if a particular character is the ending character or not here initialize a root node so try a node root new try node so to insert it create a current node initialize it with root node iterate over the word check if this current character is present as a child if it is present if it is not present as a child then insert it into the try so current children C equals to new cry node otherwise move to the child node if it is present Mark the is and as true then here in this Boolean function in the search function what we're going to do is so we want to search for this word in the try so we just care about the capital letters so if we have some character children which is not there we're gonna check if it is like if it is uppercase or not so if it is not there and it is also an uppercase letter so is upper is this right function U is upper for this character C if it is the case then we return false right from here otherwise we check if we have the children if this children is if this child is present then move to this child okay and at the end of this function return is current is and okay that means we have reached the ending character and you want to check if it is marked as the last character in The try means you want to utilize all of the characters of the pattern if we do not utilize all of the characters even in that case the given word is invalid okay so and here we will iterate over all of the words all of the queries and call this search function for the query that we have okay and at the end return this res okay we have a problem okay we refer to c u r it got accepted let's submit it okay so that's all I thank you got the solution so we can see that the time complexity is same the time complexity is basically for insert function it is Big of n if n is the length of the word length of the pattern that we have and for the insert function sorry for the search function the complexity is Big of M where m is the length of the string that we are searching for and we're looking and we'll look thank you
Camelcase Matching
time-based-key-value-store
Given an array of strings `queries` and a string `pattern`, return a boolean array `answer` where `answer[i]` is `true` if `queries[i]` matches `pattern`, and `false` otherwise. A query word `queries[i]` matches `pattern` if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters. **Example 1:** **Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FB " **Output:** \[true,false,true,true,false\] **Explanation:** "FooBar " can be generated like this "F " + "oo " + "B " + "ar ". "FootBall " can be generated like this "F " + "oot " + "B " + "all ". "FrameBuffer " can be generated like this "F " + "rame " + "B " + "uffer ". **Example 2:** **Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBa " **Output:** \[true,false,true,false,false\] **Explanation:** "FooBar " can be generated like this "Fo " + "o " + "Ba " + "r ". "FootBall " can be generated like this "Fo " + "ot " + "Ba " + "ll ". **Example 3:** **Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBaT " **Output:** \[false,true,false,false,false\] **Explanation:** "FooBarTest " can be generated like this "Fo " + "o " + "Ba " + "r " + "T " + "est ". **Constraints:** * `1 <= pattern.length, queries.length <= 100` * `1 <= queries[i].length <= 100` * `queries[i]` and `pattern` consist of English letters.
null
Hash Table,String,Binary Search,Design
Medium
2161
213
Hello everyone welcome to my channel with mike so today we are going to do its video number six before our DP concept ok before starting some speech i.e. before starting some speech i.e. before starting some speech i.e. motivation see everyone face failures everyone face rejection everyone is motivated come some point of time In life okay remember only dose have one hosted up and caught moving okay so don't stop they have you cup moving never ever give up okay never ever stop and cup moving okay you remember we started 1d base dp in this Now okay and in 1db, we have again done Meenakshi number, climbing shares, we have done house D one, today we are going to do house rubber, we are okay and I told you that you can refer but notes, gave all the things in it, Rakhi. I have also given the link of the video. Okay, now before starting, you will see the house Robert One in this place. Come on, this is your prediction. It is very important so please go and watch it first, after that come here. Okay. Let's start House Robert 2 Lead Co Number 23 is medium level question but it is very easy if you have made house of one then it is just copy paste its code just copy paste it and this question will be solved so let's start Let's start the question. Do you understand this? Look at the house number, you are exactly like House Robert One, there is only one difference in it, I will tell you after reading it, then you will understand, it is the same in this too, there is a thief and only one is planning Hajj. Some houses, some amount of money is kept in every house, they have to steal it. Okay, the house that comes in this place in a circle, this is the different and rubber is fine in you, Redmi, the last one is fine, that is, if mother takes your house, whatever you give. 0123 If this is your house, then what was there in house number one, that this house is here, Thoughts It, what is it in this, Hyderabad tu mein ki, which is never one of zero, what was there in house rubber one, three That is, after doing 0, one is there, one's tu is there, you are three, but three's ni is also back to zero, okay, what does it mean that if you steal at zero, then now there is no theft at three. Can do, that is, one is the adjacent house of zero but it is also adjusted to zero, okay, similarly, the adjacent house of three is you, but the adjacent house of three is also zero, okay, what does it mean that if you steal on zero? So you cannot steal on three, okay or think that if you are stealing on three, it means that you would not have stolen on zero, only then you can do it, okay, this is clear, let's move ahead. The rest is all from the question, here is the last one meaning by adjustment house security system connect it bill automatically contact now some interior name is given I am example late one two three one ok indexing do zero one two three Amount of money has been given in every house as return. Maximum amount of money you can drop tonight without auditing by police. It is absolutely a question, only this time you have to pay attention to one thing that brother, if you steal on one then the adjacent of the forest. What is it that you cannot do here, one more thing has been given that your adjacant is also this one, you cannot steal on this one too, so if you look at it then this is definitely of house number one, is n't the question exactly two? Will try this thing first, I am stealing on 0 house, so for me, which one will be 123, how did I become one, don't steal in the last house, Shakti, both of them are connected, all the houses are arranged in a circular way, okay. So what will be the valid index for me? I will steal the zero and the third one will be canceled just like that, so see, I have taken zero till one and till the index, it must be clear. Okay, if we see, then how will one go? So, what is my starting index, what is zero and what is my ending index? Look, I am taking it, that is, N - 2 is I am taking it, that is, N - 2 is I am taking it, that is, N - 2 is clear till here and what is the second one, brother, how are you, what is there in me that I have not taken 0. If zero is not taken then it means this third house can be taken. If there are chances, then what will I explore and what is the next number? One, three, okay, so here I write what will be the index starting index, for me it will be one. And what will be the last Sunday N - 1, And what will be the last Sunday N - 1, And what will be the last Sunday N - 1, why in the beginning because I was zero, I am not taking that, now look after this, now pay attention to the most important thing friend, look at this lesson and look at this lesson, both the houses are equal to one, you are not able to see the house rubber. It is visible that there is a circular that if you choose zero, then you cannot choose third, otherwise I have already discarded that here, if you choose zero, then see here, I am not choosing third, either zero. If it doesn't heal then I am choosing the third one, that thing is here, so I am taking care of it, after taking care of it, how are two becoming possible, how can I have number one, how can you be number, okay then how can you be number one and you too? If you look carefully, this is the question of house number one, so we don't have to do anything, I am a housewife, I will copy and paste the code of house number one, what will I say once, from index zero to index 2. Find out the answer till the index and show me the answer is ok and then I will say once. Find out the answer once and then I will say ok. The maximum of both will be my answer. Thoughts have been converted into rubber bands. It is ok, so that is why I am saying. Okay, we have not done anything, we just have to paste the same code as Ho = 1. we have not done anything, we just have to paste the same code as Ho = 1. we have not done anything, we just have to paste the same code as Ho = 1. In this too, what did we think about, we had given in the question that if you steal zero thousands, then you cannot do the third house on your own, right because circular. They are connected, it is Adjacent, it is correct, yes, now it was zero, we take it as mother, so it is an obvious thing that you are not chosen anyway because it is Adjacent, but you cannot use Third also because Third is also Adjacent to Zero. Till now it is clear that there was zero, if you select it, then you cannot select the first index and you cannot select the third index as well, that is what I have written here, okay, now look here, pay attention, then select the first index here, what did I say that Here I have got zero on this and here I have got on this, okay here also I have two possibilities that brother, should I take the house with zero or not, if I am late then how much rupees will I get, ₹ 1, I am not late. So zero rupees will I get, ₹ 1, I am not late. So zero rupees will I get, ₹ 1, I am not late. So zero rupees are okay, our 1 2 3 is 1 2 3 and if you look at this how, if I have taken the zero solid one, then now the problem is that I cannot take it, then it is adjacent, here A will go and if I have not taken it. Okay, I haven't taken this one, so I can take this one, here A will go and so on, just be D, a tree will be formed with one, absolutely similar, okay, here too it is going to be exactly the same, here also there are two options that I have taken this house. So you will get two rupees, if you don't take it, you will get zero rupees. If you take it, you will get 231. So I can't take it. Right ADJ If you can't take it to the house, then A will come here. Okay. And if you don't take it, then 2 3 1. If you don't take it, then you are gone. And I can take it, the adjacent one is fine, this thing has become very easy, that is, now we do not have to do anything, I will write the function separately, once I will say that brother, if you want to take the one with zero, then calculate n - 2. that brother, if you want to take the one with zero, then calculate n - 2. that brother, if you want to take the one with zero, then calculate n - 2. Show me, it's okay from the house, or else he will say, 'Friend, I don't want to else he will say, 'Friend, I don't want to else he will say, 'Friend, I don't want to take the zero one from the one. If I take it from the one, then I can take even the N-1 house, right? Find out the answer from the one and take the zero one from the one. If I take it from the one, then I can take even the N-1 house, right? Find out the answer from the one and show me. The maximum of the two will be my result. So if seen, the code of house number one is very similar, meaning it is the same. If you have to copy paste, then I will just copy paste the code of house number one and just send different indexes and get the answer from both. Okay, so now in this video. I will do Recjan Plus memorization, after this there will be a separate video in which what I will do Bottom Up, you can also try, you have to write bottom up, you just send the indexes separately, it is okay, after that you know a separate There will be another video coming in which you know what I will tell that House Robert One can also be made in constant space, this dropper which I told about bottom up, you can make it in constant space only and I will also I will tell you why it is made from constant space, it is okay, similarly house rubber can be made from science house, you will also be made from constant space because what are we doing in house number 2, brother, let us code for house number one only. It's okay, so we will make House Robert Tu also with constant space. Okay, then a separate video will come and this will also come a separate video, but today's video, I thought exactly the same thing applies here because I am using the same code of house number one here. Okay, so let's solve it by meditation in regression and see if you are able to pass the test cases. So let's code it. With recension, see, just let you know how to throw one. We are going to copy and paste the key code, okay what do I do, but if you write Mike, then I am copying and pasting my code from there, okay, you do not copy paste, you write it yourself, I am just to tell you that the key code. I am doing it, okay, I went to 1dp here, what is house one, recognition and memorization, okay, starting here, it means there is only one house, so just steal from there and take out the other and if this is equal, you are the same, then brother. Out of the two, take out the one which is maximum, steal from it and take out the one which is ok, copy paste, Thoughts IT, I minimize it is ok, the house with first house index, if people are taking what results, then zero will have to be sent. N - Right, we can go till the 2nd house, then N - Right, we can go till the 2nd house, then N - Right, we can go till the 2nd house, then what will we do, I will set it again because obviously it is a matter of doing it twice, tomorrow, okay, so let's do the house number 1 again tomorrow, what am I saying this time, take the first index house, okay. What will come of this first index and what was it mine brother how were you right how were you in me brother what will we do take first ho second house na i.e. first ho second house na i.e. first ho second house na i.e. first index with first index if mother takes the house or first index if Once done, the maximum of the two will be my result. Pay attention to one thing here, see what we wrote here. This is the code of my house dropper one. So remember what we used to send. It will start with Xerox and this means N. Used to send the size, there was no index, this N is my size, it is okay here, the house from zero to N - 2 house from zero to N - 2 house from zero to N - 2 is okay, so here the return in equal tu will not be zero because that look, what is N - 2, this is not be zero because that look, what is N - 2, this is not be zero because that look, what is N - 2, this is my index, right? Mines tu is a valid index and here n - 1 is also a valid index ok n - 1 is also a valid index ok n - 1 is also a valid index ok so here we cannot return the value of n this will come n - 2 which is a valid value of n this will come n - 2 which is a valid value of n this will come n - 2 which is a valid index and how to get the value of n - 1 for tu There will be an index and how to get the value of n - 1 for tu There will be an index and how to get the value of n - 1 for tu There will be an assignment here, which is a variety index, so you will not apply equal, if it becomes greater, then the return will be zero, then it will be out of bound for us, it is clear till here, dry it and do it definitely, it is the code of Just House Dropper One. Ok, let's check whether we are passing or not, after that let's submit and see the question using recognition and memorization. Next video will be on this. Listen very carefully in which we will make it from bottom up also and after that also a video will come in which we will make House Robert One. And ho is this rubber, you will make both of them bottom up but will make it with constant space, it is okay so I hope, I am able, you help, there is any doubt, resident in the common area, I tree, help you out, give gas, next video, thank you. You
House Robber II
house-robber-ii
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are **arranged in a circle.** That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and **it will automatically contact the police if two adjacent houses were broken into on the same night**. Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_. **Example 1:** **Input:** nums = \[2,3,2\] **Output:** 3 **Explanation:** You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. **Example 2:** **Input:** nums = \[1,2,3,1\] **Output:** 4 **Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** 3 **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 1000`
Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the House Robber, which is already been solved.
Array,Dynamic Programming
Medium
198,256,276,337,600,656
20
to determine if a given set of parentheses is valid this is a very basic problem but at the same time it is very important because it has a lot of different applications and it is asked in a lot of different ways the underlying concept however Remains the Same One such sample problem is available on lead code so let's see what we can do about it Hello friends welcome back to my Channel first I will explain you the problem statement and we will look at some sample test cases going forward I want to quickly go over what do you actually mean by valid parenthesis and then we will try to approach the problem gradually we will take the help of a stack data structure and then arrive at an efficient solution as usual we will also do a dry run off the code so that you can understand and visualize how all of this is actually working in action without further Ado let's get started first of all let us try to make sure that we're understanding the problem statement correctly in this problem you are given a string that has both the opening and closing brackets of all the different types so you have curly braces you have the normal brackets and you have the square brackets as well correct and now you have to determine which of these strings are valid so when it comes to valid parenthesis what is the rule that you should know the Only Rule that you should know is that if you are opening a certain kind of parentheses then you have to close it as well and you have to close all of these brackets in the same order in which you are opening them so if you're opening the normal brackets first then you have to close them first as well in the second example if you are opening the square brackets first then you open the curly brackets first then first of all you have to close the curly brackets and only then you can close the square brackets so that is what a valid parenthesis actually mean so in this problem let us say you have these sample test cases for the first test case you can see that we open a normal bracket and we close it so I can say that for the first test case this string is valid and I will return a true correct if you look at the second test case now I open a square bracket first and then I open a curly bracket after that if you check I close my curly bracket as well so far so good move ahead now I open a normal parenthesis and then I close it as well so this is also valid and now what are you left with you are left with one more square bracket and you close it so this string is also valid so once again you return a true for the third test case what do you open a normal bracket first and now before you can close any other bracket first of all you have to close this one but what are we doing over here we close a square bracket first and this is not valid so for this particular test case you need to return false as your answer so if you feel that the problem treatment is now even clear to you feel free to first try it out otherwise let us dive into the solution before you start working out a solution you must first try to understand why these problems are important and what are its applications for example you might have seen these kind of equations right and if I ask you that go ahead and solve it how do you approach this you do not just jump on it right you will try to analyze this string and then determine that hey this is an inner bracket and that is what I have to solve First Once I solve this then I will look at some other bracket and then I will start looking at all of these outer brackets as well so this is why valid parentheses are very important they tell you the order in which you have to go about solving your problem if this string was invalid let us say instead of this string you had a curly braces over here right then how do you solve this problem it is not possible Right This is not telling you anything so that is why these problems are really important and you will find them in a lot of interviews basically what you can now do is you can get rid of all of these variables and all of these operators so ultimately your equation translates to a string like this and you just have to determine if this string has valid parentheses or not if you try to approach this problem in a Brute Force way how would you go about it you would Traverse this string and then you will try to solve this innermost bracket first so what I'm doing is I'm traversing the string and I get all of these opening brackets right next if you move ahead you see a closing bracket over here right and now you go back and check hey where did I find the opening bracket you found it over here so you know that okay this is the portion that I have to solve so for a root Force approach you will start to move from the front until you get a closing bracket as soon as you get a closing bracket you move backward and try to find the opening bracket you found this pair right so you will remove it from your string and now your problem becomes this you got rid of one set of brackets once again you will do the same approach right you will start to look ahead and then you will find a closing bracket once again you go back to see hey where is my opening bracket you found this and then once again you will eliminate this set of brackets so now you get this string you will keep on doing this ahead and ultimately if all brackets are gone yes the string was valid otherwise you will have one or the other dangling brackets and that is how you can say that hey this string is not valid so this is a Brute Force approach and it will work every time but you will end up taking a lot of time just to analyze your string again and again correct so definitely it can be done in a better way if you try to notice when you are traversing your string and as soon as you find a closing bracket what do you look for the opening bracket right so you will look for the most recent bracket that you had encountered and that gives you a hint what does that mean it means the last character you just encountered that is last in first out and it gives you the hint of a stack data structure if you're new to stack data structures I would highly recommend you to pause this video and look at my introductory video on Stacks first but if you're aware with them let us move ahead and take advantage of the stack data structure to come up with a very efficient solution okay so now I have a stack data structure and I have the same string with me you have to determine if this string has valid parentheses or not one way to approach this problem will be that you start traversing the string from the beginning and what is the first character that you get an opening bracket right so if your string has to be valid and if you get a opening square bracket then definitely you will want a closing square bracket as well correct so what you do is as soon as you get a opening square bracket just add a closing square bracket to your stack and now move ahead now you get a opening curly bracket and if your string has to be valid then there should be one closing curly bracket as well correct so I will add a closing curly bracket to my stack as well just wait for it a little while and all of it will make sense to you now move ahead what do you see a normal opening bracket over here right and for your string to be valid you should have a closing normal bracket also right and if you notice what are we doing over here we got all of these brackets in this order right and in our stack I am storing this order I'm preserving this order so what happens next I see a closing bracket this time as soon as you see a closing bracket you need to search hey do I have opening brackets for it now look in your stack if you pop an element what do you find a closing bracket that means there was one opening bracket as well right so it simply means that this set has been taken care of so what I will do is I will just remove this element from my stack and now just move ahead once again you see a opening square bracket an opening square bracket means there has to be a closing square bracket also so just add it to the stack so basically if you're getting any opening bracket just add its reverse closing bracket to the stack and now you have a closing bracket as soon as you see a closing bracket just look at the top element in your stack the top element is the same it means that hey I was able to find a pair so once again just remove this now move ahead what is the next element it is a closing curly bracket look in your stack you have your closing curly bracket over here so just remove this element once again so far so good what happens now you get a opening normal bracket so add a closing normal bracket to your stack move ahead you get a normal closing bracket so look in your stack it is the same so just pop this element and you can move ahead you get the last element and that is a closing bracket and if you look in your stack you have the closing square bracket as well they both are same so you simply remove it from the stack if you notice you have traversed the entire string and your stack is also empty that means all of the brackets are taken care of so if this condition is true if you reach the end of the string and your stack is empty you return a true so if you notice in just one scan of the string you were able to determine if you have valid parenthesis or not similarly let us look at one example where the parentheses are not valid what will happen then you have a opening bracket so I will add a closing bracket in here correct the next one is a opening curly braces so I add a closing curly braces the next is a normal parenthesis so I add a closing parenthesis move ahead now you see a closing parenthesis over here and on your stack also you have a closing parenthesis so well and good you remove this now move ahead you get a opening square bracket so you add equivalent closing bracket over here move ahead now you see a closing curly bracket but if you check your stack you have a closing square bracket and these two are not the same that simply tells you that one of the brackets did not close properly or one of the brackets did not open properly so as soon as these two elements do not match simply stop over there you can say that this string is invalid and return false as your answer now based upon this idea let us quickly do a dry around of the code and see how it works in action on the left side of your screen you have the actual code to implement this solution and on the right I have a sample string that is passed in as a input parameter to the function is valid so beginning off with the dry run what is the first thing that we do first of all we create a character stack and this will store all of my parenthesis moving ahead what do we do now we start a fall Loop that will iterate over each of these characters in my given string and what do we do over here we check each of these characters so if I get any of the opening parentheses then I will add its equivalent closing parentheses to my stack so if I have a square bracket then I will add the closing square bracket to my stack if I have a opening curly brace then I will add the closing curly brace to my stack so for the first three elements I will add their equivalent closing brackets to my stack now look at the next step what happens if you get any other character than the opening bracket so let us say I get a character that is a closing bracket right it won't match any of these conditions so what do we try to pop from the stack and on popping if I find the same element then well and good just pop the stack and continue on otherwise you can simply return a false so for this particular scenario as soon as you pop they both are same so the Stag gets popped out and your Loop will run once again you encounter this opening bracket so you will add a equivalent closing bracket over here so this Loop will go on and at any instant if the closing bracket does not match the top of the stack then you will simply return a false or at any moment if your stack is not empty at the very end then also you can simply return a false because it means one or the other parenthesis did not either open or close correctly the time complexity of this solution is order of n because you only do one iteration to Traverse through the entire array and the space complexity of this solution is also order of n because you need that extra space to store all of the elements in your stack I hope I was able to simplify the problem and its solution for you as for my final thoughts I just want to say that this problem has a lot of different applications for example right now you just have to determine if this set of parentheses are valid then there can be an extension that you have inserted all the variables and some operators as well then how do you determine if it is a valid string going forward someone can ask you okay what is the maximum depth of the nesting of the parenthesis that you can find similarly you can also be asked that okay what is the minimum number of parentheses that you have to remove to make this a valid parentheses string so all of these problems are related and they all take the help of the stack data structure so let me know what all such problems you come across also let me know what problems have you found while going throughout the video tell me everything in the comment section below and it will be helpful for anyone else also who is watching the video as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends also a huge shout out to all the members who support my channel this really keeps me going also I want to give you a quick update as I will be releasing my playlist on all the introductory concept of graphs so stay tuned and until next time
Valid Parentheses
valid-parentheses
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. 3. Every close bracket has a corresponding open bracket of the same type. **Example 1:** **Input:** s = "() " **Output:** true **Example 2:** **Input:** s = "()\[\]{} " **Output:** true **Example 3:** **Input:** s = "(\] " **Output:** false **Constraints:** * `1 <= s.length <= 104` * `s` consists of parentheses only `'()[]{}'`.
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
String,Stack
Easy
22,32,301,1045,2221
49
another day another problem so let's Solve IT hello beautiful people today we're gonna solve the group anagrams problem so let's start by reading the problem given an array of strings grouped anagrams together you can return the answer and any order so the question give us a list of words or less of string and they ask you to return a function of a list that have a group of list of anagrams and as we know undergrounds are worked as brightened by the same letter but rearrange it differently for example the word zob is about because both of these words have the same letters but rearrange it differently so let's say we have a group of strings inside list e t tan eight net and bat elsewhere gonna be a list that hold a group of list of anagrams the unusual gonna be a list that hold a group of lists of anagrams so there is a two way to solve this problem the hard way and the easy way so let's say about the hard solution first we also try to put all of the letters in the string inside the list and alphabetical order and after that we're gonna sort all the words inside the list alphabetically or an order but the problem is that we don't know how to find the original word from which we can make an anagram so let's change a little bit how we are going to solve this problem instead of putting the word an alphabetical order we will make a new list or array of indices and the indices gonna be attached to each word inside the list and after that we saw the word alphabetically and we're gonna start sorting the word that are already sorted but the difference between the first way that we have done before is that each word gonna have his indices like his index for example it's gonna have zero T gonna have one tan gonna have two eight gonna have three not gonna have four and that gonna have five and after that we sort the letter inside the word so each time we sort word inside and unless it's gonna be holding his indices like for the first one ABT it's going to hold the five which is for Resort and it was at the last index of the list so now we have sorted all the indices according to the sorted order of the list that have all the anagrams sorted so with this method we can easily find the original word that have formed the anagrams by just using the indices or the index so all we're gonna do now is to iterate throughout the array of indices and we're going to say at the first index what anagrams we are dealing with it first one is going to be ABT so we're going to create a new group of anagrams and add the original word that have formed for example bad to the next list and then we move to the next word and then we get to the tricky Step at index 0. our anagrams are e80 so the new anagrams are AET and we add at the original word to the list which is e a t eat it because the index is zero then we move to the next indices in this one we repeat the same thing and that index one we are dealing with the anagrams e a t and the original word have formed the anagrams RT at index one and we add it to the group of anagrams then we move to the next index which is three so the anagrams are a e t and the original world that have the index 3 are ate the next index are two with a new anagram which is a and t we look for the word at the original list so the word is 10 plus index are four with underground ENT so the original word are not and now we have found a group of anagrams so this is the way we solve this problem it's a little bit hard and require a lot of thinking so for the code explanation the first thing we're gonna do is to make a new list with all the same strings but this time we will put them an alphabetical order and we will go throughout the string and call the sorted function for each one this will create a list of the letters and then we will use the join method to turn the list of letters into string and after that we create a list of indices and we sort the list of indices such that they represent the order of the sorted strings but the sorted string should be sorted alphabetically this line basically says when we are dealing with the index 0 and 1 compare the two sorted string at zero and one see which one comes before the other alphabetically and sort them then we're gonna create an empty array that's going to be the result and we're going to initialize a current anagram list which is going to be an empty array and finally we're gonna have the current underground that we are looking for it that's going to be the sources string at the first index of indices array so we're gonna iterate throughout the indices we're going to take the string at the current index also we're gonna take the sorted string at the current index and we're gonna check if the salt and string are equal to the current underground if yes we add it to the current and ground list and we continue if the search and string are not equal to the current anagram we add the current underground to the result and we update the current anagram list to the new world and we change the current and gram to the search and string because we are at the new stream because we continue even if the current is not equal to the sources string finally we add the last current underground list to the result list because we are breaking the loop before we are done with it and we return the result foreign solution the time complexity are of as n log n plus n s log s so because we are sorting the arrays and you know that sorting takes off and log n where n is the length of the input arrays so for every string we have S strings so we sort each string which is going to take office and login the second thing that we have done it is that we have an array indices and we are sorting the indices based on the order of the alphabetically undergrounds that are already sorted so the S log is come from sorting an arrays of length s and n gonna be the comparison that we compose the word each time for the space complexity is going to be of s and the simpler solution and the optimal solution is once we have sorted all the word we can just group them in hash table and group all the anagrams together so we're going to iterate throughout the strings in the input strings and we sort each word and we check if we already have it inside the hash table if yes we append the underground inside the list of the world that we are currently at if we don't have it we start a new group of anagrams a new list of anagrams and so on foreign for the second solution the time complexity is going to be office and login because we are iterating in all the strings and for each strings we are sorting the letters for the space complexity it's going to be of s and because we are creating a new hash table where we are storing all the anagrams and the N is the length of the longest word
Group Anagrams
group-anagrams
Given an array of strings `strs`, group **the anagrams** together. You can 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:** strs = \["eat","tea","tan","ate","nat","bat"\] **Output:** \[\["bat"\],\["nat","tan"\],\["ate","eat","tea"\]\] **Example 2:** **Input:** strs = \[""\] **Output:** \[\[""\]\] **Example 3:** **Input:** strs = \["a"\] **Output:** \[\["a"\]\] **Constraints:** * `1 <= strs.length <= 104` * `0 <= strs[i].length <= 100` * `strs[i]` consists of lowercase English letters.
null
Hash Table,String,Sorting
Medium
242,249
1,061
Hello friends, how are you all, hope you all will be very good, so today our question is a medium level question of a lead, inside this question we will have two strings whose lance will be S1 and S2 and one more string will be By doing the best level and inside it, whatever position of S1 and S2 will be there, it will be the equivalent character. They have told that some relation is being formed. It is fine at the bottom and inside this question, we have to return Let's C is the graphical smallest equivalent string. Off base level by using equivalent information from S1 and S2 So this was the description of our question. If we understand this question through example then like this is the first example we have. In this example the given thing we will have is first S1. It will be S2, this is the value of R K R, okay, the second one will be M O R I S, okay, now what did they say in this? The first condition they said to us is P and M. We both have one valentine, so it is okay. I write these equivalent things, what do I do, one is separate PM, okay, the second one is our AO, what is the third one, RR is connected to R, then our RK is connected to it, okay, then if we talk about this, then A And I is okay, the second one is R and S so okay A will go inside it, okay we have found this equivalence, now after that if we see what we have to do is that our base level is given to us like its value is purse I. So we have to tell in its respect that which is the minimum position of P, the set in which P will come, if you call it a set or graph, whatever you want to say, then it will come in this set, then the minimum position in it will come in this set. Lesbiographical, we have to take the lowest one, like peak, A has been in this, our A has been in this, luxury graphical minimum, what is our M, okay lexico, then which one will come first in the order, M will come, then A has come, A is in this, so Okay, let's write A. Okay, R has come. Which is the minimum among R? Okay, we have noted down K, then one more time what comes to us is S. This is the first time for one more time, so I will write it here. Okay, what comes after that? A Okay, this one is the minimum in the group. Okay, which one is the third? When R comes back, it will be done here, then it will be mine. The answer is okay, I think you must have understood, if we Discuss the approach of solution, so I can do what is the character of the string inside it, then can I consider that character as 'has' and 'not', if I consider that character as 'has' and 'not', if I consider that character as 'has' and 'not', if I consider it, then I can do 'like', ' consider it, then I can do 'like', ' consider it, then I can do 'like', ' suppose that's my'. suppose that's my'. suppose that's my'. P is initially the parent of It will be its own parent, so what do I do between these, I create a relation like my P and connect it and I create this relation, so what can I see inside it, I compare P and the M which is theirs. Which one is the parent, which one is smaller, which one is bigger, I will update its parent, guess who is bigger in my PM, legsography, tomorrow I am the bigger lensiko, which one comes first in your order, my M will come first, so what will I do to the parent of PK? Let me tell you who is its parent, M is ok, I like it, I write it like MP, ok, now who is mine next, who was my relation, A was from O, R was from R, K was from S and A's was mine from I's so what will I do how will I relate them inside A's and O's is ok oy unique clean the ligament a little like I had what was PM's ok was A's and what was A was with O'r With K so that S and A were with I, so do I write in this, M became its parent, okay, its child became P, A became a parent, that became okay, R came, K became parent in this, okay R and S's okay, I can do it like this, Na Han Bhai, you can update the convert. Okay, if we look at the example, I have Padkali, so do I first write P, the unique character which can be whatever, R inside it. K is not correct yet, AMO will be I and S. Who is their initial parent? P is the parent of K, AR is the parent of R is the parent of I will update the one who is smaller in I from the parents of the bigger one. Okay, my P is M. Which M is the smallest among them? So, now who is the parent of P? It is M. Okay, what is there in A and O, who is the smallest? Sa is small, O's parent will be K, this will be R. Okay, no, there will be no difference which of R and K is smaller, then K will be the parent of R, K will be okay, now again A will come and I will be and mine. If i is ok then update of parent of i will come last then my R and S are ok in R and race what is my small R and in this S is small but who are the parents of R and which of these two is smaller K so I, who will become the parent of Who is the parent of A? Who is the parent of R? Who is the parent of Our R is who is the parent of R? Is it okay? What has happened to me? The answer is done. Okay, I think you must have understood. Now if we look at the second example of this, the one given by Hello, then my What is the pass? Hello's, A, O, K is written, R, A, Jaega, La, Gaya and Di. Okay, I have written these unique words, initially who is their parent? All these are from their own parents, so there are no new parents. Let's go, let's create a relation, H is connected to which V, is it okay, and these have a relation, who is the smallest, what is ours here, H is our small, okay, H is small, V, what is the other one, which is small, which one is A, so who becomes its parent? A ok now let me look at the other L and R ok our L is small so the current of R will be L ok after that what comes I have O D from both L &amp; L ok I have O D from both L &amp; L ok I have O D from both L &amp; L ok inside this we see that Who is the parent of our O? What is the parenthesis of O? A's parent is A himself and who is the parent of Di? Now we are not talking about these two, now we are in this position in comparison of these two parents. If A is A and who can become its parent, then we say Di, which is smaller among A and Di, our smaller A is, so what we do is update the parent of A, who will become the parent of Di O? The current will be A and the current of Di will be itself D. We convert it on the basis of 'Yaar Main'. If the answer convert it on the basis of 'Yaar Main'. If the answer convert it on the basis of 'Yaar Main'. If the answer comes out then the print of 'Ha Hai Ha' will be Who is 'Khud Hai' who is the comes out then the print of 'Ha Hai Ha' will be Who is 'Khud Hai' who is the comes out then the print of 'Ha Hai Ha' will be Who is 'Khud Hai' who is the parent of 'O' Who is the parent of ' parent of 'O' Who is the parent of ' parent of 'O' Who is the parent of ' A' and 'A' will be who is the parent of 'Di' Okay di A' and 'A' will be who is the parent of 'Di' Okay di A' and 'A' will be who is the parent of 'Di' Okay di and then comes okay I think you have understood the solution how to do it let's convert it into code before converting it into court if we look at our data structure like we have how many possible strings inside The characters can be 26. There can be 26 notes. So can we have the representation of the notes in the form of a graph? Like, let me make a graph here, the size of which will be 26, the note will be the note, its frequency will be like A. What will happen to A? The parent itself will be I have gone to the coding screen here, I create my graph, what will be the size of the new in 26, which I was just discussing, okay, now what do I have to do, create their parents inside this, initially who will be the parent of whom for INT. i = 0 i goes tu mera INT. i = 0 i goes tu mera INT. i = 0 i goes tu mera 26 end i + + ok 26 end i + + ok 26 end i + + ok now what will be the value of graph i will have the value of i ok my parents are set inside the graph now what do i have to do if i have to make connections between them What will I do to make a connection? Tu S van dot is the length given to us in the question. Okay I + Okay now what do I have to do. I have to I + Okay now what do I have to do. I have to I + Okay now what do I have to do. I have to find out what I have to do first of all. Their fine relationships will be formed through whom. Well, through the parent and parent, I write here ID, I have like one, I give A to S van ka, if I find which is its parent and which is its parent, which will be the smallest, I will update inside that. So I will do a find and create a function here, that is, first I will write the meaning, then I will give the function in it, I will graph it and then send it. If we want to update the character of F1 mines, then how will we update the value, which will be minimum. We will add the minimum value to it, sorry, which will be the maximum, so I write here, if it is greater, then what will I do, this is my graph, I will implement it above the A position inside the graph, okay if I found it here. But now what will I do after this which will return my string sub is equal to you new string builder Okay, now I will put a loop here which is I am not equal to zero I tend to mine in whose respect the base str will run. lenthkil will run in support, okay i++ str will run. lenthkil will run in support, okay i++ str will run. lenthkil will run in support, okay i++ will happen, okay what will I do after this, I have to add it inside SP, whom will we do, whatever position of its base staircase, if it is P, then we have to bring the parent of P. Okay, so I will do app end here, what will happen, I will have character, okay, A will come inside it, A will be done, we will do plus and we have to find its parent, so find is okay, sorry, level means will come here, base str.rector will come. Which position's I str.rector will come. Which position's I str.rector will come. Which position's I position, in this we will have to do minus a, okay, this will bring the character for that and add inside it and in the last I will return here, everything is okay, now I will find one of this, how will it find the parent? If we look at the thing, we create an ID here, find my parameters, inside this, the brick graph will come, one is fine, then the ID will be the index of our in case, if we run it is not just that, then what do you do brother? If you want to update my value, what will it do? ID The most complicated function was this function, I think a lot of people would be confused about this function, so what am I doing with this function we find out who are the parents, okay if we take the initialism from this loop. At the first time, we call here, we ask here who is the parent, then in the first place, whoever is the parent, we assume inside this that P came, we sent P here, so inside the graph, whatever is our graph now. Who is the parent of P inside? If P is there, then what will be the return from here? Look at this condition of mine, what is written in it, which is the index of P, it is okay and if the graph is not equal to the value, then we have to run this look, okay? What is that, what will be the return from here, I will get P, in the first case, I will set the parents of P in P, okay, after that when my M came inside it and its M came, then I used to get M inside M too, okay. Now I compare these two, whether M is greater or P is greater, then what is my M? It is smaller than P. Like, I have put a condition here, so what do I do, which is my graph, which will be P, okay. Which will be the value of P inside the graph, whom will I set to M, okay, what will be our relation, who will be the parent of P, in this case it will be M, okay, this is its but now nine, we have one. The condition comes and P is connected to our K, it is fine, in this case we will go to P, we will call this function, if we get the parent of P, then this function will come here, when we see this, which is the index of P, these are not equal. Whatever will happen to the graph, which is not equal to the index P inside the graph, no, because what is P there, it has value M, so what will it do in this case, it will replace the index we have sent to M with M. Okay, here we have replaced it with M, made it M and here we have returned M, so now the relation that will be formed is because K is not being formed from my P, it is being formed from my K, like my relation of An will be K. Okay, I think this function of ours is doing this thing, it is handling the parent thing, I think you must have understood why I did it here, if we are in this question, if you are talking about time complexity and space complexity. Talking about it, here you can see that I have done a loop here, it ranks 26 times, that is, after that, I have a 4 loop here which runs at the end and here I also consider the string which is base as N. So what becomes my time complexity n+n+26 like this is our constant ok n+n+26 like this is our constant ok n+n+26 like this is our constant ok and if there is a plus then we also like the plus you multiply and what is the constant in plus 26 if both of these are constants then what should be our time complexity Oye, okay, this is our time complexity. If we talk about space complexity, what have we done in space complexity? There is one of size 26 here. Apart from that, we have done it here, so inside our space, we have done it. How many spaces are there in it, okay? 26 And this again is our constant, then what will be our space complexity? Or okay, I said in space and time because I am taking the ss van s tu and the base length as main in it. What is their length? I am here, you can do this, our maximum space which will be taken, if you want to differentiate it a little, then this will be the length of the base level, that will be our space and our time will be s2s1, I think this video. It will be very helpful for you, if you have not liked this video yet then go and like it immediately. If you have not subscribed the channel then subscribe the channel immediately. See you with another video till then bye.
Lexicographically Smallest Equivalent String
number-of-valid-subarrays
You are given two strings of the same length `s1` and `s2` and a string `baseStr`. We say `s1[i]` and `s2[i]` are equivalent characters. * For example, if `s1 = "abc "` and `s2 = "cde "`, then we have `'a' == 'c'`, `'b' == 'd'`, and `'c' == 'e'`. Equivalent characters follow the usual rules of any equivalence relation: * **Reflexivity:** `'a' == 'a'`. * **Symmetry:** `'a' == 'b'` implies `'b' == 'a'`. * **Transitivity:** `'a' == 'b'` and `'b' == 'c'` implies `'a' == 'c'`. For example, given the equivalency information from `s1 = "abc "` and `s2 = "cde "`, `"acd "` and `"aab "` are equivalent strings of `baseStr = "eed "`, and `"aab "` is the lexicographically smallest equivalent string of `baseStr`. Return _the lexicographically smallest equivalent string of_ `baseStr` _by using the equivalency information from_ `s1` _and_ `s2`. **Example 1:** **Input:** s1 = "parker ", s2 = "morris ", baseStr = "parser " **Output:** "makkek " **Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as \[m,p\], \[a,o\], \[k,r,s\], \[e,i\]. The characters in each group are equivalent and sorted in lexicographical order. So the answer is "makkek ". **Example 2:** **Input:** s1 = "hello ", s2 = "world ", baseStr = "hold " **Output:** "hdld " **Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as \[h,w\], \[d,e,o\], \[l,r\]. So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld ". **Example 3:** **Input:** s1 = "leetcode ", s2 = "programs ", baseStr = "sourcecode " **Output:** "aauaaaaada " **Explanation:** We group the equivalent characters in s1 and s2 as \[a,o,e,r,s,c\], \[l,p\], \[g,t\] and \[d,m\], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada ". **Constraints:** * `1 <= s1.length, s2.length, baseStr <= 1000` * `s1.length == s2.length` * `s1`, `s2`, and `baseStr` consist of lowercase English letters.
Given a data structure that answers queries of the type to find the minimum in a range of an array (Range minimum query (RMQ) sparse table) in O(1) time. How can you solve this problem? For each starting index do a binary search with an RMQ to find the ending possible position.
Array,Stack,Monotonic Stack
Hard
2233
1,071
hey guys welcome back to my video series on solving Leaf coat problems I'm Alex and this video we're solving 1071 greatest common divisor of strings I already solved it but the video took too long for this I'm recording another video so what's the problem about so for two strings s and t we say t divides s if and only if s equals t plus C plus t for example T is concatenated with itself one or more times so the string ABC is a b c plus ABC so string to T will be ABC given two string one and string two Returns the largest string X such that X divides both string 1 and string two so we need to find a value that divides both string one and string two in this case it's ABC because it's the same and a b in this case a b and in the last case leads codes well there's nothing that can divide both so empty string so how do we solve this so it is let's look at the ABAB example so we have six strings and then we have apdb plus four so to solve this we need to find a b how do we find it first of all we know that it's six characters here and four characters on this one so whatever is the word that divides both of them if it exists it must be the greatest common divisor of both of them so let's try it because we need to find something that multiplies by two not two or multiplied by three gives us results and this is something that multiplied by 2 gives this result and the greatest common divisor of both of them is a size two a b so first of all let's find the greatest common device common divisor equals gcd this is from the math module of length of string one and length of string two and now we need to check if now we need to check that they both start equally so string one from zero until the greatest common divisor this is equal to string two from zero to the greatest common divisor if so we do some things so now we need to see that string one is equal to string one from zero to the greatest common divisor so in this case a b times the length of string one divided by two integrate division why are we saying this so string one is a b i see if it's equal to we know the greatest common device will be two so a b must be equal to a b times the length of string 1 which is six divided by two which this is free so a b times 3 must be a b also if then we do the same thing for string two stream two equals string two okay same thing and if so we return string one from zero all the way to the greatest common divisor and if nothing checks out they say we should return an empty string so let's just submit okay wrong answer outputs nothing expected ABC okay let me just run this locally see what went wrong so string one is ABC string two is ABC nothing just off string one let's see if A B C equals between two PVC and then okay string one which is ABC we see ABC okay ABC and times three which is not three oh it's not divided by two this is like a stupid mistake of course not divided by two it's divided by the greatest common divisive same thing for the rest yeah and now let's check the result ABC let's go okay run time beats 56 percent memory beats 89 let's submit again and see if we're lucky yeah which is even worse well I'm actually happy with this okay now we do 37 beats okay a lot better hope you guys enjoyed it see you later
Greatest Common Divisor of Strings
binary-prefix-divisible-by-5
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times). Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`. **Example 1:** **Input:** str1 = "ABCABC ", str2 = "ABC " **Output:** "ABC " **Example 2:** **Input:** str1 = "ABABAB ", str2 = "ABAB " **Output:** "AB " **Example 3:** **Input:** str1 = "LEET ", str2 = "CODE " **Output:** " " **Constraints:** * `1 <= str1.length, str2.length <= 1000` * `str1` and `str2` consist of English uppercase letters.
If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.
Array
Easy
null
502
hey everyone welcome back and let's write some more neat code today so today let's solve the problem IPO we're given two arrays one array is the profits array and another array is the capital array suppose something like this where we have one two three for our profit values and zero one for Capital we're also given an initial Capital called W let's say it's zero in this case and we're also given an integer K in this case two so you can see there's quite a lot of variables in this problem our goal is to maximize the amount of money AKA Capital that we have at the end initially we have zero so what we would like to do is take some of the profits so maybe we take two and we take three we can only take up to K of these values and when we take them we mean add them to our total Capital so if we start with zero we add two to it we add three to it we end up with five so that's good the only catch is that we can only take profits if the capital corresponding with the same index so like these two or maybe these two or these two if the capital corresponding to that profit is less than or equal then our current capital we know we started where W was equal to zero but as we take profits our W value will change so the profits available to us will also change though this part tripped me up when we take a profit we don't actually have to subtract the capital needed this is not like the cost it takes us this is the capital so as long as our capital is greater than or equal to this we are allowed to take the profit and we don't lose any Capital ever so once you get past all the variables and different kind of interactions this problem isn't too bad so what we're going to want to do is try to find the maximal profits and we're going to need to do this repeatedly so you might think we can sort the profits array or use a heap in this case using a heap is going to be better and we're going to see that towards the end so for now let's assume we're going to use a heap for the profits more specifically a Max Heap so that we can get the max amount of profit so let's be naive let's say this is in our Max Heap we're gonna pop the max value which is three let's say we also added the capital as well so we see that this profit has a capital of one that is not less than or equal to our current capital so we can't include this three at least not yet so a better solution would have been to not have added this from the beginning to our Max heap of profits we should only initialize that Heap with profits that we can actually take this is the only one we can initially take because it's the only one with the capital of less than or equal to zero now let's see what happens when this is initially our Max Heap well we pop from it there's only one value to pop in the first place there's only one value to pop we get this profit of one we see that capital is less than or equal to our current capital so we take the profit and add it so we get now a profit of one so let's say we took this profit and now we can only take one more profit the problem here though is that our Max heap of profits is now empty so what should we do should we go through the entire input array obviously not this one but the rest of the input array and see which one of these profits can we now take and then push them onto the max heap of profits so that we can then pop from them that would definitely work but you can see in the worst case every time we pop from the Heap we would then have to iterate through the entire array again and again this is no better than iterating through the entire array K times that time complexity would be n times K that is a Brute Force approach but the question is can we do better than that and the answer is yes because we know that among the rest of the array let's say these are the ones we couldn't afford previously we didn't have enough capital for them but now that we have increased our capital and remember our capital is never going to go down it's only going to go up maybe it'll stay the same or it'll go up it'll never go down so as our Capital changes we might have access to more of these profits but we don't know which ones but let's say that this one actually required a capital of two and this one required a capital of one we know for sure that this one is probably going to become available to us before for this one because it requires a lower Capital so among all of the ones we haven't considered yet we should go through them in order of smaller capital and then bigger Capital AKA we should maybe take all of these and throw them in a Min Heap not based on the profit though but based on the capital if we do that we won't have to iterate through all of these to know which ones have become available we can look at the one with the lowest needed capital and check is that Capital less than or equal to our current capital if it is then we take this and pop it from that Min Heap and push it to the max heap of profits so we're going to actually have two heaps in this case this is a pattern that's used in other problems though a little bit differently than this one but it is a pattern nonetheless but that's pretty much the entire idea this problem is not too bad once you can figure out that it is a two heaps problem which I admit is not easy to do especially if you haven't seen this pattern before because it is pretty rare So now how would we solve the rest of this problem well both of these would go into our Max heap of profits because we can afford both of them but which one of them has a higher profit it's this one so we would pop this from our Max heap of profits and then take that profit which is three and add it to our current total then we would have a current total capital of four we're only allowed to take two profits we took both of them so then we would return this as our result how did we improve the time complexity well we're gonna need to iterate K times so the time complexity is going to be K times what's going to be the time complexity of pushing to Max profits it's going to be log n in the worst case what's going to be the time complexity of popping from the minimum Capital it's going to be login as well we're gonna in the worst case I have to do two of these on every iteration of the loop but that's not too bad if we say this is two times log n that will reduce to being K Times log n anyway so that is the overall time complexity space complexity is going to be a big of n we do have a couple heaps so now let's code this up so what I'm going to do is first create our two heaps we know one is Max profit initially let's set that to be empty we know these are only the projects that we can actually afford right now and we're gonna have a second Heap for minimizing the capital these are the ones that we can't necessarily afford right now but maybe in the future we will be able to afford them the way I'm going to initialize this is first as an array so I'm going to go through every pair of capital profits that we have in Python you can do something like this you can zip the two arrays but you could do this in like an outer for Loop like down here if you wanted to it's not a big deal I'm just trying to do this as concisely as possible because this is just kind of the boilerplate we have our pairs of capital and profit and we're going to add each pair to this array and then we're going to take that array and turn it into a heap and python every Heap is a Min Heap by default so this will turn into a Min Heap so now we're gonna iterate K times so every single time we want to pop from the max Heap so the max profit Heap and then take it and add it to the current capital which I'm just going to use the input parameter because that tells us our starting capital and we know it's going to change so might as well add to it and then at the end we know we're going to return that Capital but we know that so far our Max profits is empty so we have to initial lies it and we know that every time we pop from it then on the next iteration of the loop we might need to pop from the minimum Capital Heap and push onto the max profits so instead of initializing Max profits out here I'm just gonna inside here before we pop from it I'm gonna say while our minimum Capital Heap is non-empty and the Capital Heap is non-empty and the Capital Heap is non-empty and the minimum value in the minimum Heap or the root of that minimum Heap is at index 0 and we know it actually has a pair of values capital and the profit the capital the first value is what's going to be used as the key for this Heap so it's going to minimize all these pairs based on the capital since that's the first value we're going to now say index zero so we're getting the capital that is the minimal and we're asking is this less than or equal to our current capital because if it is that means we can pop from this minimum Capital Heap and when we pop from it we're going to get the capital and the profit we added both of these but once we pop them we only care about the profit the capital was only used to tell us can we get this profit or not if we can then we don't need this anymore so even though we popped it we're not going to use it we're just going to say this profit is now available to us so we're gonna push it onto the max profit heat but the thing is we want this to be a Max Heap so we can't just push the profit because everything is a Min Heap in Python by default so if we want this to be a Max Heap we have to make this value negative you can just say negative P or negative 1 times P so this will make it a Max Heap but since we're trying to add to the capital and we want the capital to be positive when we pop from here we're going to be getting that negative value so we should say add to it after multiplying this by negative 1 or we could say minus equal this but I think this is probably more readable but remember they told us we have to choose at most K profits it's possible that we don't even have K profits available to us in which case this would throw an error trying to pop from an empty Heap we'll throw an error so what we should say is if our Max Heap is ever empty we might as well break and probably just return at that point because if none of the profits are available to us we can't increase our current capital so we can't really get any other profits so this is the entire code now let's run it to make sure that it works and as you can see yes it does and it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io it has interviews check out neatcode.io it has interviews check out neatcode.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
IPO
ipo
Suppose LeetCode will start its **IPO** soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the **IPO**. Since it has limited resources, it can only finish at most `k` distinct projects before the **IPO**. Help LeetCode design the best way to maximize its total capital after finishing at most `k` distinct projects. You are given `n` projects where the `ith` project has a pure profit `profits[i]` and a minimum capital of `capital[i]` is needed to start it. Initially, you have `w` capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of **at most** `k` distinct projects from given projects to **maximize your final capital**, and return _the final maximized capital_. The answer is guaranteed to fit in a 32-bit signed integer. **Example 1:** **Input:** k = 2, w = 0, profits = \[1,2,3\], capital = \[0,1,1\] **Output:** 4 **Explanation:** Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. **Example 2:** **Input:** k = 3, w = 0, profits = \[1,2,3\], capital = \[0,1,2\] **Output:** 6 **Constraints:** * `1 <= k <= 105` * `0 <= w <= 109` * `n == profits.length` * `n == capital.length` * `1 <= n <= 105` * `0 <= profits[i] <= 104` * `0 <= capital[i] <= 109`
null
Array,Greedy,Sorting,Heap (Priority Queue)
Hard
null
1,300
hey guys welcome back to another video and today we're going to be solving the lead code question sum of mutated area closest to target and this is lead code question 1300 all right so let's just go over the question real quick i know the question itself is a little confusing but then after this i'm going to break it down and make it a lot easier to understand all right so given an integer array and the target value target return the integer value such that when we change all the integers larger than the value in the given area to be equal to value the sum of the area gets as close as possible to the target so in case of a tie we return the minimum of such integer and notice that the answer is not necessarily a number from an array so what does this actually mean so to better understand let's just look at this example real quickly so we're given this area four comma nine comma three and the target we have is ten so that means that whatever the stuff over here the so whatever elements we have over here have to add up to be equal to 10 or as close as possible now in this case our output is 3. so what does the output actually mean so that means that everything which is greater than the output is gonna change its value to the value of the output so over here we have the number four and the output over here we got is three anything greater than the number three is going gonna change to have a value of three so four is going to change to have a value of three nine is also going to change to have a value of three but three is going to stay the same because it doesn't matter three is equal to three so now when we add our new array which is just consistent of 3s so we're going to get 3 plus 3 and that equals to 9. and that's the closest we can get by adding integers to our target so let's just look at another example and then i'll break it down for you so we have this area over here two comma three comma five and our target is ten so now let's add this one so we get two plus three plus five so that's nothing else but 10. so as it is our array equals to the target so we don't really need to change anything so in that case we just gave an output of 5. so that means anything greater than 5 is going to have a value of 5. but in our area we have nothing greater than five so everything just holds the same value and we have the same value as our target so now let's see how can we actually achieve that value and get close to the target so let's say in our question we're given this area over here five comma two comma three and our target that we need to reach is ten so what we're going to do our first step is going to be to sort the array in ascending order so from smallest to highest so we're going to do that real quick so we're going to get 2 comma 3 comma 5. so now that we have this it's going to make it a lot easier for us to actually find out the answer now what we're going to do is we're going to look at the length of the array so what is the length of our array so one two three we have a length of three and our target is ten now we need to come up with a number which when repeated gives us a value closest to 10. so how can we come up with that number and coming up with that number is nothing else but doing target and dividing that by the length of our array so in this case our length is 3 and our target is 10. so we're going to do 10 by 3 and we're going to round it so we're actually going to get 3.33 actually going to get 3.33 actually going to get 3.33 but when you round it we're going to round it down so we're just going to get a value of 3. so what does this 3 actually mean in other words it just means that if we have this array 3 comma 3 this is going to be our most ideal case and where our numbers are repeated this is the closest we can get to 10. so what we're going to do is we're going to look to see if the first element over here has the value of 3 or it's greater than 3 but in this case we have two is not greater than three neither is it equal to three so now what we're gonna do is we're gonna ignore the two and we're gonna move on to the next element so in this case we're gonna go to the three and we're still not going to look for the same element so now what we're going to do is we're going to account for the 2 in our target so now our target it was 10 but now we're going to account for the two so all we're going to do is we're going to subtract it by that element so we're going to do 10 minus 2. so the target changes and now we're not going to look for a length of 3 we're going to just look at the remaining length so before it was three now we need to just look at this and this so our length is going to decrease by one so it's going to be what our original length was minus one and now this gives us a value of eight by two which is nothing else but four so this means that we need to reach the number eight and the most optimal way to get that is so that our next two numbers are equal to four so two comma 4. now we're going to check if the next if the element is equal to 4 or greater than 4. so 3 is neither equal to or greater than 4. so in that case we're going to ignore this as well and now we're going to iterate through the next number so now for the last time we need to change our target again so we had 10 originally now we need to account for 2 and we also need to account for 3. so now our target changes to whatever that value is and now we need to change our length again so our length changed to 2 and now we need to do 2 minus 1. okay so now this is equal to ten minus two eight minus three five divided by one which is nothing else but five so now in this case we're looking for the value five so we have two we have three and now we need to now our most optimal solution is 5. so now we're going to see if our last element is equal to or greater than 5 and luckily this element is equal to 5 and when something is equal to or greater than what our optimal solution is we're going to just return the optimal solution so in this case we're going to return the value 5 and that's going to be our answer so now let's see how we can implement this using code so as usual i'm going to be using python 3 in order to implement this okay so our first step is to sort the array so we're just going to do array.sort array.sort array.sort and that should sort it for us in ascending order now we're going to create a variable called length which is going to store the length of our area so length of array so this holds the length of our array now we're going to iterate through all the elements inside of the area so for x in range the length so this is the length so we're going to iterate through everything inside of the array so now we're going to have a variable called our solution and so this is basically our most optimal solution right and to get that we need to take the target and we need to divide that by our length and make sure we also need to round this value it's because we only need integers and after we have this we need to check if the element in the array is equal to or greater than the solution so if array x is greater than or equal to solution in that case we're just going to return our solution and we'll be done but if that's not the case we need to alter our targets so target minus equals we're going to subtract it by the current element we're on and we also need to decrease the length by one so now we're going to decrease the length by one and we're also going to change the target and now after we do this and let's see after all these uh after all these iterations in our for loop we still do not get the answer and in that case we're just going to return the biggest number inside of our array so that is going to be the last number because we sorted it so we're just going to return array and the last element so area negative 1 is going to return the last element so i'm going to submit this and let's see what happens all right so as you can see our solution did get accepted and finally do let me know if you have a better solution in mind or if you have any questions regarding this and uh thanks a lot for watching and don't forget to like and subscribe thank you
Sum of Mutated Array Closest to Target
critical-connections-in-a-network
Given an integer array `arr` and a target value `target`, return the integer `value` such that when we change all the integers larger than `value` in the given array to be equal to `value`, the sum of the array gets as close as possible (in absolute difference) to `target`. In case of a tie, return the minimum such integer. Notice that the answer is not neccesarilly a number from `arr`. **Example 1:** **Input:** arr = \[4,9,3\], target = 10 **Output:** 3 **Explanation:** When using 3 arr converts to \[3, 3, 3\] which sums 9 and that's the optimal answer. **Example 2:** **Input:** arr = \[2,3,5\], target = 10 **Output:** 5 **Example 3:** **Input:** arr = \[60864,25176,27249,21296,20204\], target = 56803 **Output:** 11361 **Constraints:** * `1 <= arr.length <= 104` * `1 <= arr[i], target <= 105`
Use Tarjan's algorithm.
Depth-First Search,Graph,Biconnected Component
Hard
null
1,696
hi everyone happy holiday and today let's solve the weekly contest uh median question jump game six the question statement so we are given an integer array noms and integer k and we are initially standing at index zero and in one move we're able to jump at most k steps forward but cannot jump outside the array boundary so that means we can jump from index i to any index in a range of i plus 1 to minimum of n minus 1 and i plus k inclusive and we want to reach the last index of the array and we have a score that is the sum of all elements we have visited in the array and we have to return the maximum score we can get so for example one starting from the first element one we can jump forming the subsequence one negative one four and three so the maximum score we can get is seven and for example two the jump would be ten four and three so the sum would be 17. and for example three the maximum score we can get is zero in a data constraint the length of the nums array can go up to 10 to the power of five so if you have worked on other jump game problems then you will know that the approach to solve this kind of questions is dynamic programming and here the dp array is the maximum score we can get at index i and the initial value of the dp array is the first element in the nums array and dp transition since we can jump k steps forward in the nums array the maximum score we can get at the current element will be the maximum of nums i plus dp i minus 1 or dpi minus 2 all the way back to dpi minus k so as you can see the key part is to keep track of the maximum of the dp array in the sliding window so the data structure we can use is a dac data structure which is double ended queue and for that data structure we're able to pop elements from the left or from the right we will pop elements from the left to make sure that all elements in the deck stays within the sliding window and we will pop elements from the right to keep track of the potential maximum in the sliding window and this technique is the same as solving question 239 sliding window maximum so make sure that you check out this question as well now let's look at the code okay and first create and initialize the dp array and then create a dac queue and we will put a tubal of the current element num and its index into the queue and next iterate through the nums array first calculate a dpi which is a nouns i plus q 0 and next we only want to keep potential maximum sliding window maximum in q so if dpi is bigger than the last element in q then we will pop it out from the right and then append dpi and its index i into the queue from the right and next is to check if the first element is still within the sliding window so this if condition if i minus k is equal to q 0 1 this means that this element you will be leaving the sliding window so we will pop it out from the left and finally return the last element in a dp array now let's see the code in action here we will be looking at example two and it in this example k which is the width of the siding window is 3 and the output will be 17. so initially dp 0 will be 10 which is the first element in a numser array and we will push the first element and its index 0 into q and at index one dp1 is a negative five plus the first element in q which is ten so it will be five and next is to push the dp value 5 and its index 1 into q and since 5 is smaller than the elements in q 10 so this element will not be pipeled and then index 2 calculate dp2 which is a negative 2 plus 10 which is equal to 8. and then push 8 2 into q you can see that 8 is bigger than 5 which means that 5 has no potential to become the sliding window maximum so we will just pop it out from the right and here you can notice that the current sliding widow maximum which is the maximum of dp i minus 1 i minus 2 all the way back to dpi minus k will always be the first element in q so that is the main reason why we are updating dpi by adding nums i and the first element in q and following the same process at index 3 dp 3 is 4 plus 10 which is 14 and then push 14 3 into q and now 14 is bigger than either 8 or 10. so we will pop 10 and 8 both from the q and at index 4 dp4 is 14 as well and we'll push 14 4 into q and here you can also notice that since the width of the sliding window is 3 so the left pointer which is the left boundary of the siding window will be now pointing to index 1. and finally the last element is 3 so dp 5 is 14 plus 3 which is 17 and 17 is bigger than 14 so these two elements will be pop out from q so the result the final output is the last element in dp which is dp5 is 17. and this will conclude the algorithm finally let's review so the algorithm we use to solve these questions is dynamic programming and the meaning of the dp array is a maximum square we can get at each index i and the key data structure we use in this question is a dac which is a double ended queue and this key dial structure this technique is what we use in solving the related question 239 the sliding window maximum so be sure to check out this question as well and the time and space complexity of this approach is both a linear big of n because we are looping through the array once and we are maintaining a deck to keep track of a sliding window maximum and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the next one you
Jump Game VI
strange-printer-ii
You are given a **0-indexed** integer array `nums` and an integer `k`. You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**. You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array. Return _the **maximum score** you can get_. **Example 1:** **Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2 **Output:** 7 **Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7. **Example 2:** **Input:** nums = \[10,-5,-2,4,0,3\], k = 3 **Output:** 17 **Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17. **Example 3:** **Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2 **Output:** 0 **Constraints:** * `1 <= nums.length, k <= 105` * `-104 <= nums[i] <= 104`
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
Array,Graph,Topological Sort,Matrix
Hard
664
1,825
hey everybody this is larry this is day q4 of the weekly contest 236 that i'm going over finding mk average um hit the like button hit the subscribe button join me on discord let me know what you think about this problem and in general uh so yeah so for this problem i'm doing the contest i had some issues with reading i actually tried to solve the one way with it didn't have just the last m elements so i had a so i was just a little bit weird out but um but yeah so i tracked the entire thing but what so i had to re restart and reset my mind to do the last m prompts i was at a real typo somewhere but i did but the idea i had uh and you can do this in other languages you may use multi-set or multi-set or multi-set or something like that uh in c plus but in uh in java sorry in python i use sorted list um and you can actually use any like sorted this structure like you know binary um like a binary a balanced binary search tree or something like that basically just an a way to you know an um basically just a data structure that allows you to get the min and the max in efficient time uh and also remove elements and log in uh we'll add elements and log in uh get the min and max hopefully in order one more of log n is fine and that's a login for add i'm in log n for n and also of log n removal then that would be you know that's my benchmark for knowing that i'll be fast enough um so what i did is actually i wrapped the sorted list with a thing called started list with some i need to add more functions to make it like more useful because i end up you know but the idea here is that um i have this class that gives me you know what we said about the abstract data type of um this tree like thing um that you add a thing to keep track of the total of the sum that is inside that thing um so basically what i did was that i for implementation i basically have three lists right so i have list a you know let's say a b oh my computer's though uh let's just say a sub 1 or a 1 a 2 a 3 and then dot um you know you have the middle which is a4 dot you know a sub you know whatever some other number uh a sub j and then some other uh other boundary of doo and then a sub m right um a sub n minus one oh no this is a m because it's one index and the idea is that okay you want this left side to be to always be to hold the invariant that is going to have k elements um you have the right side also k elements and then on the middle you know that becomes clear that it is just m minus k or okay you know m minus two times k or something um and so those are the length of the list and as long as we're able to move items from left you know from the lists to each other then that's all you know all we have to do is make sure that we hold this in variant and that's the key observation or you know that's the key solution for this problem as long as you're able to do that um you know it doesn't really matter or like you know other stuff doesn't really matter someone's able to do that uh hold that in varian and having the sorted list data structure will allow us to do that i do this in a very funky way perhaps um but basically what i do is i literally like you know like if it if we have more lists um it may get a little bit confusing a little bit uh trickier but you know maybe you need to binary search the list itself to figure out which list to insert to um but because we don't have three lists i did it very manually basically i tried to add yeah let's say we added a new number uh x right so i try to put x inside the smallest k element um and if it's inside you know if x goes here then we have the extra element that's you know so a sub we'll remove this biggest element and then we'll try to put it here and once we put that here well you know this number will um you know this will be already too small so then or too many items so then we put the next number here and so forth basically like a cascading um addition right and then we move always to opposite basically i try to remove from the large or i try to see is it in the largest section if it's not then you try to see if it's in the middle section um if it's not if it is then we remove that number and then we take numbers from bigger you know like basic cascading down and cascading up um and because every operation is log n you know in theory that should be fast enough unless your login gets really expensive and that's basically my idea um and then we have this buffer here that allow us to just keep track of the last m's because in the beginning you know you need to at some point remove elements uh and then when you remove them you do stuff and then you add them you also do stuff and we'll go over in a second um let's go over to calculate m sum uh average you know given this you know keeping in mind that every time we add a number to a sorted list or your trees like structure we keep track of the total so then the this is really easy then because you just look at this total and then you divide it by the dividend right um i mean i think this is you know this is what it sounds like uh hopefully you know i don't need to explain this part because if i do you might need to work on easier problems but yeah this is a data structure problem uh but yeah basically for each element we add an element if the buffer is too big we have to remove something from the list um so here we take the first item and this is the item that we're moving this is just uh this is usual sliding window stuff if you will um you know as you slide the left pointer from left to right this may be reversed on your screen but from left to right um you know you remove an item and that item is the thing that you remove from the greater data structure um so first we try to remove from the right if it's we move from the right this is done um if we try to remove from the mid then yeah we remove from the mid we take the smallest element from the right and then we put it to the mid so basically you know um depending on how you like to solve this problem you have to maintain your invariant and the way that i do it is that whenever i remove an element i always push everything all the way to the left as much as possible almost like three sorted lists next to each other well and that's what it is um so yeah so if it's less than m elements the only element that's gonna be missing is from the largest uh group you don't have to implement it quite that way but that's the way that i did it just i don't know um yeah and if left has the all element because it all is not left it's not in middle or the right then the r is in the left and if it's on left then we remove them from the left and then we remove the smallest element from the mid and put it in left and then we move the smallest element in the right and then we put it in mid um hopefully that makes sense like i said i just cascade everything down the smallest element you know you pop you know it's like musical chairs everyone push one over and then addition is in the same way so i add one to the left if it overflows and it should after you know self.m but this happens you know self.m but this happens you know self.m but this happens earlier if this overflows self.k which is the k if this overflows self.k which is the k if this overflows self.k which is the k that we're given then we take the biggest element and then we remove it and we put in the middle if there are enough elements in the middle then you remove the biggest element from the middle and then you put it into the right um that's pretty much it i actually had a wrong answer because i would solve that k here because i wasn't thinking i was rushing it a little bit um and i didn't test i should have tested um but yeah that's all i have um and if you look at each of these things uh and keeping in mind that sort of list when i add and remove a number i keep track of the total inside that region so that we can get this ready efficiently um so what's the cost right well this is going to calculate mkl which is going to be of one because this is just an o one and this is our one as well and division is all one say so this is gonna be all one so what's the complexity of add element this is where all the work is at right well you know you can go through this very slowly and i'll go for it a little bit quicker but uh but let me know but this is basically o of one because this is just a list um of one and then the thing that's expensive is going to be the removals and at most there's going to be three removals and uh and at the most there'll be three ads or something like that uh for the removal part and also like the same amount so like you know maybe at most six adds six removal something like that um which is constant number of adds and constant number of removals and all and each add and remove always log n so in total or log m if you want to call it that um so in total it's going to be log m uh so add element is going to take log m time and given that we're only given uh 10 to the fifth number of course that's going to be fast enough uh cool that's all i have for this problem let me know what you think i think once you get the concept like i said this is a data structure problem so once you get the concept and you find the right data structure to match um the performance profile that you want then yeah then that's good enough the uh the biggest thing of course is just also keeping track of the total in a in an efficient way and having a data structure that allow you to do that um yeah uh that's all i have you can watch me sell it live during the contest next which i've done that first but i misread the problem twice said okay m and k is stream of number mk average numbers and s m okay the case and that's just two heaps right maybe okay nice now london okay so m is the number of elements that's inside okay is this smallest okay that's this is pretty straightforward i wish i got q3 not in the dumb way um okay how many queries are the 10 to the fifth so we have to be slightly and we don't remove any numbers so once a number is removed then it is gone the only tricky thing is the beginning i guess okay i just have a buffer okay so we actually want this to be okay thinking of one night okay um okay what you to remaining so this should be just m minus something like that yeah okay this should give me some random number that must be a list did i do it the other way whoops how do i literally just did it earlier today this is really bad think once i get soon wait i misunderstood something last oh you only care about the last m not that it was more than them okay huh let me sweat this one actually okay then now what there's still going to be two hips but it's just a lot more annoying uh and also because of the duke numbers it's a little bit just confusing in touch i missed the last input 45 minutes enough time what how do you get this song in a good time i know you could do it with like binary index tree but that's a mess is the easy way this is a little bit hacky but let's try this so i need this oh man i should forget how to do this i do overload something if i forget how so whatever you oh i need a buffer as well i need to remove first okay like this that's still right let's see this is not gonna be right but at least the ten pot should be right this abstraction was not necessary okay three is right the other one is not hmm that's still hot oh it's not odd because let me just push everything too big because the ingredient is not true oh come on okay yep that's what i thought it would be okay yes that's correct um okay is okay logan okay that's good um hmm okay so this is good but now is it fast enough is this good yeah is this fast enough let's give it a yellow i think huh wrong answer well that's not expected to be honest my answer is in the s3 huh three six one six i guess why does this have four items 312 um oh this is wrong okay the middle one should have okay so do you lie yeah thanks everybody for watching this video hope this helped uh and hit the like button to subscribe and join me on discord let me know what you think about this problem and how did you do during the contest or just afterwards uh of solving or whatever uh i'll see y'all next time uh yeah stay good stay healthy take care of yourself take care of others um to good health and to good mental health i'll see you next problem see ya
Finding MK Average
find-minimum-time-to-finish-all-jobs
You are given two integers, `m` and `k`, and a stream of integers. You are tasked to implement a data structure that calculates the **MKAverage** for the stream. The **MKAverage** can be calculated using these steps: 1. If the number of the elements in the stream is less than `m` you should consider the **MKAverage** to be `-1`. Otherwise, copy the last `m` elements of the stream to a separate container. 2. Remove the smallest `k` elements and the largest `k` elements from the container. 3. Calculate the average value for the rest of the elements **rounded down to the nearest integer**. Implement the `MKAverage` class: * `MKAverage(int m, int k)` Initializes the **MKAverage** object with an empty stream and the two integers `m` and `k`. * `void addElement(int num)` Inserts a new element `num` into the stream. * `int calculateMKAverage()` Calculates and returns the **MKAverage** for the current stream **rounded down to the nearest integer**. **Example 1:** **Input** \[ "MKAverage ", "addElement ", "addElement ", "calculateMKAverage ", "addElement ", "calculateMKAverage ", "addElement ", "addElement ", "addElement ", "calculateMKAverage "\] \[\[3, 1\], \[3\], \[1\], \[\], \[10\], \[\], \[5\], \[5\], \[5\], \[\]\] **Output** \[null, null, null, -1, null, 3, null, null, null, 5\] **Explanation** `MKAverage obj = new MKAverage(3, 1); obj.addElement(3); // current elements are [3] obj.addElement(1); // current elements are [3,1] obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist. obj.addElement(10); // current elements are [3,1,10] obj.calculateMKAverage(); // The last 3 elements are [3,1,10]. // After removing smallest and largest 1 element the container will be [3]. // The average of [3] equals 3/1 = 3, return 3 obj.addElement(5); // current elements are [3,1,10,5] obj.addElement(5); // current elements are [3,1,10,5,5] obj.addElement(5); // current elements are [3,1,10,5,5,5] obj.calculateMKAverage(); // The last 3 elements are [5,5,5]. // After removing smallest and largest 1 element the container will be [5]. // The average of [5] equals 5/1 = 5, return 5` **Constraints:** * `3 <= m <= 105` * `1 <= k*2 < m` * `1 <= num <= 105` * At most `105` calls will be made to `addElement` and `calculateMKAverage`.
We can select a subset of tasks and assign it to a worker then solve the subproblem on the remaining tasks
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Hard
2114
1,289
hi guys welcome to my channel and today let's talk about this another dynamic programming problem this one is problem one two eight nine from lead code and so let's solve this problem so here is our problem and i want you to pause this video and just look at the problem and see the example so this problem is another dynamic programming problem and so why is this dynamic programming what is the optimal substructure here in this case so what do i mean by optimal substructure if i give you this problem where you have to find the shortest path from seattle to la and you have to pass go through san francisco well i mean from here to here from seattle to san francisco you would take the path b and then from san francisco to la you would have to take the path e now what is sub optimal substructure meaning so in other words you if you want to find the shortest path from seattle to la you first have to find the shortest path from seattle to san francisco and then you have to find the shortest path from san francisco to la and then you add them up so that's what you mean by what we mean by having an optimal substructure in this case well obviously if there is a direct path from seattle to la then this problem is not a um optimal substructure so just be careful in that so let's work on this problem so this is our uh two dimensional matrix we call that grid and so i mean the first row is just that so basically we will create a dp matrix of size n by n where n is the length of this matrix and we are given a square matrix okay so first row for dp you just initialize it by setting it equal to dp of 0 comma j is just equal to grid of zero comma j so basically this one is just same as this guy zero comma zero dpo zero comma one is just grid of zero comma one and so on for the second row you are basically so we have to follow this rule where you cannot choose two elements in adjacent row that are in the same column so basically for this guy you would have to choose either number from here or here and then you have to add this guy you take the minimum of these two and then you just add this number this guy four and then you add them up and you get six for this guy you will be looking at the of the previous row this number and this number so one and three and then you add this five and you get six and you do the same thing and you keep doing it and for the last row you do the same thing for this guy you'll be looking at the minimum of this six and seven obviously the minimum is six and then you add seven so you get 13 you also you do the same thing you get the 14 and 15 you take you find the minimum of this the last row that is 13 and you return that answer well that's it for this problem and let's see how we can hold this up um okay first okay so we have to find the dimension of this and if we only have one number so if the dimension is one by one then we just return the number it'll be return grid zero okay and then we initialize our dp matrix so there will be zero four in range n for in range n okay and we initialize the first row this dp so there will be a k for chain range and dp of zero j is just great zero comma j okay now we have to do the uh we have to run the for loop twice for i in range one to n or j in range n okay and um well if the um okay we can do it in this way very simple so if we are on the first column if j is equal to zero so that's the first column dp of i comma j is just minimum of dp oh so we are looking at the last row and everything except the first guy and then we take the minimum and then we add this grid i comma j and um next one if j is equal to n minus 1 so if we are look if we are looking at this last column so when we are on the last column it will be just dp of i j is equal to just mean dp of i minus 1 and yeah everything except j plus grid i comma j and then else will be just dp of i comma j is just minimum of so the case will be just minimum dp i minus one comma j then minimum tp i minus 1 j plus 1 and then plus grade i comma j so basically um we are taking so if we are saying at here so the this else part will be here so if we are not on the first column or the last column then we will be just taking the minimum from first column all the way to the um so j minus one column you take the minimum so you that will give you the minimum from first column all the way to j minus ones column you also take the minimum of the you also look at the minimum from j plus one column all the way to the last column and you find the minimum here you find two you find the minimum of those two numbers and you add them you add this grid and uh i think this should be it and then return uh minimum dp of n minus one this one should be it let's see okay um so just one i just want to emphasize that you can actually optimize this a lot so you don't actually need the um say n by n matrix how many rows do you need you actually need two rows to compute this so i actually want you to try that part and yeah so i will leave that up to you and so that is for this problem and if my video helps please subscribe to my channel and so my plan is i will probably do more um dynamic programming problems i will get some more problems from say um code force and hackers rank so i will do greedy and so i will so my plan is i will probably do more deep dynamic programming problems and greedy problems and um yeah that's it for this video and thank you so much you guys for watching and i hope you guys enjoy the rest of the evening thank you bye
Minimum Falling Path Sum II
day-of-the-week
Given an `n x n` integer matrix `grid`, return _the minimum sum of a **falling path with non-zero shifts**_. A **falling path with non-zero shifts** is a choice of exactly one element from each row of `grid` such that no two elements chosen in adjacent rows are in the same column. **Example 1:** **Input:** arr = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** 13 **Explanation:** The possible falling paths are: \[1,5,9\], \[1,5,7\], \[1,6,7\], \[1,6,8\], \[2,4,8\], \[2,4,9\], \[2,6,7\], \[2,6,8\], \[3,4,8\], \[3,4,9\], \[3,5,7\], \[3,5,9\] The falling path with the smallest sum is \[1,5,7\], so the answer is 13. **Example 2:** **Input:** grid = \[\[7\]\] **Output:** 7 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 200` * `-99 <= grid[i][j] <= 99`
Sum up the number of days for the years before the given year. Handle the case of a leap year. Find the number of days for each month of the given year.
Math
Easy
null