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
428
okay let's take a look at leak code 428 serialized and deserialized and airy tree so yesterday i posted a video of the serialized and dc realized binary slash binary search tree and this problem is very similar in that we're gonna use pre-order traversal again uh gonna use pre-order traversal again uh gonna use pre-order traversal again uh i'm gonna you know do this problem individually from the previous problem excuse me so even if i even if you haven't watched that video you'll be able to do this one uh this problem just by watching this video so i mean i'll pretty much you know go over again the um how the dfs works uh how you use pre-order traversal uh how you use pre-order traversal uh how you use pre-order traversal and they'll do and i'll kind of just walk through step by step with the recursive call stack to show you how everything gets populated and traversed with the dfs so you can really deeply understand this you know walk through so okay so first thing we have to understand is the problem so to serialize and deserialize this basically just means um we have two functions we have a serialized function where we're given a root node and then we have to turn the root this tree into a string and then in the d serialize we're going to take the string and then turn it back into the original tree structure so um yeah kind of just going around in a circle um yeah so um the first thing you need to know uh is that with an enery tree um i think uh um yeah okay so anyways for the nra tree uh the main difference in how you recursively traverse it you know from a binary tree with a binary tree you can just call dfs of node.left dfs of node.right dfs of node.left dfs of node.right dfs of node.left dfs of node.right with the nra tree you don't know how many children there are so you have to just um you can't just like you know manually write it out like this you have to go through the array of children and then call gfs on each child like this so that's the main difference with the nra tree for this problem we're still going to do a pre-order traversal so let's just look a pre-order traversal so let's just look a pre-order traversal so let's just look at a pre-order traversal of this tree here a pre-order traversal of this tree here a pre-order traversal of this tree here and see um let's see how we would serialize it if it were the previous problem like basically just doing a pre-order basically just doing a pre-order basically just doing a pre-order traversal and then putting the null values where they belong so what we did in the last video for the binary tree is we just did we did a pre-order traversal so starting at the pre-order traversal so starting at the pre-order traversal so starting at the one we have the one then we go left to the three then we go left to the five then we try to go left and there's nothing there so we print the none and then we come back up to the five and then we go to the right print the none again then we go back up to the three then we go to the right print the six so if you're following along over here you can see we're printing out the respective stuff that we're touching and then once we finish looking at the six um six has no left no right so both of those are printed as none then we come back up to the three come back to the one then one will go to the two so two is printed and then the two children which are none are printed and then once two is done we go back to one then go to the four and then 4 is printed and then the children which are non are printed so that's what it would look like if we were to treat this as like a binary tree or if we were to serialize it the same way we did for the previous problem um uh so basically the problem with this is you know let's try to use this encoding to try to um i was trying to use this encoding to build the n-ary tree let's see build the n-ary tree let's see build the n-ary tree let's see how can we do that um so we have the one as the root obviously and then next we can have the three as a child then next we can have the um five as a child um we can have the nun as a child um see we just don't know where the you know where the child array ends for each parent the problem here is that uh we just don't know you know how many children this one has there's no information that tells us how many children one has we i mean for all we know the rest of these elements here could all be children of one right um this is a n area tree it doesn't tell us how many children each one is supposed to have um you know we're not given that information of n um you know if we look at the second example here this first layer has four children then some of these children of the first layer have only two children or one children right so we don't even know you know what the expected number of children is supposed to be so we can't necessarily we can't definitively say that these um you know we can't definitively place each uh node right we don't know the structure of this tree we don't know exactly you know this one could have like five children it could have one children one child you know it doesn't tell us so this could be another possible you know um destruction deserialization aka like reconstruction of the tree so you know another way we could you know create this tree is if we did um you know we put the nun down here so you know there's too many ways that we could you know uh interpret this data it's not conclusive there's no definitive way for us to know the relationship between each parent and which one which of the following nodes are considerate considered its children so we need a better way to serialize the string than just than the way we did in the previous um problem so an approach that we can take is we can capture the a second piece of data you know besides just the node itself we can capture a second piece of data which is the number of children it has right so um if we were to take this tree you know and break it down so it would be a node value of one and it has three children so that's what this first block of information is going to tell us and then following a pre-order traversal we following a pre-order traversal we following a pre-order traversal we traverse to the left and then the next piece of information is we have a node value three with two children right so that's what this next piece of val information is and then we traverse to the left again based on pre-order traversal based on pre-order traversal based on pre-order traversal and then we come to the node of value five with zero children right and then we do the same thing for six zero and then two zero and four zero so in this way now we'll know you know we'll know exactly you know how many times we have to call dfs to you know how many children it's going to have following it right so this um you know this three right here marks that we're gonna iterate you know from zero to three so the next three elements in this list are going to be considered its children and then you know respectively so like here this one this node of value 3 has two number of children in this piece of information so we know that the next two directly after are its children right so that's kind of how we're going to use this extra piece of information in order to help us create the exact same initial end area tree okay so now i'm going to walk through exactly how we're going to generate this in the deserialize function so just think of the dc realize as rebuilding it using the string and then building it back into the original tree so the first thing we want to do like i did in the last video is i'm going to turn this input string so the d serialize function takes in the string so i'm going to turn that input string i'm obviously going to split it and stuff but let's just say that it's already split by the delimiter of the comma whatever but yeah anyways just you want to turn it into a deck and the reason we want to use a deck is because you can pop off the front in o of one time and so we're going to need to pop off once we create a new node we want to pop it off so that the front of the deck is always going to be the one that's holding the next node that we should be creating you know if we pop off the one comma three then the next node we create is this three node value three with two children okay so i'm gonna start from scratch and show you exactly how this tree is built up i'm gonna i have some pseudo code here to kind of help guide us through the process this isn't the exact code but this is just like a little basic outline of what's happening and then this is just like the bare minimums and then there's a recursive call stack which is going to show you how exactly the recursion is happening and um when every node gets you know linked to its respective parent and stuff you know because let me preface by saying that in dfs um you kind of the nodes are not actually linked up until after it finishes traversing down one whole path and then once that whole path is finished then it'll go back up and then once it hits the return statement then it starts to connect the dots i'll show you what i mean by that in a second so okay so let's just start off by looking at this dfs method here so the first thing we do is we're going to unpack this deck.pop left so deck.pop unpack this deck.pop left so deck.pop unpack this deck.pop left so deck.pop left is just popping off the first item here so one hashtag three so the first number is going to be our node value second number is going to be our number of children so that's what i have represented here so let's process this let's pop it off process it and then we're going to create a new node with that value so we're going to create a new node with value 1 and then we're going to iterate in the range of that number of children right so we're going to iterate from 0 to 3 and then each iteration of 0 to 3 we're going to have we're going to add the results of a dfs call to the children array of that current node being one so right now we can this thing of this call stack is just like kind of keeping track of which layer we're in which node which nodes call stack we're looking at so right now we're looking at the call stack we're looking at the call for node one okay so um i'll keep updating this as we continue and so right the once node one comes into this for loop it's going to try to append the result of dfs and also let me say that we can append you know a dfs call because each dfs call is actually returning a node and you'll see in a second so um yep so the first thing we do is we go into another dfs call and then once we are in this new dfs call we're actually in a different um you know call stack frame and this new contact frame is for the node three and the reason is because during this call frame we're going to be processing the next item in the deck right the first thing we do is we always pop off the leftmost item in the deck so that gets processed three hashtag two so that is going to be created a new node with three with value three and two children is gonna be created so i'm going to just put this here floating in memory at some point so like i said these two nodes don't know don't have a relationship with each other just yet i'll show you when they do officially become linked up so you can just think of them as like floating around in space right now in some random pointers in memory okay so we just created this node right in this call stack and then we're going to iterate in the range of zero to two because this has two children so it's going to try to append a dfs call so then when we call this dfs it takes us to another call frame which is going to be for the call frame of node 5 right because at this new dfs call we're going to process this 5 0 and pop it off and then we're going to create a new node with value five and zero children so that's what's happening here and then we're going to iterate in the range of zero to zero so that this whole statement is just skipped because 0 to 0 can't be a for loop condition and then we're going to return this node the node that of the calls frame that we're currently in which is node 5. so this node 5 gets returned to its previous call to the call that it came from and it was called from this the stack frame of node three is the one that called the node.children.append and it called the node.children.append and it called the node.children.append and it called dfs and that dfs created this five so this five zero actually is being created by um this call from three as you can see right this uh the frame that we're current currently on was five and we just finished processing it so now we're going back to the previous call stack frame of three right so then three will continue um remember we need to iterate from zero to two for this one because it has two children so we only finished processing the first children let's make another node.children.pen let's make another node.children.pen let's make another node.children.pen call in this for loop so basically just calling dfs again for the second child and let's see what happens so then we're going to be brought into another call frame for the node 6 right because in this call frame we're going to be popping off the 6 and then creating a new node of 6 value 6 with 0 children and then so in this frame um so we're gonna iterate in the range from zero to zero so um that doesn't happen so then it comes down here and hits the next statement which is return node so it's going to return itself to whichever call that you know called it and the call that called it was um right here node 3 is the one that called it slot created it so we're going to return it to node 3 and so this is when it finally gets linked up okay so it gets linked up right here when this return statement happens okay so now node 3 has just finished its you know for loop it processed two children nodes and then now so this call stack for node three has just finished the for loop and now it's going to return itself to whichever call you know whichever call it came from so node three came from the call from node one so it's going to return itself to node one so now this is when these two get linked up okay so then after that finishes now uh now node one has only processed one out of its three children so now it has two more children to process you know in this for loop right so yeah so now it's going to call node.children.pen dfs it's going to call node.children.pen dfs it's going to call node.children.pen dfs again and then now this new dfs call is going to give going to bring us to the call frame for node 2 because that's the next one in our deck and so we popped it off and then we process it and so we're going to just place it somewhere in memory and then yep so then now we're inside this call frame for node two and then since has zero children this condition doesn't happen and it returns itself to whichever you know um call it came from and it came from node one's call so we're going to return it and link it up with you know its parent of one and then so now um we're back in the frame for call frame for node one and node one has one more child to process so it's going to call node.children.pen dfs node.children.pen dfs node.children.pen dfs then we're going to be brought into another new call frame for node four because this next element on the deck is four so we pop that off and we process it we create a new node of four of value four with zero children and then since um we're in this new frame and for i in range zero so for zero and range zero um we're not going to hit this condition and then we return itself with you know this node four to whichever call that it came from and it came from node one's call so we return it to node one and then yep so now node one has finished processing all three of its children it just finished this for loop for the call frame of node one and now it's going to return itself to you know whatever called this initial dfs call okay so now you can see why it's necessary that we have this second piece of information you know this um the number of children or in order to help us determine when to you know when to stop you know making dfs calls otherwise you know we wouldn't know how many children are belonging to each node so then it would just be uh kind of a free-for-all we could uh kind of a free-for-all we could uh kind of a free-for-all we could literally just recreate it any way we wanted there would be no rules no boundaries nothing to kind of be a barrier between each um node and its children okay yeah so hopefully you understood that problem please go and try and implement it um on your own now i'll have the code in the description and yeah thanks for watching
Serialize and Deserialize N-ary Tree
serialize-and-deserialize-n-ary-tree
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize an N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that an N-ary tree can be serialized to a string and this string can be deserialized to the original tree structure. For example, you may serialize the following `3-ary` tree as `[1 [3[5 6] 2 4]]`. Note that this is just an example, you do not necessarily need to follow this format. Or you can follow LeetCode's level order traversal serialization format, where each group of children is separated by the null value. For example, the above tree may be serialized as `[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]`. You do not necessarily need to follow the above-suggested formats, there are many more different formats that work so please be creative and come up with different approaches yourself. **Example 1:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Example 2:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[1,null,3,2,4,null,5,6\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The height of the n-ary tree is less than or equal to `1000` * Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
null
null
Hard
null
318
in this video we are going to solve a problem where we have to find the maximum product of word lengths so we are given an array of words like abc is a word then we have let's say bcd and so on many words and we have to pick two words out of this array and we have to pick the word such that none of the characters in word one word w1 matches with any character in word w2 so in this case b and c match so we cannot pick this maybe there is a word uh d e then we can pick that and the length of w1 in this case is 3 here it's 2 so the product of lengths of w1 multiplied by w2 it's 6 in this case so we have to maximize this product and if not none such word exist for example let's say we have a b we have a let's say this much only then we cannot pick any two words where the characters are not common any single character is not common because if we pick this and this a is common if we pick second and third again a is common if we pick first and third we have again common characters so in this case return zero and otherwise try to return the maximum such product possible so uh if you uh let's first think of a naive approach so first would be that we have to compare each word with every other word so it's like if you have 10 people and everybody has to seek shake hands with every other nine person so in that case total combination total possibilities are 10 multiplied by 9 divided by 2 that is 45 or more generally n multiplied by n minus 1 by 2 so it's of n square so this part we cannot avoid we have to compare all the words against every other word but the thing that we can improve is that if we pick two words abcd and let's say d e f g h it has a length of 4 it has a length of 5. so we have to check for whether there is a common character or not so we see that first character j we will find a here we did not find we move to b we try to find b here we did not find c and d so this comparison between just one pair of word will take m n time so if m is the length of first word n is the length of second word so it will take m n time and there are n square possibilities n square comparisons required so uh it will be so let's denote it with l1 l2 for one comparison and n square such possibilities so it will be n square only but this constant factor will uh increase the runtime so how can we improve the comparison so first we are trying to improve the comparison of two words and the only thing we have to compare is that none of the characters here should match this one and if we can bring it down to o of 1 then we are good to go we have optimized this comparison so what we can do this is not possible with characters treated as characters or like normal string comparison this is not possible so we will end up doing something like this so what we do we know that these characters will be only lowercase english alphabets so these characters can be only from small a to small g just 26 characters so what we will do we will represent the existence of any character in a word with a binary representation so for a it will be 0 b it will be 1 0 see it will be 1 0 d it will be 1 0 and so on you get the idea so for z it will be 1 at 25th place followed by 25 zeros and let's say if we have a b c a if we have to represent this so this has three characters a b and c so this is a this is b this is c so take the r of all of these so uh it's 0 1 so this will represent this so now we will pre-process this so now we will pre-process this so now we will pre-process this array and convert each word to this binary representation which we can think of as int so if we found a so we have a value initialized to zero and then whenever we encounter any character we process it and if it's a we left shift by zero if it's b we left it by one and so on and keep taking r so for a b c a we will get 1 0 now each word is an int instead of string and how much time this preprocessing took sum of lengths of all the words which will be better than this so here it's for each comparison this is n square times l i l j and so obviously this is much better some smaller constant here n square itself will be big and this sum amortized constant what is the average l1 li lj factor so now it's just a matter of comparing two integers and then what we will do two loops for i equal to 0 to n minus 1 or n minus 2 j equal to i plus 1 2 n minus 1 we compare if so how can we compare whether any bit matches so this is 1 0 let's say we have 1 0 1 then there is no character common in between these two but let's say if this is zero then there is a common character or rather if there is a one here then there is a common character so if we take end of these two if any bit matches and will be greater than zero if none of the bit matches and of these two will be zero and means bit by hand operator so if our w1 so w1 will be first of all w1 will be this array let us say a ai and w2 will be a of j so if w1 and w 2 is equal to 0 then only we will consider this pair then we will see what is length of w 1 multiplied by length of w 2 if it's more than some of the existing result so we will initialize a result with 0 and whenever we get a product which is more than the current best solution we update this result and finally at the end of this we return the result so i hope it's clear clearly it's o of n square with some constant but much better than comparing each word character by character so let's write the code for this in c plus java and python so for example if you take this example here we have two words a b c w and x t f n none of the characters are common and the length of first one is for length of second one is also 4 so product is 16 you cannot find a better product in this case similarly here 4 in the third example you see that no such pair is possible so the length is 0. and the number of words so words is the array is at least two words are there so some base checks you can skip for this exercise so n is the number of words so it will be words not size then we will convert each word to integer we will call it word int and its length will be in and initialize to zero we will fill this array then uh for end i equal to zero i less than n plus i so this is the preprocessing step that i was talking about you so let's keep a variable int uh so this will be the integer integral representation of this word w so this we are subtracting the sky value of a from all the characters all the english letters from small a to small g so for a it will be zero for b it will be one for c it will be 2 and so on then word int i is equal to w int now preprocessing is done and each word is represented by an integer now we have the result that is max product which is initialized to 0 and then again we will have 2 loops for each word pair each distinct word pair because if we compare a word with itself all the characters will be common so no point in comparing that you can keep n also in the end we will have one extra comparison last word with itself so that will be useless um so word into i is the integral representation of word one word int j is the integral representation of word two and if we take bit by bit wise and any bit matches this will be more than 0 otherwise it will be 0. so if this is equal to 0 then only we are interested and a length of word one that is uh you have to take words i dot length and multiply with words j dot length so you see that we will same word will be we will be finding the length of same words multiple times and finding the length may take some time so it's also a good idea to store the length of words beforehand in a separate vector we will call it word lim and here we can store it let's change this to underscore lamp since len is also a function in python so when we write code in python it may be confusing so here what we will do we have the length already world length i multiplied by wordland j and return max product so this answer matches let's submit and the solution is accepted now we will write the same thing in java and python and the java solution is also accepted finally we will write it in python 3. you so here we cannot directly uh subtract one character from other we have to call the function ord to get the sky value of this character and the python solution is also accepted
Maximum Product of Word Lengths
maximum-product-of-word-lengths
Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`. **Example 1:** **Input:** words = \[ "abcw ", "baz ", "foo ", "bar ", "xtfn ", "abcdef "\] **Output:** 16 **Explanation:** The two words can be "abcw ", "xtfn ". **Example 2:** **Input:** words = \[ "a ", "ab ", "abc ", "d ", "cd ", "bcd ", "abcd "\] **Output:** 4 **Explanation:** The two words can be "ab ", "cd ". **Example 3:** **Input:** words = \[ "a ", "aa ", "aaa ", "aaaa "\] **Output:** 0 **Explanation:** No such pair of words. **Constraints:** * `2 <= words.length <= 1000` * `1 <= words[i].length <= 1000` * `words[i]` consists only of lowercase English letters.
null
Array,String,Bit Manipulation
Medium
null
392
This is a Pakistani serial, today it's all its subsequent spider-man, it is a very simple subsequent spider-man, it is a very simple subsequent spider-man, it is a very simple problem, so let's stay on some questions, if this is a sequence, it means it is ABC, subscribe to Twitter and if not then for. Return and the sequence is subsequent. Suppose if this is CBI G DC such a write and the input that was in it was ABC then suppose if they want A is on BTU is NCTP means mask is also JPC, that in this There should be present and you can see that this is a seal, it is present in it, that means it is in the Air Force, but it is happy in one thing, but it is present in one thing, so in this also, we will not say anything about it, okay, then the position will be done, so if Suppose this happens, meaning first comes, then this comes, then comes again, is all this sequence, meaning this thing is a sequence with BTC, no, because the point is that it should be in the order format, see. You can say that this is that and that is a two after this it means one after this c means 300 0.21 shift Bahraich so there are such appointments 300 0.21 shift Bahraich so there are such appointments 300 0.21 shift Bahraich so there are such appointments and if it comes in full then there is no problem statement with it since morning so we understood that if you If cigarette is to be gold then there should be one thing meaning what is a chord there will be in the appointment and one thing should be in that element meaning the character which is there should be a paration so inside the right a 2 h is stuck then we will say Sab Singh ok so what we used to do earlier We were taking points. Okay, inches record has been set at 201. Now what should we do? We will run eightfold because we were running it, so in tie will remain, one more point A has come which we will select Jio SIM and what will be the condition. Which means the question comes, if it will run till this fort, then we will say ok brother, run till I lid and p dot length, if you are in August Plus, what will happen, what will be the size, okay now what do you do, make I plus here, you see. You can see what I had done that I was moving towards the right and here the one from Mala is Nighty and this is S, so its point will not go further but it will go before it, after this it will move ahead only when the exam goes on, only then Z will move forward. Plus ok then we will do the same friends, if you can see then after the clan plus after this we will take an ice and check this joint that if this happens then do one thing that is do plus I had done the same if suppose this happens Okay, so what will you do, you will start the return just like that, I did this, so you can see what I said here, if you do this then you reach till this point, that is, you check the seats, that means today, if you reach like this. It goes meaning if it reaches the seat then what will you do will you break down and if it doesn't reach like this means there is no present in it then it should reach here and not share all these trophies, if it won't do then what will you do will make it positive ok so I said the same. Done here, if this happens then do one thing, return the returned forms, ok, we will see after your submission, Jhala, why is there any problem, ok, who has written 120 here, then of course I have to write this also, if you know it is MP3, then also like this. We will have to do it okay if this is why then what will you do always dot length if let's say this becomes 110 then what will you do you will return true friend letter so now let's try it loan court at this time let's see that * Pron this time let's see that * Pron this time let's see that * Pron If you have any diet then you can ask in the comment section then see you in the next video. If you like the video then like it and if you have any doubt then you can comment. Bye.
Is Subsequence
is-subsequence
Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not). **Example 1:** **Input:** s = "abc", t = "ahbgdc" **Output:** true **Example 2:** **Input:** s = "axc", t = "ahbgdc" **Output:** false **Constraints:** * `0 <= s.length <= 100` * `0 <= t.length <= 104` * `s` and `t` consist only of lowercase English letters. **Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code?
null
Two Pointers,String,Dynamic Programming
Easy
808,1051
112
Indian Welcome Back to My Channel Ayurvedic Cream Events Today Will Be Solving Problems Facing Maximum Panch Samini Given in Binary Tree Now What is a Parts and This Seedhi Previous Video Aapta is Nothing But Any 5 Lakhs Start From Any Day Ago to Day Odds What We Call This Five Okay And In Emergency Single Not Will Only Use 106 170 Indian Old 05 2010 Newly Appointed Nurses Goal This And Welcome Back Leaders Such Characters Path Means This Fuel Like And Tapa Spa 2017 And Disappearing Once Upon Example Of A Pass For Fifty To Know Side Effects 1520 - 09 Dubai Multiple Get Pass That They Consider Avery 1520 - 09 Dubai Multiple Get Pass That They Consider Avery 1520 - 09 Dubai Multiple Get Pass That They Consider Avery Note Combination Tabby Multiple Five Right Swear Small Five Person Figure Out Witch For Kids In Maximum Summation Example Website Digital Spy Cricket Team Plus 2835 Plus 752 Superstition Maximum Mon Day Can Get They Consider Avery Life Every Need to Every Sadhana and Siddhi Maxims from the Comforts and I Want to Write a Program Dil Peace Lain Returns This Positive Energy Maximum Path Some Chor Gang Officer Like to Take Place and Comes to Mind Burial Solution and Comes to Mind Was Possibly and Trying Out every possible player of the day in this way the can do anything can be easy for any thing so ifin cry at every possible rough mention after and after every possible question which emergency is give me the maximum song again say that is My Fennel 125 Solution On Setting Of The Root S Complicated Editor And User Name And Travertine Square Combination Is Faux Prostate Fix We Already Leo Is Balance Clear And Creative Officer Of The Distance Between Two Notes Contact Update Mode Times Will Not Work Last Date For Institute Will go through something present in the previous videos Airtel Spinning Wheel Maximum Height of Binary Search Tree House in this video is highly recommended that you should definitely checkout this video for Mining's Maximum Height of Binary and as well as Foreign Lady with Thors of Binary Sadi Studio Software Developed And In Order To Understand Maximum Pass And Please Payment Scenes For WhatsApp Download Welcome Back To Difficult To Understand These Amlon Sukha Nahi Se Ek Mango Tanning 100 Figure Out What's The Difference Mum Indulgent Developed Maximum Baat Understand Left And Right The Divide into Maximum Parts Subscribe No Tension No Value Has a Value Only Left Side Effects of Subscribe Maximum I Will Definitely Be A Plus B Plus I Turn On This Particular Airplane Mode Astrology Note State Den O Fall Which is the Maximum Possible Notes For Short Term Effect Editor Visheshwar Width Out For This No Deduction For Soldiers Against This Background For Love You Might Of What Is Traveler 500 But This Is Difficult Maximum - Survey Of Channel 500 But This Is Difficult Maximum - Survey Of Channel 500 But This Is Difficult Maximum - Survey Of Channel - 2019 To Subscribe Node In Agreement With Every Node Maximum Hello Everyone Maximum Old Notes Will Be Amazed Maximum Parts Amazing This Strat Mix's Something Similar To What They Did In Finding Maximum With Five Every Right To This Award Is What Like Or Thinking Will Be Boil Group Cross Seen Solution And Drivers That I Can't Understand GBL Guru Son Of Mother Quotes From Finance Maximum He Of Mining Maximum Weight And Appeared Something Like This Illegal And They Are Doing Something F1 Plus Maths Of Shailesh Kumar And H And Issues Can Not Define The Maximum Height Of Ministry Of You Remember 100 Or Hooda Said This Egg Fried To Figure out of function marks path with which I am sending this modification Uttam Maximum SP Gautam Maximum off here and there on the left and here on the right leg Vishwasth Maximum on the sword and returning true simple and doing a nod for all Dual Open App Recent Posts Tagged With deposit time ki subscribe upat standing on thee northern lion is booty any maximum sub and picture white part ki vidhi maximum sub actress vo time basically returning and hua tha you might ask me pathav isko in health benefits bam bugad bam mother from left side discus He is on this platform awards to find for r voice for every note or backward vote left thumb otherwise evening and you can get for the snowden say to note hair plus summation of rights of plus lipsum so i d led f here and there left arm wires Case Andar White Dialogue Shimla In I Will Be Eligible To Apply For Mila On This Point England Misunderstand Not Anshu Electronic Bulb One Spoonful Of Mockery After X2 Like This Tight Just Make Sure World Wide Web Tracking Subscription To Win Mobile Banking Just Minute Invisible Maximum And Events Held by reference in c plus and waju mexico * map of mexico * map of mexico * map of mexico ma next emperor similar to what seen in maximum vis plus white sum plus note question duke and he is the value of x basically expression for problem-free did in maximum expression for problem-free did in maximum expression for problem-free did in maximum video these plots For Much Easier to Ride So Let's Start to Finish Chali I'm at This Not Work Well As You Marks Is After Not Defined As React Reaction Like Pass and Started Due to Denote the 100-yard Dash Will Not Be Recruited 100-yard Dash Will Not Be Recruited 100-yard Dash Will Not Be Recruited Annual App Will Smith Left Probably Moment Is Most Collection Lootra Press From Unknown Site Main Not Different In Ur Life With You Today Live With Absolute This Is The National Tree To Fight Against The Right They Want To Write A Notice Standard 9 And Always Love You All Subscribe Ultimate Left Subscribe to Android App or Maximum 10 98100 next 9 plus one side left waist white 16 2010 so let's return only no and 1 end withdraw all notes that - candy crush landing from left withdraw all notes that - candy crush landing from left withdraw all notes that - candy crush landing from left yes from left in water - yes from left in water - yes from left in water - miles - 97 Good Night So Lets - And Quote miles - 97 Good Night So Lets - And Quote miles - 97 Good Night So Lets - And Quote From Left No Mother Of Sorts And Good Night Good Friday This Kun0 Green Al Kurdi Left And Right Baroda Degree Left On Chiffon Left Leg National Sudesh Vitamin 0n Ride In All Situations Jio Store Ultimately Wires 15500 Phase Laptop Man Rights of One Platform Red F1 Plus White Editor Pro0 Press Note and 150 Hundred Maximum Get Updates Pane Fact That [ __ ] Returns 15th Else No Fact That [ __ ] Returns 15th Else No Fact That [ __ ] Returns 15th Else No Reward 56th Smart Shop Life Next Flight Like Sure Right The Moment Ghost Rider Hai Vasant Correct 300 Scored Friends Left Wisdom Right Both Rich And Tap 3000 1000 If Garlic Vitamin C You Right Samvat 2067 Isse When Will Consider Subha Or 000087 Show Your Body Maximum Will Not Be Questioned By Others But Why Does Not Be Considered Hands Relative Special No 885 In Maths And Left Right 1000 Episode 172 Nine Under 24th Nov 28th Nov 20th Left Including Team Right Samast To I Know On Left December 15th August Mixes With No Duty On The Road Durres Loop At Dahva In The Evening A Solid West Left Arm Spin Plus White Sanyam Baras Seven days plus 722 available weight more pava considered s 500 600 to 700 spotted achievement maximum 250 to 101 meanwhile sexual quantity of na which is the longest river witch you are residing this and beauty spa swift related or centers 98100 withdraw from this point Loot Notice Right One Should Right Dear Thodi 59 On Tap - 09 Dear Thodi 59 On Tap - 09 Dear Thodi 59 On Tap - 09 2011 0 Plus Minus 10th Se Divide Ventures Apni Something Pati Then In Section Or Twitter Maximum Till Not Be Returned In Just Imagine Dragons Madhav Lage In Return Not Well Which Was Built A Fixed Deposit Festival Mention And Relatives Ispat And Its 3521 Trick Serial 130 5 Plus - 05 - Its 3521 Trick Serial 130 5 Plus - 05 - Its 3521 Trick Serial 130 5 Plus - 05 - 150 Return From This Part But Your Answers To The Maximum Of Deposit For Every Node Difficult And The Umbrella Cut Everything Next Why This Logic Pregnancy Maximum Hit Logic Connection Help You To solve questions and answers-3 call back questions and answers-3 call back questions and answers-3 call back writing like share and you when you come back to you want you came back and money plant backtracking logic hua and mansi you sure mac or left wi-fi person three sure mac or left wi-fi person three sure mac or left wi-fi person three applied 2nd note coordinator lootkar android supplied Through this not love you thinking of cases this and yet maximum path and stated in this or Vikramaditya and set aside from 15th left divide unauthorized person to maximum wife umbrella of 500 1000 not consider that restart robbers similarly in the right and minus One Never Consider This Institute A Hero Fix Path Will Never Give Me Max For Them Instinct Ignoring Mist 15 Will Give Me Election Will Be Automatically Maximized In Which Characters You Ignore All The Naked Pass We Are Coming From Left Ginger Mix From Right Which Ignore Day Off Sodium porn tube the solve is the c plus co don left other runner mode on the white to initially the root right old maximum is in the developed in are because Vinod national note an available and not for status reference or worry not adapted size lineage increase answer Give Next Day Smartness Nothing Else Call The Function Of Viruddh Maximum Adverse Amazon Se Rudrapur Sahi Suparshvanath Maximum Additional Tax Return Zero Left Over You Can See This Appears To Be Uninterrupted Number Trap Definitely Tips Normal Note Considered Dubo Family From Ru Side Effects Negative From All Evil Returns Grown And Also Left Plus White Plus Not Well And Such A Person Maximum Increase The Return Of Rebel Plus Smartphones Laterite Dubai Jodi Maximum Pass Samudra Give In Nodia Justice Wave Girls Were Standing This Actually New Ventures Longest Parmesan Cheese Death About Someone Should Avoid Taking It And subscribe this channel maximum this and from two options with this pimples soil and activists who added this tube scanners then ultimately what this point is healthy wondering why did e two agree left and right some very simple guys if you this anicut - 1000 guys if you this anicut - 1000 guys if you this anicut - 1000 test wickets definitely but then it is near you know but after you don't know facts and deductive reasoning and maths of left and right very necessary to know about your life in and now these long hidden truth of life which for starting from this - not the person In this case you know which witch this boy Vyas trading deluxe Ramesh and SD rights under your intuition behind this approach questions temple ujjain explanation add court just in case you don't speech at many airports and sexual performance to make the sentence freeze also Like You Wish You Can Definitely Stop Comment Kajol's Mode Setting Me To Make Search For The Series Also Video Channel Please subscribe and 2012 Packet Vaadhar Series In The Upcoming Elections On State Andhra Pradesh BJP President It Came Cho
Path Sum
path-sum
Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22 **Output:** true **Explanation:** The root-to-leaf path with the target sum is shown. **Example 2:** **Input:** root = \[1,2,3\], targetSum = 5 **Output:** false **Explanation:** There two root-to-leaf paths in the tree: (1 --> 2): The sum is 3. (1 --> 3): The sum is 4. There is no root-to-leaf path with sum = 5. **Example 3:** **Input:** root = \[\], targetSum = 0 **Output:** false **Explanation:** Since the tree is empty, there are no root-to-leaf paths. **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-1000 <= Node.val <= 1000` * `-1000 <= targetSum <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
113,124,129,437,666
714
hi everyone so let's talk about the base time to buy and sell stock with transaction b so you're giving given the price array and also integer fee so you want to find out maximum property you can achieve and then if the constraint cannot do the subsection simultaneously so which means you want to buy and sell the stocks on same day this is not working so here's it so we want to just assume uh we will buy the first stock no matter what because we'll just we just assume we will buy the first stop and they prefer 600 then we just assume we buy a hundred dollars because it will just keep comparing do i buy the smallest value so far before i sell the stock and then before i sell the stock i need to make sure i get i have a maximum profit so the logic is this you buy the stock right and they want to sell the stock with the maximum profit so let's not worry about that multiple subscript uh multiple transaction and finally maximum profit we just want to buy and sell for one stock right so we will not at least point eight will be the maximum profit to sell the stock and we also need to uh debug the fee right so we will have to assume we sell the stock at least right so three minus one minus two because of b right so you will get zero right so this is probably the so for the base transaction right because the seller stall and then the profit is still going wouldn't be zero right all right so now we will just assume how about we sell the stock uh at this stage so it's gonna be one two minus one minus two this is going to be negative value right this is even worse because if i don't buy anything right i don't i mean i probably won't lose a dollar right so this is what the pay investment right all right let's move on to the next one eight so this will be a minus one minus two so you would go with that you got five right so five will be the maximum profit circle so when we do a transaction we got we know the profit is the maximum and then the next number is for four right so four minus one minus two which is three so we already know that this should be the maximum profit so we will sell the stock at this point and then buy and then rebuy the stock at this time right at four right so this is some logic so the rest of it should be the same so let's stop holding so i do have one i don't have in five i'm going to assume i buy the first one negative value price of 0 so if i want i listen price dollar length so what does this mean if i'm going to assume i buy a person and definitely i got the zero profit right and so i would say okay if i want to sell the stock right that's method max so the cell will be what the maximum record the maximum profit i have right and what should i compare like just give it a try right uh you won't do what you want to say okay this is my buy right my pie is a negative value right and also what i also need to just try to calculate like the current price uh for policy and also deduct the fee right so if this is working then i would update myself right if this is not working right i'm going to update my eye because there might be a value um which is what which is uh maybe there's a better price right so for example uh just um just for example the price array is three one two and then eight four nine right i assume i buy the first one but the following day is what it's more uh lower so you definitely buy it by one dollar in fifth right this is good investment if you still think about like three dollars right you probably will lose a lot of money right so uh if you want to buy again right you have to use your profit right your profits is what sell right sell minus price and i right because if you want to buy it again right you are losing money right so you use a profit to sell i mean sorry to buy the current price so you want to find out the maximum which is what negative one and negative three which ones are lower which is uh so which one is maximum which is negative one right so uh this is the logic and now you have to return you profit your profit is uh i think i made a typo right over here prices all right so here is it so let me pause it all right so here's the solution so there's a couple of times in space this is a space all of one this is the time all of un right and represent nano flow array and this is supposed to be the solution and once again you have to know a logic so just don't think about like you want to buy on the second time or third time so just making sure you know if you do the transaction successfully on the first transaction then you will do uh do better i mean you will find out the next objection automatically all right so if you didn't subscribe and then leave a like leave a comment right all right i will see you next time bye
Best Time to Buy and Sell Stock with Transaction Fee
best-time-to-buy-and-sell-stock-with-transaction-fee
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `fee` representing a transaction fee. Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** prices = \[1,3,2,8,4,9\], fee = 2 **Output:** 8 **Explanation:** The maximum profit can be achieved by: - Buying at prices\[0\] = 1 - Selling at prices\[3\] = 8 - Buying at prices\[4\] = 4 - Selling at prices\[5\] = 9 The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8. **Example 2:** **Input:** prices = \[1,3,7,5,10,3\], fee = 3 **Output:** 6 **Constraints:** * `1 <= prices.length <= 5 * 104` * `1 <= prices[i] < 5 * 104` * `0 <= fee < 5 * 104`
Consider the first K stock prices. At the end, the only legal states are that you don't own a share of stock, or that you do. Calculate the most profit you could have under each of these two cases.
Array,Dynamic Programming,Greedy
Medium
122
427
In this video we will discuss the problem of Construct Battery, its category is medium, what is this problem and then you have to construct it. There is a data structure in which each internal mode has tax children and apart from that it stores two data. Basically the structure of each mode will be like this, there will be a variable in it, there will be a value, whether it is lip or not, apart from this it stores its children, top left, top right, bottom left, so this is the structure of each mode in the battery, for that we Let us look at this example given here, first of all we check whether all the cells are zero or one then what will we do but what is there now then what will we say that this is not a lift, we will make a note my note You can store it in it. It doesn't matter that you cash in value. When it is not a note and not a leaf note, then what you have to do is divide it into equal parts. After dividing, it becomes yours. Top left This is the top right, this is the bottom left, this is the bottom right and you have to double check that this is my part, this is the part that I had divided, this is the part in this, because now only one cell is left till we are on the left. We will store this in the part, this is the leaf note, what will come in value, which is the value of this cell, whatever is our great, the value of all the elements in it, what is zero in it, so we have shown here zero and its children will be. So, Left Top Right Bottom Left Bottom Right, how will we add which one because it is a leaf and not a leaf? Then the day before yesterday we had discussed what to say in Reckon, so now we will come here and see on this one, what is the value in it. If there is one then you will remain this is leaf note and its value is one and if we make it into property then how much is it then we will come in the bottom left. Here we will say leaf is what is the value, it is one and we will make it more in the bottom left and then we will come. There are no tax children and what did we do for distribution, top right, create tax children, which we have updated, so in this way, what happened in this part, a note was created and its tax children were created, then we have all the tax information in this part. If it is from then we have written it down and given the value ' we have written it down and given the value ' we have written it down and given the value ' I' in this part. In this part, there are all from ' I' in this part. In this part, there are all from ' I' in this part. In this part, there are all from ' so we have made it zero. If it was not from 'then so we have made it zero. If it was not from 'then so we have made it zero. If it was not from 'then what would we have done in these parts too? All divisions perform. No, we don't have this problem.' What is given is that the value of n will problem.' What is given is that the value of n will problem.' What is given is that the value of n will always be 2 rest tu power something will always be square what does this mean and is the power of tu that means we will always be able to divide it into equal parts like how much was it 8/8 So, like how much was it 8/8 So, like how much was it 8/8 So, when we did this and divided the total, then what became of 1 minute? When we divided this and all, what became of 4/4? Do we have to When we divided this and all, what became of 4/4? Do we have to When we divided this and all, what became of 4/4? Do we have to do the same or not? If it is not there, then what to do, divide it into parts. Check for if the process is related to the value of all then make it a leaf note. Once we see the code implementation of how we are doing it, first of all we have this in the class and inside which we have given What is the structure of each mode? Store these two data values ​​and Store these two data values ​​and Store these two data values ​​and each one has tax points. Then we are given three constructors that if we do not specify anything, what will it do to everyone, it will set it by default and will make the points null if you Value: If you points null if you Value: If you points null if you Value: If you give a value then what will it do, it will set the value in the value and in the last it is given to you, if you specify the value of all these, then which will give the value, then this has given us the definition of a class, inside which we have three Types of constructors are available, after that we have been given this function, inside which we have given the matrix which we have to convert into quarters, so first of all what have we done inside it, we have written our extra function inside which what can we pass? We are passing the grid, we are passing the top left zero and the size of the grid. How can you pass a square? In any function, specify whatever is its top left starting cell, columnify its roads and make it square. With that you will get complete pass because all the sites of Square are equal so you can calculate only from these three values, hence we have passed the size of the lion from the beginning and whether our help function is from the value of this cell or not. If it is from then what we had to do was to create a leaf note, so what we passed is the proof that this is a leaf node and what we passed in the value is whatever is the value of one of its cells, we passed that to create a leaf note. Two, what will be the value of its cells, whatever its value is and if it is not equal to the value of all your cells, then what we had to do is we had to divide it into equal parts, so we have done the same here, we have one of our nodes. In which we have said that value can be given by one value, this is not a lift, first give anything, put force in the note and whatever points we do, requests will be made in it, pass their coordinates, what should we do? We have to divide it into 4 equal parts, what is the meaning of dividing it into five equal parts, how many will be blue / 2, that is, whatever I how many will be blue / 2, that is, whatever I how many will be blue / 2, that is, whatever I pass in the third parameter, what will it become? Blue / 2, everything will be blue / 2, Blue / 2, everything will be blue / 2, Blue / 2, everything will be blue / 2, my change. What will happen to my starting net, what will go first, will go next, Blue / 2, what will happen to this one here, my Blue / 2, what will happen to this one here, my Blue / 2, what will happen to this one here, my row, what is it from, what is the pen, what is Blue / 2, if it will row, what is it from, what is the pen, what is Blue / 2, if it will row, what is it from, what is the pen, what is Blue / 2, if it will move, then I have it in the pen, K plus Blue / 2 Then my photo will be changed and in the end a note will be made and I will return it. What do I have to do? We have to check this. Inside this, take some cells. We have to check whether the value of all these is correct or not. So here is this one. If we have passed the sale, then we will put its loops. For the saree Ross, we will run loops through all the pens and compare each value with this value, if the saree value is equal to it then it is from the saree value, if not then we will get a look. From there we have passed Lok Sabha and I Plus Blue which we have passed till there and check that the value of our current cell is equal to the IGL which was this cell or not. As soon as any Also the value will come, it is not equal i.e. if we are not equal to all the values is not equal i.e. if we are not equal to all the values is not equal i.e. if we are not equal to all the values then we will turn from here. If our loop runs and this connection of ours is never true then what does it mean that the saree is by value so in this way What we are doing is we are writing a help function in starting in which we should start with our matrix and its size i.e. we should start with our matrix and its size i.e. we should start with our matrix and its size i.e. what should we do at starting, divide it into four-five and what should we do at starting, divide it into four-five and what should we do at starting, divide it into four-five and repeat it by writing from here no its time. What will be the size of our metric? M*N. This side of it is Ma M*N. This side of it is Ma M*N. This side of it is Ma Let and this side is Ma Let M * Let and this side is Ma Let M * Let and this side is Ma Let M * N and because it is square then it will be from both M and M so we can say n² is the size of our matrix and what we are doing every time is to divide it into parts. What is meant by dividing is that whoever is going to sit in my starting line will be y2, so how many times will I have to divide like this, maximum 4. * 2 maximum 4. * 2 maximum 4. * 2 First I used to divide this will become my one part one, then I will divide all these, if I divide all these, then basically I am making 4 parts and after dividing each part, people will consume this at some time. What will happen to our time complexity? I am taking n² because this is our holes in function, what it is doing is that it will run the loop every time to check whether all the values ​​match or not, then what will we need for this, values ​​match or not, then what will we need for this, values ​​match or not, then what will we need for this, n² will be needed and how much will it be? We will have to run this many times. 4 * Logan, we will have to run this many times. 4 * Logan, we will have to run this many times. 4 * Logan, we will have to run this many times and this country of ours will come to the Black City. Basically our Recon Express will come. Whatever is ours will come. So, maximum, how far can our depth go, can we prepare till N, so this is our space. Complexity will be reduced thanks to gas
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
888
Hello guys welcome to problem in lead code called fair candidates where and reduced problem Elva Edison bread different size where is the size of the white beard angry bird lies in the side of the cheek and subscribe our Answer subscribe The Channel and subscribe the Channel Please subscribe and subscirbe Total Number Total Amount of These Questions Candy Barich Saffron Se Elections.The Ice Candy Barich Saffron Se Elections.The Ice Candy Barich Saffron Se Elections.The Ice and Electrical Embroidery and Senior Ladies Only 10 for One Can Divide Festival Total of Tourist Centers Vansh Give One Instance Restaurants Two Minus One Plus Two Wheeler Mountain Is Some Will Be Left With 3 Singrauli Brace For Equal Gives Away But You Can Never Be Left With Two And Protects One From Life Will Get 300 Very Flirt 30 Second Example C Vacancy Alison Talents Se 225 Celebs Give Away Every One And Take Dar To She Will Get For Rest And On His Five Effigies To Amount Of Candybar Bill Committed Native Will Also Help Chart Similarly All Are Example Sardar Like This Switch On Us Both Of Them Have Shorty Candy Crush C Indore Last Example Of Hai Sum Total Of Bechti Candy Crush Off 125 VS Assam Total Sum Balance Gir White Candy Butt Rock Candy Beta Mode Switch Shilpi Left With 3 And Should Take A For Such Evil 7 Debate 6 9 News Room 17 All Log In Weather For More Can Be Built A Bill To Improve Will Have 700 Wide Questions And Simple Problem You Can Influence The Absolute 4904 Elements In Both Cases The Relation Between Avatars And See The Question From Salary Of An That Sensor Angry Bird That Is Gold Ax And She Tax Candy Without Option Provide For Jobs Will Be Left Out Food And Difficult Former That Assam Professor Initial Evening Anything After 10 Give And Take Samay Isse That Is Required This Relation Equal To X Plus Minus 1.2 Times To X Plus Minus 1.2 Times To X Plus Minus 1.2 Times Will Do Any Time So Let's See What Do We Celebrate Previous Declaring That Someone Today I'm Going to Find the First in Both of Peace and Subscribe Question is equal to two Let's See What We Can Do Smartly Choices Hydrate Through the Second Merit Suggestion Heroic Lead Tricks Pending Second Lottery Louisville Store Sum Too Right Sum of All Elements Nautical Records Vibrating Golden End All Should One Thing Immediately To All Elements Have Been Set S Later Meet Weekly Declare Set Intes One Should Declare Saturn Will Just To All Elements In The Assembly Edward Norton Shirt Beat All Elements Of Matter All Elements For A Year For The Third Know What Does This Incident Twitter All The Evening Element Direction Laddoo Xray In Off Santa That And It Can Compare With Sequence Getting Satisfied Notifications Cutting Side Effect Vibrating For Witch Element Situation Get Satisfied With His Divine Astro Dash Including Answer And Adjust In No Way Return I Answer Subscribe Tab Return After Interview Answer Soldiers Declare Equal Vitamin Today Don And Decided To Dry Up To Elements Lift Spondylitis Acid Bobby 609 Verification Moff Move That Hair Oil Subscribe Lord Of Ring Road In 1 Minute Right To Do Something First Schedule With Patience But Know It Means Achoo Universe Time To Sects And Just It Provided Through Layer Let's Embroidery Meeting Characters Now I'm Fighting Rudra Service So Far It Is Just Declare Here Auto It And It Will Automatically Europe Compiler Is Going To Find The Hydrate Available Means The Type To That Available And You Can Also Not Just Clear Normal Dhela Compiler What Is Possible That Some Will Give Its President Letter This Is It I Will Be Used For Dog Lovers Decided To Go Into It * Find This Element Lovers Decided To Go Into It * Find This Element Lovers Decided To Go Into It * Find This Element Residents Are Wow Re Wow Pims Already In The State Governments Were Formed Elements And Specifications Need To Find Elements And Spiders Equation In This world where answer 800 olx just c s one daughter of mind also access nothing but element of a sweet viewers pe android plus middletown not declared its yours sam2 - someone buy to declared its yours sam2 - someone buy to declared its yours sam2 - someone buy to latest what is the world top and you updated on feature it is it and Spent with you find C files sibil to find in this will return something is not the sibil 250 parties not equal to a sworn in for development in the system you answered push back person squashed element aspect slim interest it his nv channel subscribe for this element Box Element Winters Paste Delta Withdraw This Element And You Can Also Lead To Unlock Answer Now He Also Have To Give Return Answer And Because Its Compiler Will Not Accept Dancer Need Something To Know Return To In Adhi Yukt May Soe The Largest Continent Back It Surya Tempo button to good dreams or note exempt workplace track from now on half cutting and militancy 500 yards test cases for rent pass it's not given time limit exceeded the passing thank you
Fair Candy Swap
mirror-reflection
Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the `ith` box of candy that Alice has and `bobSizes[j]` is the number of candies of the `jth` box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return a_n integer array_ `answer` _where_ `answer[0]` _is the number of candies in the box that Alice must exchange, and_ `answer[1]` _is the number of candies in the box that Bob must exchange_. If there are multiple answers, you may **return any** one of them. It is guaranteed that at least one answer exists. **Example 1:** **Input:** aliceSizes = \[1,1\], bobSizes = \[2,2\] **Output:** \[1,2\] **Example 2:** **Input:** aliceSizes = \[1,2\], bobSizes = \[2,3\] **Output:** \[1,2\] **Example 3:** **Input:** aliceSizes = \[2\], bobSizes = \[1,3\] **Output:** \[2,3\] **Constraints:** * `1 <= aliceSizes.length, bobSizes.length <= 104` * `1 <= aliceSizes[i], bobSizes[j] <= 105` * Alice and Bob have a different total number of candies. * There will be at least one valid answer for the given input.
null
Math,Geometry
Medium
null
124
binary tree maximum part okay so in this question what we have address of the root node of a binary tree and what we need to do we need to return the maximum part okay so basically what we need to do is we have lots of possible parts right so let's say this is one part this is in fact also one part so we have n number of parts and what we need to do is find the heart which has maximum some heat so how will do this pretty basically go all the nodes will basically go again this is a mission we basically go to all the nodes of a binary tree and find some of part eight and the maximum among all of them will be our answer right this is it this is how we are going to solve this one okay so let's just let just fix a root node as our source node and find the possible paths on founded move okay so if we fix a root node as a source node then one path could be this we will we don't go anywhere we will stay on that node so this is one possibility so this is one part so this is our path number one another path could be this we will go from minus 10 to 9 so this can be our another path one path can be we will go from minus 10 to 20 so this could be our part number three eat one path can also be this whole thing right yes - nine - sorry nine - nine and yes - nine - sorry nine - nine and yes - nine - sorry nine - nine and twenty so this is our path number four okay Path number 5 can be will go from minus 10 then 20 then 15 so this is our path number five eight Path number 6 can be will go from minus 10 then 20 then 7 so this can be our part number six okay what number seven can be will go from minus nine then minus 10 then 20 then chippie so this is our part number I think seven eight okay one more possible part we can have is we'll go from minus 9/2 minus 10 then is we'll go from minus 9/2 minus 10 then is we'll go from minus 9/2 minus 10 then 20 then seven so this can be our part number eight I think this is it this is all the possibilities from Italy repeats our group not as a source node right so let me write it down here okay so these are our path pattern one two three four five six seven so what is our part number one but number one is will not go anyway we'll stay on that node so the sum for this part could be can be actually it is - time and some actually it is - time and some actually it is - time and some for this park is minus one some for this park is plus ten some for this path is ninety some for this path is twenty five some for this path is 70 some for this path is thirty-four some for this path is thirty-four some for this path is thirty-four some for this path this v6 okay so fine so what we will do lecture this is our answer so initially we are storing at least possible value over and be there so it is actually minus 2 to the power 31 minus 1 so let us assume it is minus infinity so we will compare we'll compare all these parts and find maximum among all them so maximum all them all of them is this one this is part number seven is it 34 so what we will do will update our answer by this 24 so here it should be 34 so 34 is which path 34 is odd number 7 so we are talking about this part so we have found one path which has maximum sum if we treat our root node as a source node it if we treat our move node as a source node okay let me raise it fine so it was this part right it was this path and our answer for this instance is 34 but hey what we need to do is we need to repeat these steps for all the nodes of this binary tree right so what we gonna do we gonna fix each node of this tree as a source node and find all the possible paths from them and then we will find the maximum sum of that path and then you compare it will up with our answer and if it is greater than our answer then you update our answer right so let's say if we come to this node if we treat this node as a source node and we will find all possible paths from this node right okay so we cannot go upward right in my tree we can call go early downwards so what possible path do we have from this one path is window we don't do any will stay there one part can be we go from there to there one path can we will go from there to there and one part is this whole we go both direction right we can go both direction so there are four possible paths will find some of four possible paths and find the maximum on there and then we will compare that maximum with our answer if it is greater than or answer then we'll update our answer otherwise this should be this will do for all the nodes of our binary tree right so this step we are going to repeat not mandatory and this is nothing but the algorithm to solve this quotient right okay I hope the algorithm is clear to you guys name is near to you now let me show you the code of this problem so right you guys can understand how the algorithm can be implemented Hey okay so let's just take the example again so this was our tree right let's say the address of root node of the tree is given to us so what we gonna do we want to create this find max path function and what we'll do we'll pass this root for this address read function right okay so what we going to do in this function see we are doing just nothing we are fixing one node and find all the possible paths from that node and finding their sum if sum is greater than however this maximum that is nothing but minus infinity then we will update it otherwise we'll do nothing right you guys can also see here if root is null then we'll return 0 like for example we come to here so it is null so return 0 if we come here than in return 0 but C let's say but we are finding in this left variable we are finding what is the value of maximum part of your left subtree right this is what we are finding here and what here what we are finding here what is the value of your right maximum subtree right actually we are finding it here but we are finding the value of left subtree the in what we are finding here with the path which has maximum sum in your left subtree and here what we are finding the path the sum of path in your right subtree which is the maximum value but hey why are we taking this maximum with zero hate so let's see that's it there are two more notes are there see this 20 minus 20 n minus 2 like so you came here now you have you how many parts do you have from that node so one part is you'll stay here go to anyway right another one can be you go from this to this and second option is you go from this to this I mean trade option is you go to this and fourth option is you completely include all these three moves right so see the best option for this case is this both the nodes are negative both the side so the best way you will not go anywhere and you will include this node has a maximum path number 8 so that's why we will find the value of maximum path some from its left so it will come minus 20 so if it is minus 20 so it since it is negative so what you will do you will make it 0 I didn't make it 0 so instead of returning minus 20 from there we are returning 0 actually and similarly we are returning 0 here actually so this is nothing but the case you don't go anywhere used you usually at your node and this will be the maximum path so from that right so this is directly okay that's why a VAR we are taking maximum of its left and right subtree with 0 okay I think this is clear to you right now what we are doing here this is our final answer this maximum so we are taking maximum with left that's right + root dot value with left that's right + root dot value with left that's right + root dot value okay so let's say they just come to register on to this so if we were treating this node number minus 10 is the source node so answer was our answer was or credible but hey if we treat this node as a source node and if we talk about this spot this complete path then can you tell me what is the answer so if we add 2015 7 so it will come out 25 35 and 742 I guess yeah what do you hey and 42 is of course greater than this static oh right so this is nothing but our maxim and this is the this is our root dot value for that case if we are treating that node number two it is a root node as a source node sorry this routine is value of a longest value of path some maximum path some from left subtree this seven is maximum path some from right subtree right so the addition of all these three things is 42 so see this is what I do visited equal so that is what we are doing here we are taking happy for or 42 maximum so since 42 is greater than our maximum so we will update our Mac sound from 32 to 42 34 to 42 right so this is what we are doing here that finally this we will it on this so this is basically nothing we are basically finding the maximum of our left and right subtree right and adding it with our root daughter right so our final answer will be this maximum so this is what we did right so okay I think this is it this is the code of this problem and that is how we can implement that algorithm right okay I hope you guys enjoyed this video thank you so much for watching
Binary Tree Maximum Path Sum
binary-tree-maximum-path-sum
A **path** in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence **at most once**. Note that the path does not need to pass through the root. The **path sum** of a path is the sum of the node's values in the path. Given the `root` of a binary tree, return _the maximum **path sum** of any **non-empty** path_. **Example 1:** **Input:** root = \[1,2,3\] **Output:** 6 **Explanation:** The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. **Example 2:** **Input:** root = \[-10,9,20,null,null,15,7\] **Output:** 42 **Explanation:** The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42. **Constraints:** * The number of nodes in the tree is in the range `[1, 3 * 104]`. * `-1000 <= Node.val <= 1000`
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Hard
112,129,666,687,1492
392
the holiday today's liquid in challenge question is called a subsequence we have two strings s and T we need to check if the first string is the subsequence of the second one subsequence of a string is a new string obtained by deleting some of the characters from the original string without changing the relative ordering of the remaining characters so obviously T is going to be longer than s so we have to remove characters on till that T and s have the same lens and when we just compare the as another modified version of the T they have to have the same character set and that the order of those has to be the same so that's the one we want to determine if we can do so it's just going to take an example and try to manually do this ourselves it will give us intuition about how the coach the word at least thing a blue force kind of solution would be can be obtained by this so we're just going to look at the characters in T and determine do we need to remove that to have that basically align with the s so this deletion is will actually remove that so instead of doing that I'm just going to add a space for the first one indicating whenever I have space the corresponding character from T is the one that I wanted delete so it's pretty much already done now we want a to match a t be too much we see too much see and the nonsense that's happening in between has to be deleted from T in order to make s to be no equivalent to T so just to based on this really quick example we already see how we can easily approach this we're just gonna scan the two string try to match the eyes character in front s if we do have a match we advance I then in t we will try to search for the to be once we find it we can advance I to the next character and then go back to T try to find the character that matches C so once we you know advance i2b2 to the end of s it means that we satisfied the questions requirements so other time can return true if we run out of characters you know Jake come out or after we explore T is yeah basically if Jerry runs out of the lens of the T that means we couldn't to do this so it will return false so that's a pretty simple solution just by looking at how we manually do this alignment we can figure out that I'm just gonna do four characters in s we're trying to find a matching character in T so we start from zero and T so while I'm not out of the I haven't run out of characters in as in T and the current one I'm looking at is not the one that I want I would just advance this to the next position next character to see if that works if I exit this while loop there could be two cases one is that I find a match that does when I should advance the character in s that's go to the next generation otherwise it would be I want to check house as this pointer come out of the total characters we have in T if that's the case we return false if it's not this case you must be that we can advance so for that reason it would be you know finding a match for B then we also want to advance the second pointer I know it's only be confusing I'm using I they're about using J for the T but in the code I'm using anyway it should be easy to understand yeah so this is pretty much the code to solve this problem alright so yeah it's a linear path algorithm what we do is to basically do a linear scan to in T and s so it's those two string lines are two together that's the you know that's when we the only the rare luster character we can match to have those two figure it out so that's the two lines added together for spaces constant let's talk a little bit about the full up so let's say that we have the Sam T but we've got a bunch of s that we want to check is there anything that we can do to improve the code so one thing that we can do is to run some statistics on the T so basically we'll do it as a for every character we recorded so location its zeros position maybe P let's happen that one five nine or something so when we have a s we still do the kurta by character kind of trying to match that but instead of do a linear pass in T what we're gonna do is to if I wanna a I just check do I have a which location out of that it is not where is it so once we match this we have to try to match be but when I look for the list of positions of B and T I will pick the one that's larger than the one that I previously used a father prior character so this can speed up the matching a little bit faster so that could be a potential way of solving this follow ups so we just do one pass to create this statistics and for every string incoming string you want to the subsequence checking you do still do character by character but no longer go to do a full scan of the target string that you know the t string but instead of just doing some calculations on the statistics you get so it could be faster alright so that's the question today
Is Subsequence
is-subsequence
Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not). **Example 1:** **Input:** s = "abc", t = "ahbgdc" **Output:** true **Example 2:** **Input:** s = "axc", t = "ahbgdc" **Output:** false **Constraints:** * `0 <= s.length <= 100` * `0 <= t.length <= 104` * `s` and `t` consist only of lowercase English letters. **Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code?
null
Two Pointers,String,Dynamic Programming
Easy
808,1051
1,772
hey everyone this is steve today let's go through lithium problem 1772 solve features by popularity i think this is a problem that came up in one of the recent contests pretty straightforward but still it's fun that i used a combination of anyone could use a combination of different data structures so first let's take a look at the problem description you're given a string array features where features i is a single word you see features this is features i could lock touch all of these a single word that represents the name of a feature okay all these three are features of the latest product that you are working on you have made a survey where users have reported which features they like you are given the string array responses where each response is i is a string containing space separated words okay space is the delimiter i like cooler so a total of four words it mentions cooler twice right so the popularity so here comes the definition of popularity the popularity of a feature is the number of responses that contain the feature you want to sort the features in non-increasing order by their popularity non-increasing order by their popularity non-increasing order by their popularity if two features have the same popularity other than by the original index in features say if cooler and lock they have the same popularity supposed and then we'll arrange cooler appear first in the result because cooler has a lower original index than lock right 0n is 1. all right that's what it means other than by their original index in features notice that one response could contain the same feature multiple times like cooler right the same response contains this one feature twice that's what it was referring to this feature is only counted once in its popularity all right so here is something we need to pay attention to although this word this feature appears twice more than once in this response you'll be counted only once all right so only once is counted so it's asking us to return the features in sorted order let's see so appearances of kuder so kuder is the first feature that it appears once right cooler appears only once there are three responses here one two and three but cooler appears only in one response although it appears twice we count only once right i like cooler appears once in one response cooler appears twice but in could it appears twice but it's in one response all right so then appearance is locked lock is only a once it's in the second response right locker is not equal to lock and then touch appears twice so touch here and touch here so it appears touch appears in two responses that's why it touches two since cooler and lock both had one appearance cooler comes first then lock so that's the why there is a cooler lock and the first one is touch because touch has two appearances in two different responses all right this is the problem this is the context very straightforward so the idea that came to me is that we can just follow the description or definition of the popularity and what it's asking us for we can just follow this as any very intuitive solution we can define a class for example called node let's see i'll just call it class node you can call it whatever you want we'll have three fields one is index which is it's original in index because just in case there's a tie of popularity would use its original index to sort it and the second is popularity we can call it frequency and the third is just the feature we can call it words word right so what we can do is that we can build a priority queue of a max heap and how do we sort the max heap or the priority queue is that we use two sorting rules one is that we'll use priority based first if that's a type in terms of priority we'll use the original index after that we'll just keep pulling everything out of the priority queue and assert them and put them into this string array result and then return that's it so how do we form this node we can use hash maps we can use two hash maps to help us achieve how to build to go through all of these nodes to build all of those these node objects and put them into a priority queue the first hash map could simply be we can simply turn this features array into a hash map so that we can have easy access based on the feature to its original index and then the second hash map we can just go through this responses array and remember we need to then separate each of the response from these responses into space separated strings and then we'll count only one feature out of this space separated strings from one response as once and then add all of the popularities into the second hash map with the second hash map along with the first one we can just build that priority queue and insert all of these node objects into this priority queue in the end we'll just pull everything out of them priority queue i hope that makes sense if it doesn't or if it's not super clear just bear with me let's just put the idea into the actual code hopefully everything will be clear so first i'll have a map as i said the first map is very straightforward it's just going to give us easy and quick access to the index of the features right because we need it uh integer so the key of the hashmap is the feature itself and the integer the value of that first hashmap is just going to be the index map and then we just go through this zero i just wanted it of course there are multiple other different approaches to solve this problem i'm just talking about the one that's most intuitive and the one that occurred to me and so feel free to comment down below if you have any other ideas of how you want to optimize this i'll be happy to take a look and see how you guys do this three features length i plus and then map put features i and i all right this is the first one and then the second one we need another hashmap is basically 2c so we need a second hashmap it basically tells us how many what's the popularity of each feature right so the key is still the feature but the value is still an integer type but the value is going to represent the popularity right of each feature i'll call it count map make it more descriptive and then what's next we'll go through all of the features now uh we'll go through all of the response now responses all right so we'll just go through every single response since it's talking about the feature is only counted once in its popularity just in case that one response could contain the same feature multiple times although it's multiple times well count it only once because it's one response so what how do you dedupe deduplicate this right so we're just to use a hash set a hashtag everything every element in the hashtag is guaranteed to be unique right so we can use a hash set to do the job so arrays as list and then we'll just do response split based on this empty and based on this empty string right uh space oh no not empty string it's called space yes so we just split the response into every single word and then we assign them into a hash set to deduplicate that's what this does with this we'll just go through every single word in this response strings right so now what we will do is since this is this set is containing all of the potential popularity of every single feature right so or just to go through this map so if map contains key which is string and then what we'll do we'll just update this one right we'll update count map account map put uh put string up count map put what are we going to put we'll put this one this is the feature it could get all default because this feature might exist or it might not exist if it's not exist we'll just assign 0 to it otherwise we'll just increment it by one with this step we have built this count map which gives us all of the features popularity right so after this is done then we can start building our priority queue right already yeah i think that's correct note if it's type is node i'll just call it heap new let me copy this new priority queue and so here how do we solve this priority queue so first we'll check if its frequency is not equal to b's frequency how come this one is not honored maybe i need to make it public it should autocomplete right so if frequency like popularity is not equal we'll just use the most the more popular so we'll use b frequency minus a frequency however the r equal will use its original index we'll use a's index minus b's index right so that we use the first index the feature that has and smaller a smaller index that will be appearing in the result list first so all right now we can go through this feature account map key set now we'll just build the node objects into this heap keep offering a new node first is the index so how do we get the index we'll get a map get feature this one will give us the index and then frequency will get it from count map get featured and then the word is just feature itself right so for comma then the word is just feature itself so for commap i think we need get all default because it's possible that like there is a feature that's not popular at all there is it doesn't appear in any of the responses after we uh parsing the string right so get our default zero otherwise if we get a very unpopular uh feature we might not have any hits right so otherwise we will throw exceptions now okay now we can initialize the result new string the size of the result is just a heap size right and then we just pop everything off is empty while it's not empty it will just pop everything off uh rinse out oops i need one more index result uh assign this hip pull and he pull it's going to give us a note so after we do he pull we'll just get a word right and then in the end we'll just return result that's it hopefully it can work let me hit run code to see any errors cannot find symbol in no java all right that's why i can tell something is not correct here all right i think i'm missing the an angle brackets to initialize it okay now that one passed so i got a new one no constructor all right i do need a constructor um public node so the first one is index the second one is into frequency the third one is string word i thought there is a default constructor so i'm mistaken this index is given to index invest frequent i like how to complete a newly code that's so awesome i don't know how to write code without ideas sad word all right so this is the constructor let me hit run more run code one more time all right accept it now let me hit submit all right run answer that's unfortunate so the my output is this and the expected output is this so i'm missing c here what the heck input is oh because yeah i'm still missing this so you see c here it's not popular at all there is no it doesn't appear in any of in any one of these responses but still we need to put c here because it's one of the features although it comes last right so where am i missing this c that is because of what let me take a look how to debug this let me take a look how we can debug this so first i built the map and then this is just an index map and this is the count map account count map and count map here and then i built i initialized a heap object and then i go through oh i don't think i should go through the calendar because calm map is incomplete right i think i should go through this map will give me all of the features all right now let me just copy this one and rerun this one it's going to be fun oops we run this one see if it can be accepted all right it's accepted yeah i think the issue is this let me see if it can be accepted all right it's truly accepted so yeah so this one i should go through this map because this is an index map it's basically a mapping of the entire features so that i don't miss any features and unpopular features out all right so this is my response to this problem what's it called it's called salt features by popularity and yeah anyway pretty streetful and simple as long as we follow what the problem is asking us to do come up with original data structures priority queue a hash map or even and customize the cost this is my response so of course there are many other responses feel free to comment down below in the description and let me know how you guys approach this problem uh yeah but that's it for this one from my side um i hope you guys enjoyed this video if that is the case please do me a favor and hit the like button that's going to help a lot with the youtube algorithm and also please don't forget to subscribe to my channel as i have accumulated quite a lot of different lead code tutorials or data structures dfs bfs dp whatever you name it and also quite a lot of aws computing uh aws cloud computing certification exams how i passed those and prepared for them so feel free to check them out so hopefully i'll just see you guys in just a few short seconds in my other videos see you guys soon
Sort Features by Popularity
create-sorted-array-through-instructions
You are given a string array `features` where `features[i]` is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users have reported which features they like. You are given a string array `responses`, where each `responses[i]` is a string containing space-separated words. The **popularity** of a feature is the number of `responses[i]` that contain the feature. You want to sort the features in non-increasing order by their popularity. If two features have the same popularity, order them by their original index in `features`. Notice that one response could contain the same feature multiple times; this feature is only counted once in its popularity. Return _the features in sorted order._ **Example 1:** **Input:** features = \[ "cooler ", "lock ", "touch "\], responses = \[ "i like cooler cooler ", "lock touch cool ", "locker like touch "\] **Output:** \[ "touch ", "cooler ", "lock "\] **Explanation:** appearances( "cooler ") = 1, appearances( "lock ") = 1, appearances( "touch ") = 2. Since "cooler " and "lock " both had 1 appearance, "cooler " comes first because "cooler " came first in the features array. **Example 2:** **Input:** features = \[ "a ", "aa ", "b ", "c "\], responses = \[ "a ", "a aa ", "a a a a a ", "b a "\] **Output:** \[ "a ", "aa ", "b ", "c "\] **Constraints:** * `1 <= features.length <= 104` * `1 <= features[i].length <= 10` * `features` contains no duplicates. * `features[i]` consists of lowercase letters. * `1 <= responses.length <= 102` * `1 <= responses[i].length <= 103` * `responses[i]` consists of lowercase letters and spaces. * `responses[i]` contains no two consecutive spaces. * `responses[i]` has no leading or trailing spaces.
This problem is closely related to finding the number of inversions in an array if i know the position in which i will insert the i-th element in I can find the minimum cost to insert it
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
Hard
2280,2319
525
hey everyone welcome back and let's write some more neat code today so today let's solve the problem contiguous array we're given a binary array of nums meaning it just consists of zero and one in the input array and we want to return the maximum length of a continuous subarray with an equal number of zeros and ones thinking about subarrays the immediate thing that I personally think of is how many subarrays does an array of size n have it has n squ subarrays so something like this where let's say this is the input we have a subarray here basically we have n subarrays starting with the first element then we have roughly n subarrays starting with the second element and etc so it's going to be N squared if we want to check every single subarray so this is kind of our Benchmark any solution we get should be better than an N squ solution if we can find one with this type of problem what I immediately try to do to optimize it is try something like maybe a sliding window is there a pattern here where we can intelligently kind of shift our window and in this case actually there's not and let me tell you why suppose we have this input array we're counting the number of zeros and the number of ones when we start we have one and then we get two ones and then we get three ones by the time we're over here obviously the number is not equal yet now we get to a point where we have a zero and then we get a second zero at this point even though the number of these is actually not equal yet there actually are a couple valid Solutions first of all this is what we've seen so far but this is a valid solution it's of size two this is a valid solution it's of size four this is our result so far but if we were to try to do this with the sliding window you tell me how do we know if we should try to shift our window how do we know if we should chop this guy and then shift our pointer over here cuz that is a possibility but the other possibility is if we can somehow see into the future we say that actually leave the pointer over there because we know eventually there's going to be another zero over here and then the size of the window becomes six so the fact that we don't know which choice to make is going to mean that if we try to do it that way it's going to end up recursive and then that's going to end up being much worse than an N squ solution so sliding window isn't really possible here that's not a horrible thing because we can kind of use the lessons that we just learned here to try to find a better solution a possible naive approach a possible maybe even you could call it a greedy approach would be to always start at the beginning keep track of zeros and ones and once they're equal then we know that we have a valid window but that's not always going to be the case what I'm saying is that the result isn't always going to start at the beginning of the array so changing the example a little bit this is the result here this is the window and it does not start at the beginning I guess my question is maybe the general approach that we do is because what we're kind of looking for at this point we know we have an N squ solution so really we're looking for a linear time solution probably there isn't going to be an N log n solution for like this type of problem so let's focus on looking for a linear time solution generally my thought process with this is the ending point we want to consider what's the longest subarray ending at this element what is the longest subarray ending at this element and every single element and we should be able to do that for any particular element in constant time because we're going to have to do it for n elements so if we do it in constant time then we have a linear solution okay so that's the high level but how exactly do we do this how do we figure out that the longest subray ending at this element happens to be this how do we know it's not this for example and what about this guy how do we know what's the longest subrate ending here how do we know it's not this or it's not this it happens to be this one in particular well I'll tell you exactly why first of all we're going to use a lot of what we already talked about we're going to keep track of the number of zeros and ones by the time we get here we know the number of zeros is two we know the number of ones is three if they were exactly equal then that's great that's easy but this time they happen to not be exactly equal if they were exactly equal like for example in this case where we have three zeros and three ones this is the total number of zeros and ones throughout the whole subay by the time that we get here so if that's the case and these happen to be equal then that's great this is the easy part but when they're not equal like in this case this is where things get more interesting cuz we know for sure that we cannot start at the beginning of the array but at the same time do you kind of notice something here we have two zeros and three ones if only there was a way for us to know where the first one is that it happens to be over here and if only there was a way for us to know that by removing this we end up with an equal number of zeros and one ones and this is the valid result and if only there was a way to do this all in constant time now this example is pretty simple because what we can do is just remove a single element from the beginning of the array but it might not always be that simple we could have like a bunch of changing elements and the counts could be really skewed we could have five zeros and three ones and at that point we are looking to remove two zeros from the beginning of the array and I guess just to make this example a line up with this one let me correct this real quick for example this more complicated one we have five zeros and three ones like by the time what we get here we're trying to remove two of the zeros so that the counts are equal but there's no guarantee that we start with two zeros that would be very clean and easy but there's no guarantee of that they could be ones they could be zeros they could be mix and matching so instead of saying that what we're trying to do is remove zeros what we do is something a bit more intelligent it's not that we're trying to remove exactly two zeros from here that's not what we're trying to do actually we are trying to remove a prefix of this array such that by removing that prefix we end up with an equal number of zeros and an equal number of ones and not only that but we want this prefix to be as small as possible like the minimum prefix that we need to remove to make the counts equal so that's what we're trying to do now that you really understand exactly what we're trying to do we can actually approach how we're going to do that continuing with this complex example I just want to tell you that there isn't really a prefix in this case right that'll make the counts equal if this was five like there just isn't a prefix you can try everyone and that won't happen so let's go to the more simple example and talk about why that is I'm going to use a hashmap here and let me tell you why when we want to remove a prefix however large it happens to be what we're saying is we want that prefix to have an extra one we don't care how many ones it has we don't care how many zeros it has it just needs to have an extra one so in this case this is that prefix it has exactly one occurrence of one and it has exactly zero occurrences of zero given this if we remove this prefix we don't change the number of zeros but we change the number of ones to be two and that's perfect that's exactly what we wanted knowing this knowing that it's the difference that we care about how can we work backwards from here to the solution let me tell you as we are iterating over this input array not only are we going to keep track of the total number of zeros and ones at every index we are going to take the difference between the number of ones and the number of zeros and then map that to the index just to review we're mapping the difference in the counts to the index for every position we're going to kind of do that so first here we'll have 1 one and 0 so we'll say 1 minus 0 is going to map to the index Z what this means is that the First subarray with a difference of one and the difference means the number of ones minus zeros ends at index zero and so that's just telling us that this subarray is the smallest subarray starting from the beginning it's the smallest prefix where we have a surplus of one ones in the future if we were to see another subarray I suppose like this was the array like this is also a surplus of a single one if we have 1 zero and one but we wouldn't want to overwrite this to be one actually maps to index 2 because this subarray ends at index 2 we would not want to overwrite that because we want the smallest such subarray we don't want a bigger subarray if we don't need it that's pretty much all there is to the hashmap approach we'll do that for the others as well so here two would map to index one three would map to index two because there's a surplus of three ones and then here we'd get to surplus of two ones so we don't overwrite this and here we'd get to a surplus of one and we don't overwrite this but at this point what we would say is okay we have three 1es and two zeros therefore the number of extra ones is 3 minus 2 is equal to postive 1 okay where does that subarray lie what is the smallest subarray if it even exists it might not exist if it does it's over here it ends at index0 okay index0 is here so this is the subrate this is the one that we're trying to remove so right now we are at index four and this ended at index zero so therefore all we do is take four minus 0 and that tells us the size of this subay that is the logic behind this problem just to quickly show you another example before we even get to the ending over here we would probably be over here of course at this point the number of zeros would actually be one the number of ones would be three again we'll take the difference 3 - 1 is going to equal the difference 3 - 1 is going to equal the difference 3 - 1 is going to equal to two Okay let's do a look up in our hashmap and it's over here right the diff is two and the index is one so the subarray ending here has a surplus of two ones and that's what we're trying to remove cuz once we do that look at this look at it is the exact subray that we want now this one is of size two the other one that we just saw was of size four so of course this would be the result but again just wanted to kind of walk through that clearly the time complexity of this approach is going to be o of n just iterating over the input and O of n for the memory as well cuz we are having a hashmap here okay let's code it up usually when I solve these problems I take notes like this I don't know how helpful these types of notes are for you guys I can include them in the videos if you do want to I don't know how understandable these are but it usually helps me to kind of organize my thoughts we are going to count number of zeros and ones initially both of them are going to be zero we will have a result and that will initially be zero that's what we're going to return that's the max length we'll also have that hashmap that I talked about I guess I'll call it diff index maybe there's a better name for it but basically what it's going to do is count the diff it's going to map the diff to the ending index of the subarray and the way we're going to calculate the diff is going to take the count of ones and subtract the count of zero you could do it the other way if you want to it doesn't really make a difference just got to be consistent about it though now let's iterate over the input let's say for n in nums and it turns out that we're actually going to need the index as well cuz that's kind of what we're mapping it to so let's do that at the beginning enumerate this so that we can get the index end the number at the same time so now what we're going to do is say if n is equal to zero let's increment the number of zeros and if n is equal to one let's increment the number of ones before we go further I do want to quickly mention that you notice we're keeping track of the ones and zeros but we're not really using both of these very much like we're not using them individually we're only using them kind of together so if you really wanted to you could actually just have a single variable for both of these perhaps with ones you could increment that variable and with zeros you could decrement that variable but for Simplicity I'm going to kind of keep it like this I think being explicit is probably more helpful for beginners but let me know if you'd rather me show the other solution but now let's check something let's first Calculate 1 - 0 something let's first Calculate 1 - 0 something let's first Calculate 1 - 0 and what we want to know is if this is not already in the hashmap let's put it in the hashmap because we only want the first one so if this is not in diff index let's add it to diff index and we will map it to the last index of course okay now there's a couple things I mentioned earlier that there's kind of two cases the first case is if they're equal if one is equal to zero the counts are equal and that's easy because we know at that point the result is just going to be 1 + 0 because we know this going to be 1 + 0 because we know this going to be 1 + 0 because we know this is definitely the longest subarray that we've seen at this point because it starts literally at the beginning of the array but the other case maybe that's not true then we want to know so I'm going to make this an else if we want to know does that difference 1us 0 is it already in diff index and that's because if it is then we can find the last index that it curred at and then subtract it from I and then we'll get the size of our window then you kind of realize if you just like glance up at the code that we don't really need the else if here because we literally did that here it must be inserted by the time we get here we don't even need the else if we'll just change this to an else so we're guaranteed that this diff exists in the hashmap then what we're going to do is get the index of it I'll just call that this and then we'll say diff index get that Target diff which is just 1 - 0 that Target diff which is just 1 - 0 that Target diff which is just 1 - 0 then to get the size of the window let me just make sure all the code is visible we're going to set the result now we're going to set it equal to the maximum because at this point we're not guaranteed that this is the largest window like we were up here so here we're going to set this to be result or set it to be I minus the index in some cases this might end up being zero because if this was the first time that we're seeing this then we're literally just taking IUS I and that's zero of course but in some cases it might be a large number this is the entire code let's run it to make sure that it works as you can see on the left yes it does if you're preparing for coding interviews check out NE code. thanks for watching and I'll see you soon
Contiguous Array
contiguous-array
Given a binary array `nums`, return _the maximum length of a contiguous subarray with an equal number of_ `0` _and_ `1`. **Example 1:** **Input:** nums = \[0,1\] **Output:** 2 **Explanation:** \[0, 1\] is the longest contiguous subarray with an equal number of 0 and 1. **Example 2:** **Input:** nums = \[0,1,0\] **Output:** 2 **Explanation:** \[0, 1\] (or \[1, 0\]) is a longest contiguous subarray with equal number of 0 and 1. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`.
null
Array,Hash Table,Prefix Sum
Medium
325
1,710
hello and welcome back to the cracking Fang YouTube channel today we're going to be solving lead code problem 1710 maximum units on a truck we are assigned to put some amount of boxes onto one truck you are given a 2G array box types or box types of I contains two elements number of boxes and number of units per box the number of boxes is the number of boxes for each type and the number of box units per box is the number of units in each box self-explanatory self-explanatory self-explanatory you are also given an integer truck size which is the maximum number of boxes that can be put onto the truck you can choose any boxes to put on the truck as long as the number of boxes does not exceed truck size return the maximum total number of units that can be put on the truck okay so let's look at a basic example here where we're given um you know we have uh one box um here with three units inside of it we have two boxes with two units inside of it and we have three boxes with uh one unit inside of it so and we see that we have a truck size of four so what is the maximum number of units that we want to put on here so obviously we want to be maximizing the number of units so we want to go first for the boxes that have the largest amount of um units in them right because obviously we want to load up as much as possible so we can see that we have one box here that actually has uh three which is the largest one so we're gonna take one of those boxes and actually that will exhaust this entire box so we'll have three units that we just took now we have to choose from these two boxes so obviously this box here has two units per box and this one only has one so we want to use the one that has more units per box so we're going to take one of those um that we have because we have two boxes of that have two units in them so we're gonna take one box here and we still have budget so we're going to take another one we're actually going to exhaust our budget here and then what we need to do is simply well we have one uh box left because we've taken three so far we have a maximum of four and our only thing is only option left is just take one of these three that has a unit of one so we can only take one from the last box so three plus two plus one that is going to be eight so that is the maximum number that we can get here so that is a basic example let's wipe away some of this text and think about how we can actually solve this it's a relatively simple algorithm so the way that we want to solve this is actually relatively simple what we want to do is we want to basically figure out for each box uh how you know the counts that we have right what we're going to do here is we are basically going to put that information into a heap and we're going to do it a Max Heap right and the reason that we want a Max Heap is because we want to be taking the boxes that have the largest number of units at any time because that's going to give us the best bang for our buck right why take one box that has one unit in it when we could take a box that maybe has 10 units on it remember we're trying to maximize the number of units so we're going to use a Max Heap here and what we're going to put into the max Heap is just we're going to sort on the actual units right so we want to keep like you can't read that uh we're going to put the units into the max Heap and you know we're going to also put the number of boxes we have in there so what we're going to do is at each iteration uh basically while we still have budget for boxes we're gonna pop from the Heap so we're gonna pop from the Heap and we're gonna get some unit and you know box count um from the Heap and we're gonna add the units to our result we're going to add it to the results and then if we still have boxes left from that big one we're actually going to put it back onto the Heap so we're gonna push um push back uh to the Heap and then we're just going to continue until we basically used up all of our uh budget and then that's basically the answer so we're always just going to be taking the maximum number of units that we can because we're going to be prioritizing the boxes with the maximum units and that's essentially it so basically when a box runs out of um you know boxes that we have then we just go on to the next one and we just use all of them uh until we basically use up the entire budget so relatively simple again to recap we're going to build a Max Heap where we store the units and the number of boxes so the Box count and then at each iteration we're just going to pop uh from the top of the Heap get the unit and the Box count we're going to add the unit to the result and we're going to put if the Box count is greater than zero we're actually going to put it back to the Heap because we can still use it right because it might still be the largest number of boxes that we have so uh yeah that's basically it let's now go to the code editor and type this up like I said it's a really easy problem okay let's now code this up so we know that we need a Max Heap here so essentially what we're going to do is we're going to build the Heap and let's do it so we're going to say minus units and box count and where are we going to get these variables from remember that it comes from box types so we're going to say four box uh count units in box types because remember box types is a you know basically a list of lists where the first element is the Box count and the second element is the units so basically using those values and we're building our Heap here and the reason that we're using negative units here is we're trying to use a Max Heap but the default Heap in Python is actually a Min Heap so to get a Max Heap we're actually going to use negative values to flip it so now we need to actually make our Heap so we're going to say Heap queue dot uh heapify on the Heap because we need to basically transform our list into an actual Heap and the way that we do that is by calling heapify on it so now what we want to do is actually Define our result here so we're going to say Max oops Max units this is going to equal to zero and now what we want to do is we essentially just want to you know go and process while we still have some sort of budget left right so while there's actually still something on the Heap for us to pop and while truck size is actually non-zero what we want to do is actually non-zero what we want to do is actually non-zero what we want to do is we want to say the units and the Box count is we're going to pop from the top of the Heap so we're going to say Heap queue dot heat pop and we're going to pass in our Heap and now what we're going to do is we're going to say if the Box count is actually less than or equal to the truck size then that means that we can actually take all of those um you know boxes right so we're going to say that Max units which is our result we're going to add to our result basically however many units are in the box and however many boxes that we're taking so remember we now we need to get rid of the negative that we applied earlier so we're going to negate it by saying minus units to basically get it back to its original positive form and we're going to multiply the number of units times the number of boxes that we took so times box count so remember that we want to take as many boxes as we can of the ones that have the most units in them and since our box count is less than or equal to truck size we are guaranteed to be able to take all of them so uh we do that and now we need to decrement our truck size because obviously we just took some boxes so we need to decrease our capacity so we're going to say truck size minus equals box count so we're going to subtract the Box count uh so otherwise if the Box count is actually greater than truck size then we can only take however much is left on the truck right we're just going to take the remainder of our budget on this one box because we have more boxes than we actually need so we're just going to take as many as we actually can hold so we're going to say Max units this time plus equals and again we need to negate the negative here so minus units and then this time we're just going to take whatever the remaining truck size is and then we just set truck size equal to zero because obviously we've just now used our budget so in the next iteration of the while loop obviously truck size will now be zero and this while loop will break and therefore we can simply just return our Max units so let's now run this make sure I didn't make any silly mistakes looks good and what happened did it get accepted yes it did Okay cool so what is the time and space complexity here so time uh complexity here so let's do the time capacity so uh we are building a heap so there are how many elements on our Heap so there are n elements in the Heap and you know we have to essentially insert um you know n elements into it right so our Heap size is going to be you know a size n and for each element we need to insert it which is going to take log n time so our time complexity here is actually n log n and then for the space complexity what we have here um is just going to be Big O of n because our Heap needs to store all of the items so it's going to be a big O of n so that is your time and space complexity here relatively straightforward problem um you know if you know your heaps if you know basically this is a greedy problem you're taking as many as you can from the I guess the boxes with most units and that's kind of the approach you have the little twist here is that you need to use the Heap which may or may not be difficult for an easy question but I think it's relatively straightforward to actually solve it once you realize that you do need a heap because it's really not that complicated so hopefully this video helps you hopefully you now have a better understanding of how to use heaps especially using a Min Heap as a Max Heat by applying negative values that's definitely something that you see a lot so it's definitely a good pattern to know otherwise if you enjoyed the video please leave a like and a comment really helps me out with the YouTube algorithm if you want to help the channel grow uh subscription is much appreciated if you'd like to join a Discord community of like-minded people where we talk of like-minded people where we talk of like-minded people where we talk about all things Fang interviewing systems design you can have your resume reviewed you can ask for referrals if that sounds interesting to you can join the Discord Community I'll leave a link in the description below otherwise I'll see you in the next one
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
832
how's anyone guys today we're gonna be going over a problem called flipping an image this is a common league code question and there be questions asked by Google it says given a by a binary matrix a we want to flip the image horizontally and then invert it and return the resulting image to flip an image horizontally means that each row of the image is reversed for example flipping 1 0 horizontally results in 0 1 so we're flipping it like this right so we have an image that's in this state we're flipping it to the state Tim Burton image means that each 0 is replaced by 1 and each one is replaced by 0 for example inverting 0 1 results in 1 0 because we're changing every one to 0 and every 0 to 1 so if we look at the first example here this is our array a to begin with and this is our output and so if we walk through let's just say the first row in the matrix 1 0 first we reverse the row so become 0 1 and then we want to go through that row and we want to flip every 0 to 1 and every one to a 0 so the first year becomes a 1 and the last 2 ones become zeros so once we've flipped the entire array and inverted or sorry flip the entire matrix and inverted the entire matrix we're done so the image has been successfully flipped so all we're really doing when we flip an image horizontally all we're doing is swapping indices of the first thing the last thing the second last thing and the second thing we're just swapping so first thing we had to do is go through the matrix go through each row in the matrix and just swap everything in each row and then what we can do is once we're done doing that we could basically just look through the matrix and just say are you a zero become one are you a one become a zero so I don't think really there's like a more optimal way to do this kind of problem it's pretty straightforward I feel like it's kind of asked in a confusing way especially if they didn't tell you what flipping horizontally meant necessarily you just kind of had to figure it out but I think that's the general approach you want to take so let's start writing the code so again we're going through all the rows in the matrix we're swapping everything in a row lasting swaps are the first thing second thing swaps with the second last thing and so on and so forth and then we're just going to ask for that same room is this thing a 0 becoming one this is a single one become a zero so let's do that so we want a loop that's going to go through our entire matrix right so we'll say for inside equals zero well I is less than a dot length I plus and now we said for the current rather Amin we want to do our swapping so we're gonna use two pointers I or sorry J and K in this case because you already have a nice we'll say in J equals zero in K equals a of length minus one and a of I dot length minus one will make sure that we start at our last index and not out of bounds of it so now we'll just say wow J is less than K meaning like wow these two pointers haven't met in the middle we still have elements to swap so we'll store the first thing so we'll say int temp equals a of I J and now that we've stored age I J we can set a of IJ equal to the other thing so a of IJ is going to be equal to a of I K because that's our pointer towards the back of the current row and then we can set a of I k equal to our temporary variable and we need to remember to increment J and D Kroenke every iteration so once this loop is finished we have successfully swapped everything in the row that we're on so now the only thing that's left to do is go through the same row and change every 0 to 1 every one to a zero so let's do that quickly so we'll just have for int actually we could just reuse a variable we could just say like J equals 0 again J is less than a of I dot length J plus and we're gonna set a of IJ right I is a current row and the matrix and J will be the current column and we just want to iterate through this row and we're gonna set it equal to the opposite of what it is right so we'll ask is a of IJ equal to a 1 question mark if that is the case we want to set it to a 0 sorry gonna set to 0 otherwise we want to set it to a 1 so if a of IJ is a 1 it becomes a 0 otherwise if a of IJ is a 0 it becomes a 1 and that should actually invert the row they were on and so now once this loop finishes our row will be inverted so I think all of our work is done so all we have to do now is return the resulting a that we've changed so again this loop is going through the entire matrix rows all the rows in the matrix this first loop here is just going to swap everything in the current row so that's flipping a horizontality and then the finally all we have to do is actually invert the value so this will go through this loop here and this will say is this a 1 changing to 0 this is a 0 turn it so long so once you return a here that should be the resulting image awesome and it is so guys that's how to solve flipping an image in Java this is a common questions asked by Google you guys have any questions you guys won't miss all be sure to leave them in the comments this was helpful you want to help me be sure to share this video with anyone who might need to see it alright guys good luck on interviews and I'll see you next time
Flipping an Image
binary-tree-pruning
Given an `n x n` binary matrix `image`, flip the image **horizontally**, then invert it, and return _the resulting image_. To flip an image horizontally means that each row of the image is reversed. * For example, flipping `[1,1,0]` horizontally results in `[0,1,1]`. To invert an image means that each `0` is replaced by `1`, and each `1` is replaced by `0`. * For example, inverting `[0,1,1]` results in `[1,0,0]`. **Example 1:** **Input:** image = \[\[1,1,0\],\[1,0,1\],\[0,0,0\]\] **Output:** \[\[1,0,0\],\[0,1,0\],\[1,1,1\]\] **Explanation:** First reverse each row: \[\[0,1,1\],\[1,0,1\],\[0,0,0\]\]. Then, invert the image: \[\[1,0,0\],\[0,1,0\],\[1,1,1\]\] **Example 2:** **Input:** image = \[\[1,1,0,0\],\[1,0,0,1\],\[0,1,1,1\],\[1,0,1,0\]\] **Output:** \[\[1,1,0,0\],\[0,1,1,0\],\[0,0,0,1\],\[1,0,1,0\]\] **Explanation:** First reverse each row: \[\[0,0,1,1\],\[1,0,0,1\],\[1,1,1,0\],\[0,1,0,1\]\]. Then invert the image: \[\[1,1,0,0\],\[0,1,1,0\],\[0,0,0,1\],\[1,0,1,0\]\] **Constraints:** * `n == image.length` * `n == image[i].length` * `1 <= n <= 20` * `images[i][j]` is either `0` or `1`.
null
Tree,Depth-First Search,Binary Tree
Medium
null
1,732
hello guys welcome back to my channel and today we are going to solve a new liquid question that is find the highest altitude the question says there is a biker going on a road trip the road trip consists of n plus one consisting uh points at different altitudes the bikers start to slip 1.0 with an altitude start to slip 1.0 with an altitude start to slip 1.0 with an altitude equals zero you are given an integer array gain of length n where n again I is at net length in net gain in altitude between 0.1 and point and one plus one between 0.1 and point and one plus one between 0.1 and point and one plus one for all 0 to 0 is less than I and I is less than n written the highest altitude of a point okay so uh before starting this question guys please do subscribe to the channel hit the like button and press the Bell icon button so with that you can get the regular update from the channel so if the question says actually let me explain it with you with the example here the question says um the question says here is uh we will be given an array like here because again so in which we will be we have to return the sum of it to the next way to the next element and then we have written the highest value and first of all we have to put 0 at the zeroth index so let me explain it to you what I am saying with an example here so if you see here first element would be zero then we will plus minus 5 that would give us What minus 4 minus Pi by minus 5 x t and then again next thing we will be doing here is minus 5 next element is R minus 4 uh sorry it's four plus four so it is equity uh minus four let me check whether okay so it is one XP so one we would that would give us minus four and then minus 4 next element are we are having is here so this is one okay so we have added one now we have uh four so minus 4 plus 5 will be given 1 and then 1 plus 0 will give us 1 and then minus 7 sorry 1 plus minus 7 will give us minus 6 so this is the values we are getting minus 4 9 minus 5 minus 4 1 6 so this is the value of the result we are getting here so let me explain to you again what actually we will be doing here is so first of all we will be having a value 0 at 0th index in our result array and then we will be adding the elements of it with the previous element so if you see here is uh if we add 0 plus with minus 5 we will get a minus five then minus five plus one we're getting one and four minus four plus four five we will be getting 1 and 1 plus 0 will be writing one and one plus minus seven which is equal is equals to minus six so you can see you have added these elements from the previous element and then we will got a new array that is 4 minus 10 minus four uh one minus six so now what we will what we have to do we have to return the maximum numbers if you see here the maximum number here is Max num is one in this example you can see that the next number is one so for that we have to write the code saying that starting with an empty array in which I will be only putting zero then I will be creating a low for I in range from 0 to length of okay so I will be creating a loop from uh of a value I from 0 to length Okay again then I will be creating a new variable in which I will be saying that result I Plus V and I okay so result I plus gain I and then what I have done here I am saying that uh the result value over here would be first I okay here it would be 0 then again I would be uh this value minus 5 similarly it will go again and then we will be getting all thing here so we will be just appending this thing here SL Dot come in them okay so what we have got here is we will be if we return this thing here so we'll be getting 5 minus 4 my 1 6 in the new array that is result okay so actually so we don't have to we do not have to return the array we have to also written the Max return Max result and now if we run the code okay so we can see you can see that we have got our answer let me check it with one multiple uh test cases so you can see that we have we do whatever our answer so it was all in the question guys and it was a quite reasoning uh about how to create such thing where we can add the number with the previous number so here the logic where we can create a variable inside a loop in which we will be just adding the number uh from previous and the next and then we will we have just appended it in the uh our result array so and then we have at the end result the maximum value here so maximum value is 1 and this was all on the all in the question guys hope you have liked the video please do subscribe to the channel and hit the like button thank you guys for watching the video see you next time
Find the Highest Altitude
minimum-one-bit-operations-to-make-integers-zero
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._ **Example 1:** **Input:** gain = \[-5,1,5,0,-7\] **Output:** 1 **Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1. **Example 2:** **Input:** gain = \[-4,-3,-2,-1,4,3,2\] **Output:** 0 **Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0. **Constraints:** * `n == gain.length` * `1 <= n <= 100` * `-100 <= gain[i] <= 100`
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
Dynamic Programming,Bit Manipulation,Memoization
Hard
2119
1,171
guys welcome back to our daily lead code Challenge Series and today's question is a really mind Buster remove zero some consecutive notes from link list it's a medium one but it's really has got some really pick twixs yeah it's going to bust your mind it took me so much time to debug my own code yeah seriously so we'll just see the question we have been given a head of a link list and then link list is like that one then two and then one then two then minus 3 then three then one so the main thing is uh we need to remove zero some consecutive notes now if you see 1 + 2 consecutive notes now if you see 1 + 2 consecutive notes now if you see 1 + 2 is 3 and 3 + - 3 is 0 so we just need to is 3 and 3 + - 3 is 0 so we just need to is 3 and 3 + - 3 is 0 so we just need to return 3 1 or we can also remove - 3 + 3 return 3 1 or we can also remove - 3 + 3 return 3 1 or we can also remove - 3 + 3 is zero uh or 1 2 and 1 like that so if you have already done this question for arrays then you will think of using Maps like uh when we used to do 1 2 3 1 2 Min - 3 and 1 we used to do 1 2 3 1 2 Min - 3 and 1 we used to do 1 2 3 1 2 Min - 3 and 1 we used to do this for arrays now what there we need to do we used to uh create a prefix sum 1 3 Z and three and one 1 3 0 and after that three and four yeah and we need to store these in our map yeah so how we used to do it we used to create a map and suppose we are on the first one so I will create map and initially there will be zero which will lead me to zero then what I used to have is this one now mp1 I'm getting on one now I'll Do MP3 I'm getting on two right now I'll do mp uh zero which is the sum which I'm getting again so when I'm getting this Zero Sum then I what I need to do is I need to go back so from here till here we have got zero so we can directly remove it and we can move ahead so this is the main concept of it I guess most of you would have done otherwise I'll drop a link in the comments as well so we'll just see we'll keep on traversing see one is the sum now three is the sum and now zero so zero has come again because zero we used to take initially that it is already there so zero has come so we'll remove this part and then we'll start from here again three and four then there's no uh repeating prefix sum but in case of link list this is going to be bit uh hard so what we'll do in case of Link list We'll add a dummy node here zero and we'll take our map of uh integer to our node which will take zero to our this node list node zero the first one right so then we'll keep on doing the sum so first one I'll get one and I'll put list node one this one then I'll get three sum I'll put list node two to it this one and then I'll get M I'll again get perix sum as zero when I reach here and I have already got zero so from 0o till here this will be removed in actual from in link list case of view after zero is next till this point it will be removed so we'll remove it and we'll Point our zero to next of our current that is three and one and we'll remove these entries from our map except the 01 so we'll do it like MP3 uh again we have got this sum as three and we'll put list node three now these one will not exist these two not exist same for this not and now we'll get MP4 so this doesn't repeat so this will be our final answer so we just code it out so what I'll do I'll just take one dummy node list node dummy which is going to be my new list node zero and dummy will point to my head dumy is next and as a matter of fact our result would be also dummy. next because this is just a dummy note the next one would be a real answer and what we'll do is uh we'll take one hash map or direct map integer to our list node and this will be our map new hash map and we'll just insert this mp. putut zero and this is going to be a dummy dumy node is going to be there and now what else we can do I'll take one in prefix sum which is our zero so we have already inserted Dy to our map now what I'll do I'll just uh loop over while head is not equal to null and what else we can do okay yeah so what we'll do we'll just keep on adding to prefix sum plus equal to my add. well right I've got this value now I'll check if I have uh if MP do contains key this prefix sum so that means I've already got it somewhere behind so I need to erase those values else I'll just put it mp. putut and prefix sum and head that's it and I'll just do head is head. next right so now we have got that value earlier on like if you see the example of here when prefix sum became zero so we have already got zero here in our map so what we'll do we'll First grab this node which is going to be suppose our list node start and this is going to be our we'll say head not head yeah it is going to be our not head but it is going to be mp. getet prefix sum now I'll get one more see this start so this zero is our start now right so zero has to be there still we only need to remove from one so what I'll do is list not temp equal to start and while temp is not equal to our head again yeah like this I need to so one is my Temp and so this one is my temp and this will Loop over until it comes to minus three right currently because I'm on minus 3 so while temp is not equal to head and I'll just do temp is temp. next actually temp is also I just missed one thing temp is also on my zero yeah so now my temp will go from 1 2 and minus 3 like that and I'll just take one more sum is going to be my zero for now or I'll take prefix sum uh yeah so what we'll do is see what the concept of sum is what we need to do is we need to remove these uh values from our map because now these are being removed right these are being removed so if they are being removed so I will remove these values right so I will remove these values so I think we'll need to start our sum from zero yeah so what I'll do is sum plus is temp. well now I can just remove mp. remove and sum now there's one more thing to it that's really important here and which is uh if you closely observe uh which is uh temp I suppose it is T So temp will reach my one I'll add it I'll remove it temp will reach my two I'll add it I'll remove it temp will reach my minus three I'll add it but I can't remove it because when temp is at three my sum become zero and zero I can't remove zero has to be there so I'll put one condition remove has to be done if temp is not equal to head if it is on last one don't remove some yeah this is how it's going to work so I'll just try to run it and we'll check it okay we have got it wrong I'll just verify it once okay yeah so we have not updated our list the actual one so now we need to update it like this was the start now start should point to three and what is three now start. nextt should be our temp. nextt right should be our temp. nextt or you can also say head. nextt that is one and the same now we'll just run it once boom works fine I'll just submit it okay we've got it wrong uh let me just verify it once we'll see this as I've told you I've been I've spent around like two three hours on this question this is really had Buster yeah okay we'll see what the issue is okay I think I've got the issue yeah this has to be prefix Su and I'll tell you why yeah let me just submit it and we'll get back to this point yeah this works fine so now why this has to be prefix sum is suppose uh instead of this I'll just copy it right and we'll come down here this was my list suppose I have something like uh maybe five like that so now you see uh my mp0 is there which is my first node my MP5 is there 0 + 5 which is my node my MP5 is there 0 + 5 which is my node my MP5 is there 0 + 5 which is my second node and I've got MP6 5 + 1 node and I've got MP6 5 + 1 node and I've got MP6 5 + 1 6 so MP6 which is going to be my third node and I've got my MP6 and I've got mp8 6 + 2 which is my fourth mp8 6 + 2 which is my fourth mp8 6 + 2 which is my fourth node and then I've got MP again the sum becomes minus 3 this is my - 3 so 8 - 3 becomes minus 3 this is my - 3 so 8 - 3 becomes minus 3 this is my - 3 so 8 - 3 is so prefix sum becomes again 5 8 - 3 and five I have already again 5 8 - 3 and five I have already again 5 8 - 3 and five I have already got here right so I need to remove from this second node is this one right so after this I need to remove these three right and when I'm removing this I also need to remove the entries of these I mean yeah not the 5 one but these so now if I'll start my sum from zero then it will give me some one some two and it will remove one and two which is not there I need to start my sum from the previous prefix sum that is five which becomes right here that's that is the thing that we are checking so my sum should start from five so that it will remove 5 + 1 five so that it will remove 5 + 1 five so that it will remove 5 + 1 6 removed then it will do 6 + 2 removed then it will do 6 + 2 removed then it will do 6 + 2 8 removed like that so this was the main gist of this question and uh while I was solving it later on after solving it I went through the editorial and I found this really uh this I shouldn't say funny but really interesting solution yeah uh using hashmaps only yeah so what the hashmap says is what they are doing is um we'll take this example or the same one yeah this one only we'll take so what they're doing is they have just put one zero uh and the dummy node is this front and current one is on this front only right so they are doing just prefix sum and they are putting prefix sum and current so what they're doing is yeah we'll show it like that so I'll just uh yeah so where were we so what they've done uh first zero is the first node that is the front this one now MP5 second one is second node MP6 is third node mp8 is our fourth node now this 8 - 3 is mp8 is our fourth node now this 8 - 3 is mp8 is our fourth node now this 8 - 3 is 5 so five is already there and this will become our fifth node like that right and 5 + 3 again 8 node like that right and 5 + 3 again 8 node like that right and 5 + 3 again 8 right so 8 will now become sixth node right and 8 + 1 is 9 so 9 will node right and 8 + 1 is 9 so 9 will node right and 8 + 1 is 9 so 9 will become our seventh node now this is going to node seventh node now this is going to be really interesting how they're framing it so now they have uh turned the prefix sum to zero and current is again on the front and that is the dummy node so now what they have done is I'll just keep on calculating prefix sum currently my prefix sum is zero now 0 + currently my prefix sum is zero now 0 + currently my prefix sum is zero now 0 + 5 it becomes five right and this is my front so it becomes five right and I'll do current. next current do next that is zero after zero what will come prefix sum uh that is the map. get this prefix sum five and so five is coming on Fifth node so zero uh um 1 2 third fourth fifth uh maybe I've got it wrong mp0 is first node second third fourth fifth node maybe I have just made this wrong this whole map I'll just reverifying so my mp0 is the first node MP5 is the second node MP6 is the third node mp8 is the fourth node and MP it's again zero we're getting zero here okay so we are getting uh not zero five here yeah we're getting five here so this will lead to me yeah okay we were on the right track I'll just control Z it yeah we were on the all through the while we were on the right track yeah so prefix sum is 0 + 5 now we'll check five here sum is 0 + 5 now we'll check five here sum is 0 + 5 now we'll check five here five is the fifth node z uh 1 second third fourth fifth now this is the fifth node so we'll take the next of it which is three right we have to take the next one and now current will become the next one so we'll directly come to this one three to this node you see how this is working so now what we'll do is we'll do five and we'll do + 3 = 8 now we'll go to mp8 is my do + 3 = 8 now we'll go to mp8 is my do + 3 = 8 now we'll go to mp8 is my sixth node is first second third fourth fifth sixth node is this so I'll take the next one of it which is the last node 0 3 and 1 boom now we'll do uh we'll go to the next one which is one so now I'll do 8 + next one which is one so now I'll do 8 + next one which is one so now I'll do 8 + 1 that is 9 so I'll go to MP9 which is seventh node is this one and its next is null n so I'll just put here next null and now it will go to the next that is null and it will come out and this will return front. next now this is our front so it will return this so this is a really interesting solution that I found here and we can also discuss one more solution which is provided above uh which is a o Square which is mostly like what they are doing is they're looping uh they're starting from one node like they're starting from zero like that they're starting from zero and uh they'll start and Traverse every node and they'll keep on calculating the sum and they'll see when the sum becomes zero they'll just update the start right and then they'll start from the next one this way they are traversing every node and it's afterwards like that I didn't like it so much as it is in O Square so we need not discuss it but we need to go through the hint if you'll see the hint you'll get to know a lot about this problem convert the link list into an array while you can find a non-empty sub array while you can find a non-empty sub array while you can find a non-empty sub array with some zero erase it convert the array back into a link list yeah so I guess uh there's no need to convert the link list into an array because that creating an array will again take on space and we are already using a hashmap in o space so I guess uh the best solution would be to use this or the one provided in this yeah this one is also pretty good yeah so that's it for this video thank you guys
Remove Zero Sum Consecutive Nodes from Linked List
shortest-path-in-binary-matrix
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of `ListNode` objects.) **Example 1:** **Input:** head = \[1,2,-3,3,1\] **Output:** \[3,1\] **Note:** The answer \[1,2,1\] would also be accepted. **Example 2:** **Input:** head = \[1,2,3,-3,4\] **Output:** \[1,2,4\] **Example 3:** **Input:** head = \[1,2,3,-3,-2\] **Output:** \[1\] **Constraints:** * The given linked list will contain between `1` and `1000` nodes. * Each node in the linked list has `-1000 <= node.val <= 1000`.
Do a breadth first search to find the shortest path.
Array,Breadth-First Search,Matrix
Medium
null
1,688
hello everyone today we're going to continue with our practice so uh the question we're discussing today is lead code 1688 count of matches in tournament okay so let's get straight into the question says that you are given an integer n the number of teams in a tournament that has strange rules right if the current number of teams is even okay just a second yeah so if the current number of teams is even then each team gets paired with another team in this round of the tournament and a total of n by two matches are played okay so from these n by two matches whichever teams win so that means a total of n by two teams advance to the next round right similarly if the current number of teams is odd one team randomly advances in the tournament okay so one team straight away goes to the next round and the rest of them get paired so a total of n minus one by two matches are played and the teams that go into the next round are n minus one by two plus the one team that automatically advance to the next round okay what the question asks is to return the number of matches played in the tournament until a winner is decided so the total number of matches that would be played in the tournament is what we have to return based on these rules okay to understand this better let's look at an example so here n is seven right now seven is odd that means in the first round one of the teams will automatically advance and the rest of the six teams will play matches with each other they'll get paired and play matches okay so the math the number of matches will be three right which is six by two and the total teams that will advance will be three plus the one team that automatically advanced so four okay now in round two since the number of teams is four which is even all of them can get paired with each other so the number of matches will be two and two teams will advance okay now in round three since there are two teams again the number of matches played will be one and finally one team will advance and obviously that will be declared the winner right so the total number of matches that were played were 3 plus 2 plus 1 which is 6 right and that's what the output is okay so that's what we have to do for any given input n in our program okay so let's uh see what kind of an algorithm we can make so that this can be done okay so let's talk about the algorithm now so uh the first thing that we'll do is we'll maintain a variable right called matches so this will basically count the number of matches that have already been played okay that have already been played so when the program is just starting out none of the matches have been played right so uh the initial value of matches in our program should be zero okay and now to develop the algorithm we'll use a flowchart so the first thing written in the flowchart is obviously going to be our input which is n so n is the number of teams that are going to play in the first round of the tournament right but um it's possible that as input n is given to us already as one right so the first thing we should do is check is n equal to one okay if n is equal to one then what should we do we should directly return matches right if n is one initially then we don't have to play any matches right matches is zero so we should just return that variable right but if n isn't one right then what do we do now to decide what we have to do uh if n isn't one we need to first check another thing right so we need to check is n even okay if n is even then we know that the number of matches that are going to be played in this round will be n by 2 directly right so what we can do is matches is equal to matches plus n by 2. so this will increase the number of matches by n by two right because in this round n by two more matches will be played so that's what we should do right and after this what we need to do is change the value of n to the new number of teams remaining right the number of teams that are going to be playing in the next round two so how many is that going to be that's going to be the current value of n divided by 2 right so to do that we should write n is equal to n by 2 make sense after this we should also consider the case if n isn't even right that means if n is odd then how many matches will be played in our question it's given to us right the number of matches that will be played is n minus 1 by 2 because one of the teams will advance automatically so we should add this number to matches and that should be the new value of matches right and after this we should change the number of teams n to the new number of teams that will qualify from these rounds right from these matches so what is that going to be that is going to be one because one of the teams automatically qualifies plus the winners from the matches right so 1 plus n minus 1 by 2 right this is going to be the new value of n okay this is also what's given in the question right n minus 1 by 2 plus 1 right so that's the same thing now after we've done this uh our program isn't going to stay in these two separate branches right once we've made these uh two separate decisions like once we've executed this part of the code or this part of the code based on whether n is even or not our program doesn't need to stay in two branches anymore it can come back to one branch okay because now what i need to do is i need to check again if n is one right i need to do this for both the cases so i'll check again if n is one and if it is one then i'll just return the matches that i've counted till now right and if it isn't one then i'll repeat the same process again so what's going to happen is this arrow is actually going to go back to this step okay this step right and clearly you can see that what this is becoming now is a loop right so this outer arrow that we just made is a loop right and this is n is equal to 1 is the ending condition of the loop which means that while n is not equal to 1 this loop should keep running right and inside this loop we have an if statement right so uh that if statement is just to see if the current value of n is even or odd based on which we have to do two different sets of steps okay after and after we do the correct set of steps we can come back to the same uh process encode and move on okay so that's the algorithm right uh that's it that's all we have to do so uh we can now move on to implementing it okay so the implementation should be fairly easy now that we've discussed the algorithm uh the first step in the algorithm was defining a variable matches and setting it to zero right after this we need to uh start with our loop right so what does our loop say our loop says that while n is not equal to 1 we need to keep running the loop right so we just say while n is not equal to 1 we go into the loop and in the loop the first thing we need to do is uh check if n is even so how do we check if n is even we use the modulo operator right so if n mod 2 is equal to 0 that means n is even right and in the case that n is even we need to increase the value of matches by n by 2 right after doing this we also need to update the value of n to the number of teams that have qualified to the next round right so that is just equal to the original value of n upon 2 right we can use integer division here too that's fine but if n isn't even that means if n is odd then matches will be equal to matches plus n minus one by 2 right and the new number of teams that qualify to the next round is equal to 1 plus n minus 1 by 2 right exactly how we discussed in our algorithm and uh that's it after this we don't have to do anything inside this while loop right all we have to do is go back again and check if this if the number of teams that have qualified is now become one or it's still not one and we have to execute the loop again right now once the number of uh teams once the number of teams left has become one then that means we already have our winner right so all we have to do is return matches which is the number of matches we played to finally reach to a winner so that's it now this code should work let's try to run it to see if we have made any small errors or not so we haven't made any small errors we can try to submit it to see if it's actually correct and it is correct so that's great and that's all for this video thank you for watching and keep practicing
Count of Matches in Tournament
the-most-recent-orders-for-each-product
You are given an integer `n`, the number of teams in a tournament that has strange rules: * If the current number of teams is **even**, each team gets paired with another team. A total of `n / 2` matches are played, and `n / 2` teams advance to the next round. * If the current number of teams is **odd**, one team randomly advances in the tournament, and the rest gets paired. A total of `(n - 1) / 2` matches are played, and `(n - 1) / 2 + 1` teams advance to the next round. Return _the number of matches played in the tournament until a winner is decided._ **Example 1:** **Input:** n = 7 **Output:** 6 **Explanation:** Details of the tournament: - 1st Round: Teams = 7, Matches = 3, and 4 teams advance. - 2nd Round: Teams = 4, Matches = 2, and 2 teams advance. - 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner. Total number of matches = 3 + 2 + 1 = 6. **Example 2:** **Input:** n = 14 **Output:** 13 **Explanation:** Details of the tournament: - 1st Round: Teams = 14, Matches = 7, and 7 teams advance. - 2nd Round: Teams = 7, Matches = 3, and 4 teams advance. - 3rd Round: Teams = 4, Matches = 2, and 2 teams advance. - 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner. Total number of matches = 7 + 3 + 2 + 1 = 13. **Constraints:** * `1 <= n <= 200`
null
Database
Medium
1671,1735
141
Hi welcome you welcome next you do question series and here we are going to attend question number 141 which is linkless cycle meaning you have to detect here whether any cycle is being made in link less, okay what is the meaning of this linked list Let us see whether the cycle is being made or not. One question is very easy, one easy level difficulty question with very super, okay and what is given to you here, you have to give head off and necklace here and you have the link list. What does cyclone mean? What does it mean that cyclone is flinklis? Let's see if you have a link. Okay, I have a link list here and in this link list, I have to determine whether there is a cycle in this link list. What is a cycle? What is a link lace? Linked list. This is a necklace. This is your head here from where your link starts and at the end you have a tap here. Okay in the link list. You don't have a tap here, it gets made into a cycle and you can understand that cycle like this, meaning for now I am making it like this, so you have a cycle here, okay and then it gets made into a complete cycle here. Okay, I have given this shop here as a bicycle but actually what happens here is that it is all a game of address which is a link list box, we have two things in it, first I show you here. In the second one, you can give the address of the link less here, which is your next mode, which is actually your next model, here you give its address, like if someone knows its address, then here you know this box. Where is the next box? Okay, similarly, here you give the address of the next mode here. Similarly, here you give the address of the next note, so here you have to tell whether any one address contains any previous note. Is the address of the person lying there, is it 10006? Is it lying there in any other also? Like it has 1000 in it, so if you have 16 in anyone else, then it will become a complete circle here, okay because now this which is here is Whichever node is yours, it will point to it, so you do this, it will go back, okay, then it will come here, then it will come back, then it will come here, then it becomes a complete cycle of yours, so here they are telling us that You have to detect in which one of the linked lists a cycle is being formed. If a cycle is being formed in the linked list then you have to return True. If a cycle is not being formed in the linked list then you have to return False. This much is less, okay. The question is very easy, the question is very easy, you can detect this thing here, there is an algorithm from the slide algorithm, okay fluid cycle detecting alcohol, okay man, you can check from the algorithm, take a link, cycle is being made in it. Or it is not being made, he had given this concept of slow pointer off here, what do you want to do that you will run two points here, one point will be given to you here, slow pointer will be the second point, your password here is correct, both the points will be given to you from initial position here. But slope and inter will start here, what do you call slow pointer here? Yours here will be incremented by one, meaning it will go to the next note. Children, you will have a fast point here, it will skip one of your notes. It will be your friend, meaning if This slow pointer of yours is here, it has come here, then your fast quant will skip it and go here. Okay, two inters, yours is here at this time and there is a fast point. You stand somewhere here, then yours. Whatever is the slow point, it will come here and the fast quantum will skip it and go to A here. Okay, what will happen after that, your slow pointer will come here and your fast point will skip it and come directly here. At a point A, it will be like this. Both your slow center of fast point to the same element, both your fast pointers will be pointing to the same element and if this happens because in the case of a bicycle it will happen like this, if you make a bicycle then one point on one point will be like this. That both those elements must be pointing to the same element, like I just gave you an example that if your slow pointer is moving slowly, then one is going near each mode, but your fast pointer is skipping each mode. Okay, if you are skipping one note and going straight to the other, then in the cycle, there will be a point on A in such a way that both of them will point to the same note. If this happens, then if this happens then Meaning, there is a cycle in your link list, okay, if it is not so, then there is no cycle, okay, this is the concept, let us understand it in a little code, along with the code, I will give you the diagram. If okay, then it will be a little easier to understand, so what is it here first of all. So you have to check here if your head is null, okay how to handle a few gowns, then here I checked if your head is null then we will return false if your link here is only one element in the list. Or if there is even one element, then what is your role in it because with one element you cannot make a cycle? Okay, you need at least two elements to make a cycle, so what am I checking here in case of that ? Head is there, I am tapping it here, ? Head is there, I am tapping it here, ? Head is there, I am tapping it here I have checked that if even one element in your link is correct, then what you have to check here is that you have to declare two points in what is there. You will have to do this, one will be the slow pointer here, one will be your punch point here, okay, so two, I have declared here, one will be you here, there is the slow point, the second one will be you here, the fast point, okay, now check here my Here for how long do we have to run the Vile loop, as long as there is one thing here, if I show you one thing that is the condition, how is this condition, I am telling you this here, I have a link list here in which I suggest. Here is this thing, okay, I have a link list of three elements here, and one link list for one, I have a link list of support charge elements, okay, I have a link list of four elements, I have two of the elements here. Pointers are slow and 1 minute, I have fast water here, fast point here will skip one note and go straight to another note, then fast quantum, mine will come straight here, okay, fast pointer, mine will come straight here, but in this link. There is no cycle, its next element is null here, so my first check is here, if the next element of fast pointer is equal to null, then it means no one is there, what do you say? There is no cycle if the fast pointer is the next point here because this fast pointer which the fast is pointing to is not null at this time but the next point of the fast pointer has to be set at this time. The key which is your fast pointer, its next should not be equal to your tap, okay, first check, then this will come here, second check and end, okay, one more thing, this was your game of three elements, if you three elements here. If there are two elements then fast will do it, after that fast mine will point to it, okay it will come directly here but the next one of fast is not null here, the next of paste is not null here, so this one which is the condition here is here. In this case, what will happen in this case is that it will come straight here, take this here, straight to the tap, because if this condition is skipped here, then it will come straight here, now it will go straight to the tap here, in this case, it will be fine. And there also I have to break that if your fast is equal to null, that is, here if your fast is not equal then it is okay. What was the first condition that fast should not be next which I explained to you above. If you have fast here, then its next should be here. What is the second condition, if you have more elements here, then its fast which is there will be null, then that too should not be there. If it is not so, it is okay if it is like this. If it is not in the case, then what will you have to do here, put slow here, you will have to put slope in the next, that is, whatever is your slow pointer, you are incrementing it by one, but whatever you have fast influence, you are incrementing it by one. If you want to include two semis here then you will have to put them next to the next one. It is okay if at one point AK it happens that slow and fast get mixed together. It is okay if at one point AK it happens like this. It is said that if the slope and fast meet at your point, then you have to do reflection there. True, if it happens somewhere that it is not found, then you have to do false there. Okay, let's make one or two more diagrams to explain it to you. This is this is fine and this is pointing to this, yours is slow in the starting, this is also fast, both are on here, okay, slow is yours on here, and fast is yours. What will happen in the next case is that the one who is slow will go here but the one who is fast will go here. Okay, you are slow here and fast here. What will happen in the next case that your slow one will go here. What will happen in the next case, the one who is slow will have already arrived here, the one who is fast will have already arrived here. Skipping this, that too here today, now you will see one point. But both the elements of A will be pointing to the same note, so if you have the class cycle that if there is a cycle in it, then take that at the same point of time, they will be pointing to the same note, then from this you can find out that the cycle is being detected. There is a concept of slow pointer and fast pointer and this can also happen, meaning it is not that here let's elements come here, I have taken four elements in this, is that in this, it can also happen that 100 questions, so this is punch here. Six or 20, 25, any number of rounds can be put in this circle. Both the pass point and the slow pointer can put any number of rounds before pointing a mode among themselves. It is okay but it will be the method, let's see for a second. Here, if I run it as suggested, it will run absolutely successfully. After running it for a second, you will see that it is accepted here, submit it, and next has to be written first and that means you will get the fast next here later. You will have to check because if your fast is null then it is obvious that the next fast will also be null, it means fast will connect, next tap if nothing happens, then in this case there was a break there, then you look here, it is random. Whatever it is, it will be faster than zero milli second, it will be 100% faster than zero milli second, it will be 100% faster than zero milli second, it will be 100% online submission, then tell me in the comments, thanks, soch watching by.
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
253
hey everyone welcome back and let's write some more neat code today so today let's solve meeting rooms two and just like meeting rooms one we're going to solve this problem on the website called lint code because this is a premium leak code problem so if you want to be able to solve it for free you can use for free you can use for free you can use so it's pretty similar to meeting rooms one we are given a list of meeting times each meeting time is an object and it has two variables it has a start time and it has an end time and the end time is always going to come after the start time that's pretty intuitive and we want to know what's the minimum number of conference rooms required for all of these meetings now what they actually mean by conference rooms is basically what is the maximum number of overlapping meetings at any given point in time so for example in this input we have a meeting that starts at 0 ends at 30. another meeting that starts at 5 ends at 10 and then another meeting that starts at 15 and ends at 20. and we would need two meeting rooms for this problem because we are gonna have two overlapping meetings so if we had one room where the zero to thirty meeting is going on the five to 10 meeting is basically going to be going on during the same time as this one so we're going to need a second meeting room for this and we also have another meeting 15 to 20. now it doesn't overlap with this one so technically they can be a part of the same meeting room now we don't actually need to determine what goes in each meeting room we just have to know what's the maximum number of overlapping meetings at any given point in time in this case that happens to be two we are going to be required to sort the input array which is going to take n log n time complexity so this is going to be the time complexity of the algorithm the memory complexity is going to be big o of n i'm going to show you how to do the solution now if you just stare at this like the problem statement and just look at these numbers it's going to be difficult to come up with how to code the solution but as you guys know i like to draw pictures and when you look at the picture it actually becomes pretty easy to figure out how to solve this problem so let's do that so this is kind of how we can visualize those meetings right these are the exact same meetings that we were given in that first example we have one meeting going from 0 to 30 another meeting going from 5 to 10 and another meeting going from 15 to 20. now if we just go from left to right we're gonna see okay well this is the first meeting that starts right it starts at time zero and if we just keep going now we see what's the next point on our grid right well there's another meeting and this is not an end time this is not you know the first meeting isn't ending there just happens to be another meeting that's starting so another meeting just started at time five so what does that tell us that tells us two meetings have started so far but nothing has ended right there's no meeting that's ended yet so at this point in time we're gonna have two meetings going on at the same amount of time so what we're gonna be maintaining is a variable count which tells us at any given point in time what is the number of meetings going on and right now our account is 2 and we're going to end up returning whatever the max value this happened to be so what's the next point on our grid we visited this one now we're looking at this one right okay at time 10 there's an end point this is not a starting value this is an ending value so what does that tell us that tells us a meeting has just ended so what are we going to do with our count we knew we had two meetings going on at the same time over here but now after this point we're only going to have one meeting going on right like look at the picture there's only one meeting going on and it's this first one right zero to 30. so we're going to set the number of meetings going on to one now we're going to look at the next point in order now it happens to be a start time so another meeting just started at time 15 right so once again there are two meetings going on right at this point there's two meetings going on the first one and this second one so once again a meeting started that's going to tell us to increment our count so now we're gonna say two meetings are once again going on and again we're gonna repeat the same process the next point is at 20 this happens to be an end time so that means a meeting is ending right we don't technically even know is it this meeting that's ending or is it this meeting that's ending it doesn't really matter to us all we know is that after this point only one meeting is gonna be going on at any particular time and it's gonna be this one so we're gonna take our count of meetings going on decrement it and now it's gonna be one and last but not least we're going to go to the last point in our grid and it's also a end time obviously the last point is always going to be a end time for a meeting so that means another meeting is stopping after that point there's only going to be you know zero meetings going on so therefore we can take our count decrement it all the way down to zero now we notice that what was the max value that count happened to be well the max it ever reached was two so therefore we're going to return two as our result two meeting rooms is enough to contain all of these meetings so let me show you quickly how we're actually going to be sorting these points and how we're going to be able to iterate through each point in order regardless of if it's a start time for a meeting or if it's an end time for a meeting so i'm going to slightly change the example in this case so just by looking at the picture what do you think the meeting room's number would be for this problem well you see over here there's gonna be one meeting going on here there's gonna be two meetings here there's gonna be one meeting but look at this point at point time equals 10 clearly there's three meetings going on at this time or at least three meetings have a 10 value included in their time interval does that mean that there's going to be three meetings going on well technically the way this problem is defined this meeting would end before this meeting started what i'm saying is these two meetings are non-overlapping so when we are going non-overlapping so when we are going non-overlapping so when we are going through this point if we ever have a tie meaning if we ever have two points with the exact same value what we're gonna do is we're always gonna iterate through the end meeting time before we iterate through the start meeting time right notice how this is a end time this is a start time we're always gonna pick this one if we ever get a tie like this so we're actually going to have two input arrays we're not just going to sort every meeting based on the start time what i'm going to do is i'm going to put all start times in a separate array so 0 5 and 10 are all gonna go in a separate array these are all the start times for any meeting right this way we have them in sorted order and we know okay these are the ones that are start times we can differentiate between a start time and an end time we're also going to put every end time in an array as well in sorted order so we can see the first is 10 next 15 next 30. so now we're going to start this problem off with two pointers we're going to have one pointer at the beginning of start and one pointer at the beginning of end we're always between these two we're always going to pick the minimum value so we are going to maintain a count which tells us the number of meetings that are going on and if the minimum between these two is the start time what we're going to do is we're going to increment the count of meetings going on and then shift our start pointer to the next one and we can see that's the case again right 5 is less than 10 therefore a meeting has to start before this meeting ends so once again we're going to shift our pointer over here and we're going to increment our count by one so the count is now gonna be set to two and now we get to the edge case right we got a tie so a meeting is ending and a meeting is starting remember we are gonna visit the end time if there's a tie first so what we're gonna say now is that okay a meeting has to end before this meeting starts so we're gonna shift our end pointer to the next one if we iterate through an end value that means a meeting just ended therefore we're gonna decrement our count by one so two is decremented by one it's going to be set to one now again we're going to compare these two values 10 and 15. which one is smaller the 10 right so therefore another meeting is starting so we're going to increment our count by one so count is now going to be equal to two and now we don't even have any start times left so technically at this point we're just going to be iterating through the end time so we're literally just going to be decrementing this so we iterate through this decrement this down to one iterate through this decrement this down to zero so technically once we've gotten through all start times we don't even have to iterate through the remaining portion of end times so what we can say is that our max count at any given point it reached was two so therefore we're going to return two so that is basically the algorithm we're going to use and coding it up isn't going to be too difficult yes we are going to have to create two separate arrays start and end and we're going to sort these input arrays so the time complexity is going to be n log n the memory complexity is going to be big o of n that being said let's jump into the code now on lint code so like i said we are going to create a array for all start times in sorted order now i'm sure you know how to do that in your language of choice but in python there's a pretty easy way to do it so we're going to go through for every interval in the list of intervals that we're given now an interval is an object as defined up above it as two member variables start and end so since this arrays start we're going to put every start time of this interval in this input array and don't forget we are going to sort it so and i can do that on the same line just like this we're going to have a similar array for n times basically doing the exact same thing so a sorted input array of i dot n for every interval in the list of intervals now we are going to have a result variable and a count variable so count is just going to be whatever what i basically said it was going to be result is just going to continuously be whatever the max we have reached so far for the count variable and we are also going to have two pointers i'm just going to name them s and e uh they're initially going to be both zero so s is gonna be the position we're at in our start array e is gonna be the position we're at in our end array and i'm basically just going to keep going while s has not reached the end of intervals because we know of course s is going to reach the end before e does because the start times are always before the end times so remember we have two cases if the start if the position that we're at in our start array is less than the position we're at in our end array and the other case would be if the end array was greater than the s than the start array which would be the else case but also if these were equal we're also going to do the else case because if they're equal then we want to make sure we increment our e pointer first so that's exactly what we would do here we would take e increment it by one and to our count decrement it by one the opposite is going to be true up here so here since s is smaller since the start time is smaller we're going to be shifting our s pointer and we're going to be incrementing the count so we do have one additional meeting going on right now that's what we're saying and after every iteration basically we're gonna update our result potentially we always want it to be the maximum that we've reached so far for count so we're gonna just take the max of result and count once that is done that means this loop once this loop is done that means we've finished all of our start times so at that point we can basically return our result because we've ensured that it has reached whatever the maximum it was going to be and with all that we can go ahead and submit it hopefully this works and as you can see it does it's about as efficient as it would get so this is the entire code it's not too bad once you can kind of visualize what is actually going on that's how you can kind of figure out how to put the different points inside of separate input arrays but i think it would be pretty difficult to come up with this on your own in like a very short interview but i hope this was helpful if it was please like and subscribe it supports our channel a lot and i'll hopefully see you pretty soon thanks for watching
Meeting Rooms II
meeting-rooms-ii
Given an array of meeting time intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of conference rooms required_. **Example 1:** **Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\] **Output:** 2 **Example 2:** **Input:** intervals = \[\[7,10\],\[2,4\]\] **Output:** 1 **Constraints:** * `1 <= intervals.length <= 104` * `0 <= starti < endi <= 106`
Think about how we would approach this problem in a very simplistic way. We will allocate rooms to meetings that occur earlier in the day v/s the ones that occur later on, right? If you've figured out that we have to sort the meetings by their start time, the next thing to think about is how do we do the allocation? There are two scenarios possible here for any meeting. Either there is no meeting room available and a new one has to be allocated, or a meeting room has freed up and this meeting can take place there. An important thing to note is that we don't really care which room gets freed up while allocating a room for the current meeting. As long as a room is free, our job is done. We already know the rooms we have allocated till now and we also know when are they due to get free because of the end times of the meetings going on in those rooms. We can simply check the room which is due to get vacated the earliest amongst all the allocated rooms. Following up on the previous hint, we can make use of a min-heap to store the end times of the meetings in various rooms. So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied. If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room.
Array,Two Pointers,Greedy,Sorting,Heap (Priority Queue)
Medium
56,252,452,1184
84
Hi My Name Is This Video In Two See The Question Largest Rectangle In Histogram Guitar Height In The Area Of Largest Intestine Heart Attack Computer Training Report Killer Position In Order To Find Out The Area In Most Popular Rectangle You Have Height Of The End Samridhi Looking Left End Right to find out all the height at least value of the height of doing spice the condition Bluetooth Left satisfy the condition of having height equal to 1 greater than five and so e will continue 22512 Height Dashma Know the formula for you can also Tree That 2 Cows Want To Write The Height Lesson The Current Bar And The First Lesson The Current 1 - 1 - The Current 1 - 1 - The Current 1 - 1 - 1 - 1 Day Picking Up The Phone Student Project Root Cause Analysis For The Growth For Suppose You Neetu On Each And Every Index And Finding Out The Height Greater Than Or Equal To The Current In The Direction Will Give You Time Complexity In Square How Do You Search For The Computer Answer For Left Right Starting Point Industrial Estate Hi Dilvar Hi Could Be Minus One Is That Is The Only in the Fighter Zero Minus One Computer Value From the End and End Spidigo to Check the Condition Match and Another State Highway 39 Do n't Even Listen to Go to the Particular Index and See Weather in Suspicious Condition and Not But Over We See The Titans One Which Is Not Satisfied The Condition For Laptop And With Previous Year Computer O Bhai O My Friend Is Vikram I Plus One In Sadak 5 - 1 Hour Value And Say That My Previous Should Be In Sadak 5 - 1 Hour Value And Say That My Previous Should Be In Sadak 5 - 1 Hour Value And Say That My Previous Should Be Lesson And Height Of 3 Years Greater Than Equal To The Current Height 10 Freedom Fighter In Computer Virana Phone NFC Will Become Maximum of Mind Serial and Height and Width Height Come Fight of Eye Multiplied by the World and Will Become Right of Eye - Laptop Eye -1 Final Year of Eye - Laptop Eye -1 Final Year of Eye - Laptop Eye -1 Final Year After Every Thing Is the Meaning of Culture Perfect Girl Net Transfer All the Test Case This is going to countries in the world is going to be in increasing order not going to elements with it comes decreasing how do we use property and find the area and see the dragon in india 2nd standard height and element formula that we use in The Principle The Right Minus One Thing Right And Left Right Left So Will Start Popping Out From The Set The First Element Foxout Index 36 The Right Left Any Update The Area Of The Fertilizer Right The Height Of The Particular Element And So Where Going To Put Into The Tiger Doesn't Updated Every Pop Out Another Element Right Six Pay Commission And Height 24* 24* 24* 7 Later In Between Subway Update Justin Leeson The Value Of PKC Calculator And Show The Meaning Of Anti And I've Already Riched And Find The Second Year Final Area Required for the Route to Find Out the Largest End in the Program Buddha Vihar Map Area Bluetooth On I Go to the Height of the Height or Going to Process Animation Height of the Top Element Multiplied by the Wild Max Area Becomes the Maximum Utran Serial Sony Plus In Order To The Same Position And Process Decreases Minus Finally Giving Perfect Result Transfer All The Sample Testing OK [ Sample Testing OK Last Point Sudarshan Video Gaye Ho Ki Like De
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
246
although this question is stormy grammatics number so you give me a certain none and then you want to return true if a num is a historic chromatic and then how do you do this it's pretty straightforward so the story chromatic number is the number you looked the same when you rotate 180 so one root is equal to 1 8 is equal to eight zero is equal to zero six is equal to 9 and 9 is equal to six so this is the you know the pattern right so basically we just store into a map and then so restore everything this into the map and then uh basically it will count the what the number from the beginning and the end and to compare if they are the same if they do then just keep moving so let's go to the right let's go to the left and then return false if they are not matched and right so here is the solution so I'm putting the character into my map to the magical to new Hazmat character initial mine how old so I'm putting a key and values my parents are zero comma zero this is the first one comma one and then this is going to be eight comma eight is comma nine comma six so this is how you uh put into the map and then click inside first so before we travel we need to stay next minus one so well I let's equal to J right so we can compare so it's going to be a chart I'm going to say um x equal to number chart at AI y equal to none dot chart at J so if I get this chart in my map which is equal to the Y then I will you know continue right if not then I will just pass but also I only put 0 1 8 6 and 9 into my map as a key if there are you know two uh or you know three uh you know inside my student my right and I will just enforce and this is not a I mean this is not available and then you'll return true and again so uh there should be yeah there should be mines like this the oh man so I initialized my math and yeah so this will be the answer all right so I was asking them later you know thrill of my parents you see but whatever run it submit all right so a little bit update for the solution I can include my high and J sorry increment i decrement j on here because this is the you know I still get a current chart and I include my uh index for the next chart so I'm Gonna Roll It all right so time is space straightforward this is space I would say constant but if you want to keep this as a space definitely the remote I mean there is a small space for space complexity or whatever and this is going to be like all fun I mean it's a number two but it's actually all of them so this is a solution uh there's another solution which is shoulder just copy and paste so if you remember zero one a six nine six so it's actually what six nine six but if you combine in this 6996 into 696 it actually works so just you know still you are I equals zero J equal to length minus one and then you compare are they you know combined together are they inside lists listen if so then you'll continue the next iteration and then if not your return first this is you know in the indication they are not inside the string all right so in this line time and space is you know tonsil right and then time this is what all of a sudden right but when you use the content right actually Traverse list string every single iteration and I would say this is like although you know all of those six nine twelve sometimes so all of 12 every single iteration this is why you have a little bit wrong turn on your solution but I would say it's going to be extremely listen to all of them but yeah so both solution actually doable just pick a favor and if you see a question of a comment I will see you next time
Strobogrammatic Number
strobogrammatic-number
Given a string `num` which represents an integer, return `true` _if_ `num` _is a **strobogrammatic number**_. A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down). **Example 1:** **Input:** num = "69 " **Output:** true **Example 2:** **Input:** num = "88 " **Output:** true **Example 3:** **Input:** num = "962 " **Output:** false **Constraints:** * `1 <= num.length <= 50` * `num` consists of only digits. * `num` does not contain any leading zeros except for zero itself.
null
Hash Table,Two Pointers,String
Easy
247,248,1069
1,827
let's solve lead code 1827 minimum operations to make the a increasing all right so the question goes like this you'll be given an array of integers it could be something like 1 5 3 4 2 two right it could be something like this okay and you're required to make it into and increasing you need to sort uh not sort but you need to make it in uh strictly increasing order an array which is strictly increasing means that would be one 2 uh in this case the output would be one it starts with one so next one cannot be one it has to be two next one can be five after that it needs to be uh six it cannot be less than five next it needs to be seven cannot be less than six it next needs to be8 cannot be less than 7 next needs to be 9 cannot be less than 8 so finally this would be the converted array and how many operations would I need to do this so for example this minus this that was one operation here no operation for the five we can keep as it is three operations for six to go from 3 to 6 so 3 + this 1 is equal four operations 3 + this 1 is equal four operations 3 + this 1 is equal four operations so far 4 + how many operations here so far 4 + how many operations here so far 4 + how many operations here three operations here 7 - 4 so 4 + 3 three operations here 7 - 4 so 4 + 3 three operations here 7 - 4 so 4 + 3 that gives me 7 operations so far how about here 8 - 2 6 operations so 7 about here 8 - 2 6 operations so 7 about here 8 - 2 6 operations so 7 + 7 + 7 + 6 that gives me 13 operations so far here that would be 7 operations to go from 2 to 9 so 13 + 7 gives me 20 go from 2 to 9 so 13 + 7 gives me 20 go from 2 to 9 so 13 + 7 gives me 20 operations so the answer would be 20 operations are required to make it strictly increasing remember the operation that is allowed is only + 1 we could have is allowed is only + 1 we could have is allowed is only + 1 we could have made this uh three in of five and had it been that we had more we would we were allowed more operations are there we were allowed operations like minus one but in this question we are allowed only plus one as an operation so using just plus one how do you convert it so this is the only way so just how we solve this or we can do it programmatically as well so what I'm I going to do is I'm going to take the current start from index one and go till the end and then take the current index okay so for index one what I will do is I'll take the previous index okay I'll first figure out how much I need to add so my ADD quantity would be I'll take the previous index value at previous index minus the value at current index okay + index okay + index okay + one why + one why + one why + one because I just don't need to change this to the previous value I need to take it one more ahead than the previous value so I'll check the difference from current to previous and add one to it so that's the number of operations I'll do on that specific index so this would be how much one right for index one the number of operations would be one okay then for index 2 what about index 2 what would be the amount I need to add so now index one I'll update it to the incremented value right now index 2 would be five okay five is greater than the previous one so I need not do anything okay I can simply leave it as it is so zero operations here then for third one I can to take add the amount the value I need to add to be previous number which is 5 - 3 current number which is 5 - 3 current number which is 5 - 3 current number okay plus 1 and that would be how much 2 + 1 3 so 1 and that would be how much 2 + 1 3 so 1 and that would be how much 2 + 1 3 so I'll be adding three operations okay so this would be 3 + 3 operations okay so this would be 3 + 3 operations okay so this would be 3 + 3 6 similarly here I'll do for four the previous number is six okay for the fourth and the previous number is 6 minus the current value which is 4 + 1 so that would give me 2 + which is 4 + 1 so that would give me 2 + which is 4 + 1 so that would give me 2 + 1 3 again three operations okay three operations and that would make 4 S 7 right similarly for five index 5 the previous value is 7 current value is 2 that gives me 5 + 1 6 me 5 + 1 6 me 5 + 1 6 operations right for index value index six which is the last index how much I need to add I need to also update here so this would be 2 + 6 so this would be 2 + 6 so this would be 2 + 6 8 this would be 8 - 2 gives me 6 + 1 8 this would be 8 - 2 gives me 6 + 1 8 this would be 8 - 2 gives me 6 + 1 gives me 7 so number of operation 7 I'll add 7 to here so that would become N9 right now if you say this is exactly as this and the sum of all this would be the number of operations s that is the answer so 7 + 6 + 3 + 3 + 0 + answer so 7 + 6 + 3 + 3 + 0 + answer so 7 + 6 + 3 + 3 + 0 + 1 let's do it programmatically so I'll take uh variable answer or OPP varations okay it will be initialized with zero then I'll go for I in range from starting from the index one till the end till the last index and I'll check if n previous number i- one is if n previous number i- one is if n previous number i- one is greater or equal to number I number at index I in that case what I'll do is I'll figure out how much I need to add so how much I do I need to add that would be previous number minus current number + 1 okay and number + 1 okay and number + 1 okay and this is also I can call it add AR I can call it uh Ops right current Ops right so I can then add uh first of all add this to current index to make it increasing order right so I'll add Ops to current index and I'll add Ops to overall operations that I'm maintaining right so Ops right and for all these conditions it will do these operations and increase my operations it will keep a total of the operations and finally when the loop is over when I've gone through every number I can return operations let's run and see if this works and that worked for all three cases let's submit it and that worked 81 milliseconds better than 88% of solutions that's how better than 88% of solutions that's how better than 88% of solutions that's how we solve the problem 1 1827 minimum operations to make the array increasing
Minimum Operations to Make the Array Increasing
invalid-tweets
You are given an integer array `nums` (**0-indexed**). In one operation, you can choose an element of the array and increment it by `1`. * For example, if `nums = [1,2,3]`, you can choose to increment `nums[1]` to make `nums = [1,**3**,3]`. Return _the **minimum** number of operations needed to make_ `nums` _**strictly** **increasing**._ An array `nums` is **strictly increasing** if `nums[i] < nums[i+1]` for all `0 <= i < nums.length - 1`. An array of length `1` is trivially strictly increasing. **Example 1:** **Input:** nums = \[1,1,1\] **Output:** 3 **Explanation:** You can do the following operations: 1) Increment nums\[2\], so nums becomes \[1,1,**2**\]. 2) Increment nums\[1\], so nums becomes \[1,**2**,2\]. 3) Increment nums\[2\], so nums becomes \[1,2,**3**\]. **Example 2:** **Input:** nums = \[1,5,2,4,1\] **Output:** 14 **Example 3:** **Input:** nums = \[8\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 5000` * `1 <= nums[i] <= 104`
null
Database
Easy
null
416
Partition Equal Subset Sum: In this problem, Partition Equal Subset Sum: In this problem, Partition Equal Subset Sum: In this problem, we have been given an integer array. We have to divide this array into two subsets in such a way that the sum of the elements of the two subsets is the same. If we move the arrow to this If we are able to divide properly then we have to return true. If we cannot do so then we have to return false. So we have been given an array. We have to divide it into two equal subsets. Equal subset means the sum of their elements should be equal. Now we have been given an array, if we can divide this array into two equal subsets then what will happen, we will have one subset and the other subset, the sum of both will be the same, we assume that the sum is the sum of one of the subsets. We have equal subsets, that is, the sum of the other subset should also be k and we take the sum of our entire array to be the total sum and we have divided it into two subsets, one has even k, the other has even k. This should be equal to the sum of our total array. If we can divide this array into two equal parts, the sum of their elements should be the same. The sum of our two subsets should be equal to our total sum. What does it mean that one of our subsets The sum of elements should be sum total even divided by two then our problem is reduced to we have to find out a subset whose elements have sum total even divided by two and because our sum should be an integer value so if our total sum is an odd number We will not be able to divide into two equal parts because on dividing by two our total will come in decimal. If our total sum is odd in the starting then we can directly return false. We cannot divide it into two equal parts if the sum is even. In that case we will have to check whether we are able to divide it into equal parts or not and for that what we will check is whether there exists a subset of ours which is even. Now how do we find out that our What can we do to determine whether there is a subset whose sum of elements is equal to one? Generate all the subsets and then see whether the sum of any of the subsets is equal to our k or not. How can we generate all the subsets? Our pick Note: How can we generate all the subsets? Our pick Note: How can we generate all the subsets? Our pick Note: Through the pick approach, we consider each element, it will be in our answer or it will not be there, once we try it with pick, once we try it without pick, this is In this way, through our pick note pick approach, we can generate all the subsets. Basically we can write a recursive function. Now what information will we pass in the recursion? One, we are on this index and one, what is the total sum we have to create now. We will pass both these information 0 11 Where did this 11 come from, what is the sum of the elements of our array 1+ 5 6 P 11 17 + 5 22 and what we needed 1+ 5 6 P 11 17 + 5 22 and what we needed 1+ 5 6 P 11 17 + 5 22 and what we needed was the total sum byte i.e. 22/2 11 was the total sum byte i.e. 22/2 11 was the total sum byte i.e. 22/2 11 We get a We have to find out the subset whose sum of elements is equal to 11. We will start our query from here 0 11 and our note pick will explore these two branches. What does pick mean that we have picked this element in our subset. Pick Once we have done this then how will our sum be reduced from one to 11 or 10? Now we have to make 10 and now we will move to the next index. What will be the branch of our pick? What will happen in the case of not 1, 10, we have not picked zero i.e. is not picked zero i.e. is not picked zero i.e. is not part of our subset. We will go to the first index and our sum will still remain 11. Then we will explore this branch further. We will look at the first index. If we pick or do not pick, then what will happen to our sum? Reduce from sum. Now we have to make F. What will happen in the case of N? We will go to second index and we have to make Bh. Then again for second index we have two choices, pick or pick nut. Look at the case, we have to make it even. What is our current element? 11 If we pick it will shoot our over, that is, our eight will not be able to be made, so if our element is bigger than what we have made even, then we should not pick it. If we can then we cannot further explore the branch with pick, from here we will return false or if we pick then our result will not be true, our such a subset will not be formed, so from here we will return false Note What will happen to us in case of pick? We will move to the third index and now we have to make the sum five. Again on the third index we will pick note pick and try both these possibilities. What will happen to us? The sum will be reduced from five. We have moved to the fourth index. Our sum remains zero. The sum remains zero. What does it mean that we have found a subset whose sum of elements is equal to a? What elements have we chosen? 1 5 and 5. What is their sum? 11 So whenever our sum remains zero, what does it mean that we have a Subset found and we will return true from here. This parent will see if it has returned true from any of its branches i.e. it has branches i.e. it has branches i.e. it has found a subset then it will return true to its parent. The parent will see the result of both its left and right branches. If it gets true from any one, it will return true to its parent. If it gets false from both, it will return false. So here, if it gets one true, then it will return true. By propagating like this, it will be on our parent and in the last Our true return will be, if we do not get zero from here, what would we have done? We would have explored the remaining branches, we would have come to this branch, we would have explored all the branches. Now what will be the base case of our recurrences? What we saw was that when our sum remains zero, then we have to return from there. Secondly, what we saw was that we can explore the pick branch only when our element which we have to make even is less than or equal to it and one case is ours. What if we go out of bounds while proceeding, all our elements are finished and still our sum is not zero. Well, in this case we have gone to the fourth index, still we have to make six sum. In this case we have elements. If we don't have any left then we won't be able to make these six. Whenever we go out of bounds, in that case we will return the force, so this will be our base case, the rest will be our standard note pick approach once we see its recursive code. We were given a vector of integers. First of all we had to find out the sum of our array. We found out the sum of our array by applying a loop. If our sum is odd, in that case our answer is not possible. We checked. If our total sum is odd, then return false from here. If our sum is even, we have to check through recurse, then what will we take? Total sum divided by two and then our recursive function is growth index and which will make us even. They will pass. What was our base case, if our amount remains zero, what we have to create is zero left, that is, we got a subset, we will return, if we go out of bounds, all our elements are gone and now Also, we have to make some amount, we have gone out of bounds, we will return false, what will we do after that, our standard note, we will apply this approach, what was ours in the case of pick, if our element is less than or equal to the amount we have to make, only then We can pick and in the case of pick, will we go to the next index, out of the amount we had to create, we have picked the element which is on the current index, if it comes in our subset, then we will subcut it and our recursive function. We will call and by default what will we consider as false? If this branch returns true then our true will be updated in pick here. If no true is returned from here then it will remain our false. What will be the case of not pick? Simply we will next. We will go to the index and our remaining will remain the same and what will we do in the last pick or note, if we have received true from anywhere then we will return true, if we have returned false from both, we will return false or pick or note. If it is true then return it. This is simple. Our rec code will be in this, our pick note pick approach will be this, what will be our time delay, should we make two choices on each index, like this we will have N indexes, what will be our time delay? The power will go to Let's do this by applying memoization, when can we apply it when our statuses are repeating and I have told you that whenever you write this type of note pick rec code, all your problems will always be repeated, you can directly apply memo on it. Yes, how to apply memo, let us see what is our changing variable, two changing variables are index and remaining, so we will apply memo on these, basically we will take a 2d array, one for our index, one for remaining and then we will memorize our states. We will take a 2D vector that is equal to the size of our array for the indexes and we have to create k as many as we want. We will take a deep vector of size n * k and initialize it with -1 which will take a deep vector of size n * k and initialize it with -1 which will take a deep vector of size n * k and initialize it with -1 which will indicate that we have just created it. If the state has not been calculated, we will calculate it. On that state, our value will be updated as true or false and we will pass this DPR to our recursive function. Then after checking the base cases in our recursive, here we will check We will check whether we have already calculated the value of the state or not. If we have done so, then return it directly from here. We do not need to put any recursion on it. If we have not done so, calculate it through recursion and give the result in the end. Before returning, memorize it in your DP state so that you can use it here. Now what will happen to our time delay, whenever we put a memo, what will be our time velocity, as much as our deep states are into each state. How many deep states will we have? The size of our array will be n. In this, what we are doing to calculate each state is a constant operation. We are taking two variables and their Then we are doing some constant operation, what will our overall time loss be n * a of our time loss be n * a of our time loss be n * a of our indices which we have to create and what will be our space complexity, we have taken a deep vector of size n * k, so this is taken a deep vector of size n * k, so this is taken a deep vector of size n * k, so this is our space complexity. Now if we want, we can convert this recursive code into iterative code and then optimize its space. We have already discussed this in the coin change problem. Its code is similar to our as-it-is coin change Its code is similar to our as-it-is coin change Its code is similar to our as-it-is coin change problem. This part has already been discussed about how we convert recursive code into iterative code and then how to space optimize it, so I have given the video link of coin change problem and the link description of it's code and space optimized code for this problem. I will put it in here, you can try to convert it into Ive code yourself and then into space optimized code. If you have stock somewhere, you can refer to the link given in the description and if you want to understand the complete process, then go to coin change page. You can watch the video in which we have discussed it in detail. Thank you guys.
Partition Equal Subset Sum
partition-equal-subset-sum
Given an integer array `nums`, return `true` _if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[1,5,11,5\] **Output:** true **Explanation:** The array can be partitioned as \[1, 5, 5\] and \[11\]. **Example 2:** **Input:** nums = \[1,2,3,5\] **Output:** false **Explanation:** The array cannot be partitioned into equal sum subsets. **Constraints:** * `1 <= nums.length <= 200` * `1 <= nums[i] <= 100`
null
Array,Dynamic Programming
Medium
698,2108,2135,2162
1,371
hello quick introduction to the video my name is Cameron I'm a graduate Apprentice software engineer currently studying at Glasgow University and I'm using this video as a way to sort of rubber duck a debug a l code problem just attempt to solve it talk through my thought process and hopefully someone will find it useful so problem going to be attempting today is 1374 generate a string with characters that have odd counts so reading out this spe here it says given an integer n return a string with n characters such that each character occurs in an odd number of times H the return string must only contain lowercase English letters if there are multiple valid strings return any of them so n is equal to four output is p ppz explanation this is a valid string because the character P occurs three times and the character Zed occurs once so three is odd and so is one H note that there are many other valid strings such as o h and love H constraints are between 1 and 500 and the hint they've given is if n is odd return a string size of n formed by only a else return string formed with n one n minus one and 1 b h so I don't think I don't know if you can see this I think my camera's obstructing it um but what it's um it's saying here I'm going to copy it into my notes so that you can see so the sort of suggestion it has given is if n is odd return a string of size n formed by only by a okay so let's say it's n is equal to 3 you just do a l return string form with nus 1 a so let's say n is four it would be n minus one which is 3 which is a and then 1 B which is so they're both odd so that seems like something that would be fairly simple to implement so check if n is odd and then we'll just do we're going to say that's going to be done through is a is that how you do it so just check if it's equal to zero um if it is return a multiplied by a return a multiplied by n and going to otherwise return e * N - one plus n or h plus b sorry well it could be any letter here really just as long as they are different so let's try and implement this so we're going to copy in our ideas here a just going to put this back to default layout so we're going to do this here in it's divisible by two so if this then we're going to return a e we're going to yeah do a time n and then we can just do return e * n -1 plus -1 plus -1 plus b uh the reason we don't need to put an well we can put an N else here just for readability but it'll just go to here otherwise this would have got run it would have ran anyway so let's check if this works oh um I think it should be the other way around if it's odd so if there is a remainder of one not a remainder of zero that should work there we go three accepted test cases let's submit and that passed thank you very much for watching the video hope this was useful to you in some way shape or form if it was please let me know that leave a comment H or if you had some other way to solve this which was maybe a bit more efficient or different H you know please let me know I love discussing these problems and yeah thank you once again for watching this video and I hope you have a great day bye
Find the Longest Substring Containing Vowels in Even Counts
minimum-remove-to-make-valid-parentheses
Given the string `s`, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. **Example 1:** **Input:** s = "eleetminicoworoep " **Output:** 13 **Explanation:** The longest substring is "leetminicowor " which contains two each of the vowels: **e**, **i** and **o** and zero of the vowels: **a** and **u**. **Example 2:** **Input:** s = "leetcodeisgreat " **Output:** 5 **Explanation:** The longest substring is "leetc " which contains two e's. **Example 3:** **Input:** s = "bcbcbc " **Output:** 6 **Explanation:** In this case, the given string "bcbcbc " is the longest because all vowels: **a**, **e**, **i**, **o** and **u** appear zero times. **Constraints:** * `1 <= s.length <= 5 x 10^5` * `s` contains only lowercase English letters. It is the empty string, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string.
Each prefix of a balanced parentheses has a number of open parentheses greater or equal than closed parentheses, similar idea with each suffix. Check the array from left to right, remove characters that do not meet the property mentioned above, same idea in backward way.
String,Stack
Medium
2095,2221
290
Hi everyone, I hope it is very fine today, which is our topic, friend, in which we will talk about the topic of judge map, in which we will solve the word patterns today, how will we solve the word patterns, how easy is it going to be, in what way. If we approach then the same approach as we used for isomorphic, which was our 12th problem, we have solved 12 problems till now in the lead code, this is our 13th problem, what are we going to solve within 13 that word pattern. How do we actually draw our word patterns and what is the word pattern trying to do in it because I don't care about what happens with word patterns so we will read the questions and try to understand the questions and then move ahead. Okay, I am going to tell you a very easy approach, so stay tuned till the end of the video and if you are new to our channel, then subscribe to the channel, my friend. Let's start with what actually has to be done in this. Okay, now let's talk about word patterns. Now let's start reading the question from the word pattern. Let's see what the approach is going to be. It is saying given pattern, you have been given a pattern is it right and a string s is also given. Okay and find if s. Follow the Same Pattern We have two strings given, this is made clear, one is named as pattern, the other is named as S and what is it saying that whatever A is it following the patterns, that means the S string is that pattern. Is following the string. If it is then return true otherwise return false. Now what are you trying to say, they will understand through examples. Before understanding follow through examples, let us first understand what is the meaning of follow. It is saying here follow here. Means full match should be done. Now what should be matched, let's see the truth that there is a bye junction between a letter in a pattern. Bye junction means one mapping. Okay what is one for every letter of every letter. What should be a in between? One mapping should be T is called by junction and not MT word will be there inside your A means inside A definitely you will have words What will be the words inside A What will be the words will not be characters Okay Yes and you understand through the example what the word pattern is trying to say. Okay, let's take this example in the example and I think if you have not seen the video of isomorphic then I will tell you in advance friend this video. Before watching this previous video, I have given the complete same concept in isomorphic here because what is the meaning of same concept isomorphic, whether the S given in our isomorphic is able to get t by replacing all the characters of S. Meaning of t, whatever characters are inside t, they are able to achieve that is called isomorphic, so there is same logic here, can we achieve the pat patterns by following that means sorry a? It is okay, here we do n't have to get the pay gate, that means whether we are able to follow the patterns or not, it remains to be seen, it is only okay, we don't want to make that match happen, we just want to make the match that he is following the patterns, I said. That our patterns are that after one, two should come, three and four should come, but what is coming in the pattern, after one, five is coming, 10 is coming, 20 is coming, so it is not following the patterns. So we have to follow the patterns, what is a pattern, I had told in Isomorphic here also, let me show you by doing it, so let's understand it with an example, first quickly, now I am telling you, a pattern is given here, see the first examples here. Here is an example to understand how it came to be true. Next you will also understand what is actually being said in the question. Okay, so what is being said is given in the patterns. A B A. Okay, this is given in the patterns. One string is given in the second string and it is given in the form of a word in which dog is given cat is given dog is given is it true and what is the output coming true how is it possible so see when we in isomorphic My friend, suppose we have what is given in the form of a pattern, I have declared it as P, it is okay, P means pattern and the characters given inside the patterns are given as A B A. Okay, what do I say now, the second string given here is given as string ss, so I pick it up from here, this is given here, I control C and paste it here, control v, we have a pattern. Is given and second our s means a sting s is given ok now what are you saying is it a complete match or not because it is saying follow means there should be a full match now what should be the match understand that thing Patters We have to match the characters, we don't have to match the characters, we only have to match the patterns, now what have to be done, look, if I said here I take one or I replaced the a, I used to do the same thing, now in isomorphic, one map because of the bikes. Talking about forest, I have mapped A to Dog, so now whatever number of characters are there inside A, that is, whatever number of characters named A are there inside the patterns, then our mapping will be the same with Dog. This is what we have done. What was done inside isomorphic is that brother, if I have replaced A with E then always whatever A is will be replaced with E. Got it, so here also I did the same that if I have got A mapped with Dog then always This is what will be mapped with dog only then will the possibilities come what to do if it is a word pattern only then will it return true ok now I have taken it for the second time I have got BB mapped I have got it mapped from whom so I have got it right from cat to cat Then what do we have? B came and again I have to map B to what, so we have to map it to Kate, so what if this was a here at zero index, this was this at zero index, now here also zero. If there was a dog on the index, then I have mapped a to the dog at the zero index. At the zero index, we will always get this a mapped to the dog. If there is a dog inside it, then we have to always get the mapping from a only. I said one index. I got one index P, I got it, so I got B. Now look at what B is, I am getting CAT at index zero and K, so what have we done by mapping B to CAT, and now what we will always assume is that we have B to CAT. Mapping has to be done from 1st onwards so I moved ahead again I got B so we will see if we are getting CAT again and is it following the patterns or not otherwise work has been done on 0 and 2nd index. What do we get on the index? If we get CAT, then here too, on the index of 0 1 2, B and whom is B following? So, yes, that B will always assume that what we have to do is to get CAT, so here we are. What will we do with Kate? What will we do? Will we get it mapped? Here you can see that we have got B mapped with Kate. If there was no Kate here, Apple would be here or let's say some other name like Fox. If the box would have been there, if there was any name, I would have said, it is not matching the pattern, it is not following the patterns, it would have made return false, but what is it doing, mapped B to Kate, now when I reached B. At the index of 0 2 So here also at the index of 2 we got Kate That means it is following the patterns Now I go ahead and I reached A Pe Now it will get it mapped to whom so it will always get the dog mapped so we Again at index 0 1 2 3 we got this so here at index 0 1 2 3 what we got is the whole dog and we had to map a to dog itself so here we mapped dog so Here you can see that he is doing the whole pattern by following it, the whole pattern is matching ours, this whole pattern is our same and also completely matching, that is called, what is our word pattern, get it returned, true, now let's take it. Second example, what is being said in the second examples, second example is this, dog cat neck, now what have I done, I have changed the fees here, I will explain in this. Okay, second examples, I have explained in this, I have changed the fees here. I do it, okay, what is he doing, he is following the dog, what is he doing, he is getting the dog mapped, okay, now he will always get Dr. B., he is getting our cat he will always get Dr. B., he is getting our cat he will always get Dr. B., he is getting our cat mapped, so B. Always got the cat mapped here but now look here at the index of 01 2 3, here a is mapping our dog but here at the index of 3 the fee has come, that means this is not our word pattern. We will get the return done here. In this case, if we get a return done then we will get a false return. I hope that now you are 100% clear about hope that now you are 100% clear about what the questions actually want to say and what the word patterns mean that means if. That word pattern, the word given, that is our S, that S is our word, if it is following the patterns, that means, get it our return, in that case, draw the other wise, get it returned if false. If there was a dog here then we would have got the return done instead of true fee but here the fee is that means A So this one who is ours is getting the dog mapped I have fixed it once B If we are getting our cat mapped then always that B is he will get the cat mapped and will go as a patter so it is ok but now here I got a Nakhl on the index of three Now here we should have got the dog on the index of th but we are getting fees that means It is not matching the patterns, it is not following the patterns because here we cannot pay the fees, if I pay the fees here and what arrangements have we already made here, it has been fixed that only the dog should come one by one. At position a, this which is ours, will get mapped to do only, so how can we get a mapped to fis here, it is not possible, that is why what has been returned here is false and I think you will also see the third one which is our pattern. It is the same thing, okay, so I think it is clear to you now, look here, one is a word, the other one is the pattern, what are we doing with the character inside the patterns, look, there are two things here, now why the shape of hedge map. And why did we say that we are solving the topic of Hedge Map, then why did the logic of Hedge Map come here? Think a little, hey man, see what we are doing with one A, what are we doing with this character of A, in this whole We are getting the world mapped and then from the character of this B, we are getting the entire Kate, that is, the words of this entire Kate, mapped, so one is following the character and the other is following our word, the character is the word and the word is in which form. If it comes in the form of sting, then what is inside hedge functions? What do hedge functions say? What do we call hedge? What is hedge mapping? Actually, hedge mapping is a key value, so we also have keys and Values ​​are also there, that means keys, we will take and Values ​​are also there, that means keys, we will take and Values ​​are also there, that means keys, we will take characters as values, we will take strings, so inside the map, we will write inside the hedge map, one is character and the other is string. Now I have also made it clear to you that why we will pass character and string here. We will have one key and the other value. Here two things are being found, so we do not have to think about what we have to use directly, we have to use our hedge map and in this way we get to know, it automatically comes to our mind. Or not, there are possibilities of hedge map here, we can use it here. Okay, let's move ahead. Now let's put the hedge map here. I hope you got to know how the hedge map came about. We had shown you this in isomorphic. Let me also show you this whole pattern, this whole line is going to be copy and pasted, whole line, this whole line is going to be copy and pasted, this whole line is isomorphic because they used to do the same things here too, brother, if a is on the character of e, I fixed it. If it is then it should always come on the character of e. If it is not coming then make return false then same, we are going to give the implementation of this whole logic here, okay that is why I said that if you have not seen the videos of isomorphic then there Go and see because I will not go into that much detail but still I will try my best 100% You should still I will try my best 100% You should still I will try my best 100% You should understand in this video also why did I put the hedge map here, I think you got it, okay so I put the hedge map and Inside the hash map, we talked about two things, one is the character, second is why we took it, we also told you this because in the form of one character, we are checking the meaning of the data and second is the word, so that while mapping, we can know that it is Is it following the patterns or not then we will have a character, okay one is character and the other is string and its name is map forever so I keep map only and new and here pe has and here Okay, now what do I do? Now I want the whole word, I want it in the form of sting, right, we want this zero index P, we do not want the character, in this case we want the K, in the case of S, we want the whole word so that we can use this. Inside the pattern, inside the patterns, we will target the character and inside this S, we will target the entire word, so how to target the word, apply a little logic, if we want this entire word, we want the entire string, we do not want the character. No, we do not want D to match, we have to make the whole world follow us and we have to make that too, we do not have to make the character nor the whole word match, we have to check whether it is following the pattern or not, that's all. If you want to consider then the logic used here is that your function is in a split, what it does is that it is in the string, it converts it into an array and what it does after converting it into an array, it completes one zero. What will be included in the index? This entire word will be included, it separates the entire word in one index, so what will be the benefit to us from this, we will know that yes, because we have to target the entire word, then by using only one word, we will get the information. If you use split here, you can target the entire word. If you do not use split, then you will check at the zero index. Do you know what this zero will do? It will not think of the string, so only check D at the zero index. Where will O go, then we split it, then we split the string in the form of an array, then I name the string as an array, after splitting it, whatever character of the entire string, the words written inside the entire string, this entire string is in the form of an array. I convert it into string array, how will it be converted into s dot, its name is split, it is okay, split is a function, okay, I have put this, what will happen with this, just understand, I also write to you that now this zero index What will we target, it will target this entire array, then what will we target at index 1, we will target the entire array, it will target the array at index 01 2, and it will target the entire array at index 01 2 3. It comes in the form, something like this, it separates the data, okay, so this row on index, this one index on two index, three index on I hope this thing is clear to you, let's move ahead, now what do we do here? Logically, what we have to do is mapping. Got it, so what do I do? The pattern of this whole world, which has complete characters inside the pattern, what do we do with it? We store it inside the map memory, why is it so that from the map it is Find out if it is already present inside the map, then is it ok? Is it inside the map, our characters, our words, is it following our instructions, what we are trying to give, what we are trying to tell, which is ours? There are rules, is he following it or not, so what will I do to target that thing, see what I do, first put it inside the map, think how will you put it, then we will have to put a loop because every character has to do what we have to do in the map. We have to simultaneously put both the character and the word inside the map so that I know what is the zero index page, so now here also the page is zero index page, this is the entire zero index page, whatever it is, we put it inside the mapping. And after that we will start checking how see I started from 0 and let's go to the length of the pattern and this is the pattern, first in the form of already sting, we only converted which one, then in my casting and I Let's do plus now what do we need? Inside the patterns we will target the character but inside this s we target the entire word. What inside the got it pattern we are targeting? How will we get the character? If I say that how will we get this character on the zero index page, then by adding the character t aa, we would have got the character t aa inside the pattern, then what will I do, that pattern d character t aa, if I do not have to write that long, then I will say c name. How will I store the variable K? So pattern P A double t e r n pattern dot character at this whole line so that I don't have to write such a long line means again and again, that's why I did this now, if let's say I found this in the zero index, then this is already done. If we store it inside C, then only we will have to write C, we will not have to write the whole line, it is so long, okay, it will go to one index and by default it will change what will be found on one index, if it gets B, then B will be in our variable named C. Aka will be stored, now what do I want, from here I got the character, now I want this whole word, how to get this word, then it will be found in the case of string, so what will we do here, if we pass the string instead of passing the character, then the string is its db ID. Would have kept the word name so that you can understand that this complete word is required inside the string. String word is equal to two and how to get this word. If this word is inside then it is inside the array. If the string is not inside the array then it is inside the string. Ka zero, this is the zero index, we need the whole dog, so how will we get it, so we have to pass it here, if it is inside the array, then we will pass the array of a, now the array of i, zero index, the whole dog should be added, now this work is done, now what do I do? I am this, which is our character and this is the whole word, this is Jora, this is my character, this is the word, we store it inside our map, we put it inside the map, the meaning of put is we do it, what to do with it? I hope it is clear to you about the vector and that word, now I just have to apply a logic which I had applied in isomorphic, what was applied here, the condition is that we will check whether it is present inside the map or not, apply this thing only. So I thought I will paste it and then we will change it. Ok, the video will not be very long, so I will pick this one, it seems to be the same logic, what will I change now, just tell me, if it is okay, then I will control it. Map dot content, now s1 will not be here, this is our C, now what does it mean, understand the meaning of this line, map dot content, C means character and that character, whose patterns, what is there in the patterns ? It is present inside the map. ? It is present inside the map. ? It is present inside the map. If it is present inside the map, then I will put here not now not map dot get if that character, the first condition, what did I put to see if it is present inside the map, I checked if it is inside the map. That character is present now because I did not get anything done. When I started walking inside the map then I did map dot cont. What character is present? If it is ok then character is present. Second condition is map dot get character now dot get character taken. Now what is inside the character? So what is this, is equals y, I will put dot equal a little bit E Q L equals, whose word's, now what is the zero index inside the word, what is our zero index inside the word, so zero index is our y index. Okay, I will also put this zero index, this one index, two index, three index, in the same way, we will come here, okay and I will also put a little gap in it so that you know which index is on which, okay? This zero index one index two index this index and here also I do this zero index this one index this two index and this index ok now I said inside the map I moved inside the map I placed the content at zero index a got now what did we get at zero index a got ok now I checked map d get c now map d get c means then what did we get at zero index dog got what is that which is dog sorry character a what a which is not If the word is equals then it is not equals. The word dog means in the first case it is not equals because the character which is the word is not present in the map for the first time, so what did I check in this case? Dot Get If Which Character Is If Not Equals Is Given By Word Then After If That Character Is Not Present Inside The Map But It Is Not Present Inside The Map Then That Character Is Not Inside The Map But The Map Values ​​D Contains That It is present inside the word, Map Values ​​D Contains That It is present inside the word, Map Values ​​D Contains That It is present inside the word, which is the same condition that I had applied there, that means that it has already been mapped, but it was not inside the map, after the mapping, it was inside what, so inside our character, that means that the word is of the word. If it was inside, then if it was inside the word, then mapping has already been done, so that means it will return false. In this case, there were only these changes here and I have explained the entire condition in brief. In isomorphic, I will not do a dry run one by one. Why did you just understand that it is not inside the map then if they check that character is it equal here like I said zero index pe row index pe a which is the first time then come inside the map. I put it inside the map, I moved it on one index, I said, is it inside the map, so inside the map, assume that b was, assume that already b is our present, then it is okay, a b is present, now I check here. Will I do map dot get c now what is b inside c ok c is meaning b is b not equal towards and inside words what is our kate and this kate is already ours once present inside the map so I will check If B and B are also present then is it equal? ​​Yes yes it present then is it equal? ​​Yes yes it present then is it equal? ​​Yes yes it is equal then in that case it will make return true but if not equal then what would we do here in this case we would make return false so I checked this condition and I think and I There is no need to change anything here and one more thing we can check is its length, it is mandatory length, we must check it is okay here, what do I check, is this if the length of both is not equal, this if our Which is the length of the array because if it is not equal then how will we be able to match the entire pattern then the array dot ajt h length if not equal whose pattern is dot length then what do you do in that case also get it returned then it is ok in that case. What should I do? Get me to return. Fors I think and lastly, if overall not even one of these conditions follows us, then get me to return. True yes, if you accept it is right, it is inside the map. The value is also equals, not equals. After that, it is inside the map inside the not equals. After that, it is inside the map and is also containing the value. Get that message written and once we run it, we are getting compile time error. What error is there? Let's see the pattern dot length ok. Hey aa le e ok the spelling is wrong ok p double t r bay let's see man yes so all three of our test cases passed you can see and a little bit and I make it smaller I think you can see it in a better way Okay, now I run it once I run it and submit it, you can see that it has been accepted and I hope you have understood how easy we have solved it. Took but I would like to say that before solving this problem, what you should do is solve the isomers because I told you more deeply there. Okay, so for today, see you in the next video with similar concept, my two Jai. Hind Jai Bharat
Word Pattern
word-pattern
Given a `pattern` and a string `s`, find if `s` follows the same pattern. Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `s`. **Example 1:** **Input:** pattern = "abba ", s = "dog cat cat dog " **Output:** true **Example 2:** **Input:** pattern = "abba ", s = "dog cat cat fish " **Output:** false **Example 3:** **Input:** pattern = "aaaa ", s = "dog cat cat dog " **Output:** false **Constraints:** * `1 <= pattern.length <= 300` * `pattern` contains only lower-case English letters. * `1 <= s.length <= 3000` * `s` contains only lowercase English letters and spaces `' '`. * `s` **does not contain** any leading or trailing spaces. * All the words in `s` are separated by a **single space**.
null
Hash Table,String
Easy
205,291
1,832
hello everyone let's try to be a cheat code ninja today we will be solving a very easy string problem here we are given a definition of a pan gram is a sentence in which all the 26 characters of the English alphabet are present hence a pan gram must contain all the characters from a till z so given a sentence we have to check whether it's a pan gram or not and if it is a pentagram we have to return true else we have to return false now let's look at an example here in this sentence we can find all the characters a b c and so on till z hence this is a pan gram in the second example we cannot find the character a in the given sentence hence this is not a pan gram let's look at how we can solve this problem we have to find all the 26 characters in our sentence hence for each character we have to search whether it exists in the sentence or not for example we have to search whether a exists in the sentence and similarly we have to search b and so on the time complexity of this would be since for each of the 26 characters we have to check the entire sentence it would be o of 26 N and the space complexity would be we won't be needing any extra space hence it would be constant let's look at another solution for this we can use a hash set to store all the characters that we have found in the sentence for example we would be storing the characters t h e in our hash set and when we encounter T again we won't be adding it again to the hash set since it already exists over there at the end we will be checking if our hash set has 26 characters or not here the time complexity would be o of n because we'll be going through the sentence only once and the space complexity would be o of 26 because we'll be storing all the 26 characters in The Hash set which is basically the same as o of 1. now let's Implement our solution we have to create a hash set from our sentence and then check if its length is equal to 26 this part would create a hash set from our sentence and then we have to check whether its length is equal to 26 or not let's submit our solution as you can see our solution is accepted if you have any concerns about this Solution please mention in the comments if you thought this video was helpful please leave a like And subscribe to the channel thanks for watching
Check if the Sentence Is Pangram
minimum-operations-to-make-a-subsequence
A **pangram** is a sentence where every letter of the English alphabet appears at least once. Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._ **Example 1:** **Input:** sentence = "thequickbrownfoxjumpsoverthelazydog " **Output:** true **Explanation:** sentence contains at least one of every letter of the English alphabet. **Example 2:** **Input:** sentence = "leetcode " **Output:** false **Constraints:** * `1 <= sentence.length <= 1000` * `sentence` consists of lowercase English letters.
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
Array,Hash Table,Binary Search,Greedy
Hard
null
315
and welcome to another one of my lead code videos in this one we will do lead code number 315 count of smaller numbers after self so how the problem goes is you're given an array an input array and you need to return an output where corresponding to each element you count the number of numbers that are smaller than this number to the right in the input array so for example the first one is five so there's two numbers that are smaller than five to the right of five so there's two and one so there's that's why the output here says two the next element two if you look to the right of two only one number is smaller than two so that's why there's one next element six if you look to the right of six only one number is smaller than six so we have one and finally if we look to the right of one there's nothing so naturally this will be zero so yeah given this input we have to produce this output so how do we solve this problem so the brute forced approach is going to be an N squared algorithm where you pick an element and you scan through the rest of the array to count how many elements there are but obviously that's going to be very slow because it's O N squared for each one you have to scan through the rest of the array right so that's inefficient then the next thing that comes to mind is okay can we do some kind of sorting right but if you think about sorting here won't actually help because if you sort this array and then like try to find okay where does like five place in that array um it might not be accurate because like if you look at six for example um the smaller numbers could be at the left of six and we don't want to count them we only want to count what is to the right of six right so we could actually extend that idea and do it backwards if you think about it so basically we keep track of a sorted array but we Traverse this list going backwards and we keep track of a sorted array right so we start from the first element and then we add this to our sorted area one when we move to six we find the position of 6 in that sorted array right so everything the position will indicate how many numbers in that sorted area are smaller than six right and then we keep moving that way every time we insert an element we maintain the sorted list and then the position that we inserted in N will be our index so for example our input list is five two six one we'll maintain a sorted list right so we'll start from index one so for when traversing in index one uh our sorted list will become one and the index where we inserted one is zero right because we inserted one at the zeroth index of our sorted list and for the next iteration we will have six right so inserting six into our sorted list we'll have 1 6 and the index of this six will be one because that's where we inserted it and the index will tell us how many elements are before 6 which meaning are smaller than six right and so the next number is let's say 2 right so inserting to an assorted list will be one to six and the index will be equal to 1 because we inserted 2 at the index 1 which means there's one element smaller than six and then finally uh we have number five which will be inserted into our sorted list so it will be one two five six and since 5 is inserted at the second index will create index equals two so this tells us if you then look at this answer that's actually your answer right because it tells us like okay for each element what is the index when you insert it to the sorted array starting from the right so then so we just keep adding these indexes that we insert it in to array in backward uh like every time we add it to the front right because we're going backward and then that will be our final answer so the time complexity of this if you look at it will be um o of n log n because we will Traverse through the input list right going one by one and for each element we'll insert it into a sorted list so inserting into a sorted list is log n because we can use binary search to find the index where we should insert it right so it will be o n log n instead of the Brute Force which is O N squared so let's try to code this solution I will first start by creating the list of integer which will be our sorted list right so this is that sorted list that we talked about earlier that we will maintain and this will be an array list and then we'll create a list of um smaller to the right which will be actually be our like resulting list and this one will actually create it as a linked list because every time we want to insert at the start of the list as you saw earlier we want to read it in reverse so we will call this smaller to the right and as a linked list because insertion and linked list is o1 and insertion and arraylist at the zeroth index can be o n because it has to shift everything to the right so now we'll just go through our array in reverse order as we discussed so now we're going through it in reverse order and for each element in this array what we want to do is uh insert it in the sorted list right so we'll go we'll make a function called insert and get index which will insert nums at I in the sorted list that we maintain and return the index and then what we'll do is we'll just add that index to our array right but we'll add it at the zeroth index because we want to read it backward right so as you saw earlier uh the index will indicate how many elements are smaller than it which is uh what we actually want and then finally we'll just return this ah sorry not index we will return smaller to the right so with this uh now we just need to implement this method we just insert and get Index this is a kind of a standard binary search so I will just pause the video and paste yep so this is a binary search I'll just quickly walk through it so we have our sorted list and our number this is just an optimization that says this is actually the case where if the list is empty then we want to just insert it at the zeroth position and return zero or if our number is less than the first element in the list then you know not it is kind of the smallest element so we just insert it at the start similarly if our number is greater than the last element then we just insert it at the end and then this is just a standard binary search High minus low is greater than one we find the middle we keep moving our high and low and in the end you know the high end low can like get stuck next to each other so this just determines like where exactly what exactly is the index that is less than or equal to our number that we want to insert accounting for edge cases so yeah this is just pretty standard binary search insertion sort so let's now run the algorithm to see if it works compile error oh the method name has to be oh cool and let's submit it solution is accepted so yeah thank you so much for watching I'll see you in the next one
Count of Smaller Numbers After Self
count-of-smaller-numbers-after-self
Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`. **Example 1:** **Input:** nums = \[5,2,6,1\] **Output:** \[2,1,1,0\] **Explanation:** To the right of 5 there are **2** smaller elements (2 and 1). To the right of 2 there is only **1** smaller element (1). To the right of 6 there is **1** smaller element (1). To the right of 1 there is **0** smaller element. **Example 2:** **Input:** nums = \[-1\] **Output:** \[0\] **Example 3:** **Input:** nums = \[-1,-1\] **Output:** \[0,0\] **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
Hard
327,406,493,1482,2280
160
everyone welcome back and let's write some more neat code today so today let's solve another classic problem intersection of two linked lists there's quite a few solutions to this problem but we're going to be focusing most on the most optimal solution but let's read the problem first so we're given the head of two singly linked lists a and b we want to return the node at which the two lists intersect each other so you can tell that by this pretty good uh drawing that they gave us so in this case they intersect here because that's the first node that they share in common right that's that node belongs to both list a and to list b and we're of course given the heads of each of the list and we're not allowed to modify the structure of the two linked lists now the most easy solution would involve extra memory which does not satisfy the follow-up and what i mean by that is we follow-up and what i mean by that is we follow-up and what i mean by that is we could take each of these linked list nodes for just one of the lists let's just start with a and then let's go through every node add it to a hash set so these are going to count as all of the nodes we have seen from list a next we're going to iterate through list b checking if any of these are also in the hash set and the first one that we find so what we're going to do is say is this in the hash set nope is this nope but this one is we're going to see it is in the hash set and then we're going to return this as the intersection point because it's the first one that intersected now it's possible that the two lists don't intersect and if they don't intersect we're just going to return null as the result because they don't intersect that's the easy solution with extra memory but how could we do it if we didn't have extra memory and the answer is actually not too difficult to come up with especially when you have a picture like this one which is why i always recommend drawing pictures one of these lists is longer than the other this one has five nodes in it but this one has six nodes in it we know that if they do intersect the end of the lists is going to be the exact same so if we were given the length of each of these lists one is five one is six then how would we solve it if we already knew that well what i would do is start one pointer at the beginning of list a because it's shorter start one pointer at the beginning of list b and then increment just the b pointer by the difference in the length of these two we know that this is six this is five so the difference is one so i'm going to increment this one just by one so it's going to be over here then we're going to actually run our algorithm we're going to compare these two nodes are they the same nope then we're going to increment both of our pointers are these two the same nope then we're going to increment again and these two are the same so this is the intersection point and then we can return that as the result now of course if we never intersected right somehow we reached the end of both of the lists they're both null uh then we're going to return null as our result so in a sense null is the intersection point so it kind of works out pretty cleanly right because they intersected at null and you can encode this solution up but it involves a bit more code and there's actually a very elegant solution that i think you guys might like it uses the exact same idea of kind of using the length of each list to our advantage but in this case we don't actually have to find the exact length of each list and then you know increment that pointer by the difference um and i'll explain the intuition why before we actually get into the solution first what if i had one pointer and set it to the beginning of list a and then i incremented it five times right like this one two three four five and then reach the end uh you know the null and then when i do reach null i uh it took me five spots to do that if you don't count the null and then i go to b and then from b i go through every position one two three four five six spots before we get back to null so that makes sense that's five plus six what if we do a similar thing uh with the b list starting at the b list we go one two three four five six and then reach the end and when we reach the end we go to the other list the opposite list at a and then uh keep going and then keep doing that until we reach the end of the list so these two pointers are going to intersect at the uh the null point and the reason is because with the blue pointer we had five plus six with the purple pointer we also had five plus six so of course they are going to intersect at the end they just went through the two lists in an opposite order why is that helpful for us well because if these two pointers both intersect here after 11 spaces suppose right that means after 10 spaces they're both going to be here and that means uh if it took 10 spaces to reach that means in nine spaces they probably would have intersected here if they did that means in eight spaces they would have intersected here so basically the first time that they intersect that is going to be the result in this case i know it's not super intuitive but if you think about it uses the lists to our advantage and i'll kind of just go through a quick simulation just to show you how it works so let's say in five spots uh from a we got all the way to the end and from five spots at b we got all the way uh to this spot right so we took five spaces with each of the pointers uh next since we reached the end we're going to set the first pointer to the beginning of b this pointer is just going to be incremented by one and now we're going to increment each pointer one more time so the blue pointer is going to be set to this position and the position at the end of this list is actually going to be set to this position so now you can see yes they are basically exactly how we wanted them right now we'll keep incrementing each of these until we get to the intersection point and of course we are iterating through each of the lists twice in a sense but the time complexity is still you know pretty much n plus m the size of both lists added together uh no extra memory complexity right so the memory complexity is big o of one with that said let's finally jump into the code okay so now let's code it up and i'm gonna make it look pretty easy but there are a lot of ways that we can go wrong with this so initially i'm gonna have l1 and l2 and just set it to the beginning of each of the lists and we're going to continue to increment them while both of them are not equal to each other and uh when they are equal to each other this loop is going to exit and what are we going to return well since they're both equal we could return either one we could return l1 or l2 i'm just going to do l1 when they are equal what does that mean that means they intersected right they reach the exact same node but it could also mean that we reach the end of both lists right both of them happen to be null and we didn't find a result so in that case the loop would also exit and we would return null the easy thing we're going to do is of course set l1 to be the next node and l2 is also going to be the next node but what about when they reach the end of each of the respective lists what do we want to do then if l1 was already null what would we do well in that case we're going to set it to l2 so uh this is going to be only if l1 is non-null else going to be only if l1 is non-null else going to be only if l1 is non-null else we're going to set it to be l2 but not l2 we want it to actually be the beginning of l2 right which is head b l2 is a pointer that we're currently manipulating we don't want to set it to l2 we want to set it to head be the beginning of that list and similarly with this one if l2 else if it is null then we want to set it to the opposite list which is head a in this case now let's run the code to make sure that it works and as you can see on the left yes it does and it's pretty efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Intersection of Two Linked Lists
intersection-of-two-linked-lists
Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`. For example, the following two linked lists begin to intersect at node `c1`: The test cases are generated such that there are no cycles anywhere in the entire linked structure. **Note** that the linked lists must **retain their original structure** after the function returns. **Custom Judge:** The inputs to the **judge** are given as follows (your program is **not** given these inputs): * `intersectVal` - The value of the node where the intersection occurs. This is `0` if there is no intersected node. * `listA` - The first linked list. * `listB` - The second linked list. * `skipA` - The number of nodes to skip ahead in `listA` (starting from the head) to get to the intersected node. * `skipB` - The number of nodes to skip ahead in `listB` (starting from the head) to get to the intersected node. The judge will then create the linked structure based on these inputs and pass the two heads, `headA` and `headB` to your program. If you correctly return the intersected node, then your solution will be **accepted**. **Example 1:** **Input:** intersectVal = 8, listA = \[4,1,8,4,5\], listB = \[5,6,1,8,4,5\], skipA = 2, skipB = 3 **Output:** Intersected at '8' **Explanation:** The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as \[4,1,8,4,5\]. From the head of B, it reads as \[5,6,1,8,4,5\]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory. **Example 2:** **Input:** intersectVal = 2, listA = \[1,9,1,2,4\], listB = \[3,2,4\], skipA = 3, skipB = 1 **Output:** Intersected at '2' **Explanation:** The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as \[1,9,1,2,4\]. From the head of B, it reads as \[3,2,4\]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. **Example 3:** **Input:** intersectVal = 0, listA = \[2,6,4\], listB = \[1,5\], skipA = 3, skipB = 2 **Output:** No intersection **Explanation:** From the head of A, it reads as \[2,6,4\]. From the head of B, it reads as \[1,5\]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. **Constraints:** * The number of nodes of `listA` is in the `m`. * The number of nodes of `listB` is in the `n`. * `1 <= m, n <= 3 * 104` * `1 <= Node.val <= 105` * `0 <= skipA < m` * `0 <= skipB < n` * `intersectVal` is `0` if `listA` and `listB` do not intersect. * `intersectVal == listA[skipA] == listB[skipB]` if `listA` and `listB` intersect. **Follow up:** Could you write a solution that runs in `O(m + n)` time and use only `O(1)` memory?
null
Hash Table,Linked List,Two Pointers
Easy
599
54
legal question 54 spiral matrix and it's a median legal question basically you have mult m multiplex and matrix written all elements of the matrix in a spiral order so you want to what you want to go through is like example the matrix you want to start from this element and go all the way to the right all the way to the bottom all the way to the left and all the way up and not this one because you already printed at this output and then you want to go right and then when you print the output you want to print include every single element in the matrix and print them out and that's the sequence 9745 and that's the result that you get and if you have an element that m does not equal to n then you go from one to uh twelve and nine and five and you continue to go the go to the last element and then you print five six seven that's the end of it and you can see here some constraints here and um in the past six months microsoft asked this question 26 times and it's uh great question to practice on um if you look at this is um we want to say um like um let me give you a example here that let's say that we have this uh one two three and then the bottom has four five six and then seven eight nine right we just use this one as an example so basically this um we wanna call this um want to set a boundary for every single element when we append it this the one that we want to set it to left and the three let me just put a l and three is the right and then uh then we wanna set up a boundary of here is the up and then here is down and let me just shift them to make sure that they look right and then basically that's how it is up and down you set up a boundary and then you can iterate through the list and continue to move them and at the beginning left and up or equals to zero after you define the rows and columns and right and the bottom is at the length of the basically the rows and columns minus one right and then what you wanted to do is while the length of the result after you printed all um every single element they are smaller than the rows multiplex columns so and in this case is 3 multiplex 3 if it prints it's not exceeding 9 element then you will still need to go through continue to print the element and when you so then when you print the element you want to add way through every single row right for the first one you just go through this row but then you want to go through so the column is for the column in this range on the between the left and this right and then you append every single element to the result and when you go down this row because you have already printed this element right so you want to say the when you wanted next item you want to go through four row in different range and then you want to row plus basically the row plus one basically go to this row right and then you want to go to the bottom the last row and then you move to the left side if um you move to the left side and then if up does not equals to down that means that you still need to continue go through the list because if they are equal together you already go to the end of the list if um or if left equals to right you already go through the end of the um the row the column so then you're going to continue to go up and then print out every single element and because the i'm going to use a while loop so every single time when you go through one line you want to make sure to add the left to add a one to the left side and a decrease one on the right side and plus one on the up and a minus one on the down so for them to meet each other that's every single uh every single time when you go through a row in a column and i'm gonna show you how to do this in uh code and i think you will understand this better and so basically i'm gonna give it a result to print all the elements and i'm going to define rows and columns that's basically just like all the graph problems and you want to length is the matrix and the calls is basically the length of matrix and zero right and then you want to set up equals to left to zero like i mentioned in the graph here and then you want to set right is equals to cos minus one because the right side is basically the colon uh the cos uh basically this length defined here minus one and the down is uh equals to rows minus one and now i'm going to go through the while loop and the while loop is basically the length result is smaller than the rows multiplex calls that's the while loop and then for this while loop i'm gonna go through the first row here so i'm gonna say for call and range and the range for this column range is basically from the left to right i need to plus one because in python if i say plus one it will actually the range will only process until the right so that's how i make sure it will print this column including the element three that's why i have to do it this way so i'm gonna say result append a result append the matrix and the matrix is basically the first row right then the matrix is up and then the uh that's the call that i set the range for right and then i'm going to go down for row in range of um so now i'm going through the print uh elements six and nine so the row range is up plus one because i have moved down to six that's why it's uh row up top up plus one and then because for the down i want to make sure that it does print the nine element so i have to make sure it's down plus one so that it will print element nine right and then i'm gonna say result append matrix and the matrix here because i'm going through this column here so it's actually row and then the um the colon is the right it's basically on the right side and then that's it and if up does not equal to um down if up does not equal to down it not yet i'm going to process this from the last element to the beginning of the element so i'm going to say for call so for colon in range the last element is right minus one because i have already plus the nine so i wanna process the nine so i wanna do and left is left or minus one because i will have to go through this first element and then minus one meaning go from the last element to the beginning and i'm gonna say rest append matrix and the matrix is basically down because i'm in the last row right and then um the colon that's the call right and then um if left does not equal to right yet so i need to continue to go through the list so for row in range down minus one so basically down minus one is because i already printed the seven right so i want to start printing from the four and then from the and then the first one is up because i already printed the first element so then it's up instead of i up minus one and i want to process also from the last element to the beginning minus one meaning process the reverse uh sequence so then rest result i'm gonna append this basically the uh four here and the four is basically the row and then uh the column is the left right if you look at it the column is the left here that's it but for every single iteration i need to like i mentioned i need to make sure left plus one and the right i need to make sure minus one because every single time when i move continue to print the window is getting smaller and smaller so it can continue to print and the up i will need to plus one as well because the up will actually move down but the down will move up when you're printing so down is minus plus one in this case and then for the while loop when i um me the condition does not meet anymore i will return the result and that's it for the code uh line expected a indent block in let me just remove this part yep if you think this is helpful please like my video and subscribe to my channel and i'll see you soon with more legal questions bye
Spiral Matrix
spiral-matrix
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,3,6,9,8,7,4,5\] **Example 2:** **Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\] **Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 10` * `-100 <= matrix[i][j] <= 100`
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row. Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
Array,Matrix,Simulation
Medium
59,921
149
Hello everyone welcome to my channel code story with mike so today we will do video number four of maths playlist i.e. question number four i.e. question number four i.e. question number four when we will explain it then it is ok just to understand the question I am giving the description of the question a little bit but it will seem difficult when you understand it. One question will be very easy. One question is older than simple maths. I had studied the question in childhood. Do maths points online. Okay, this question is one of those questions which you should definitely try. It's okay because its root four is also very easy. It is important, okay, we will do optical SAM, okay, so first let's see the input output and understand what is the question, plot it in an axis plane, okay, I have done it. 1. This is done, you earn. 2. What does this say that how many such points are there? There can be more points, let's take the man here, there will be four Kama Van, it can be anything, there can be many points, it is saying how many such maximum points are there, which come in a line only, like this, look, there is only one. These three are going in the same line. Okay, man, let's take one more point. There would have been one more point here. 2 3 So 2 3 This something happens here. Okay, so the answer is still ours. It would be three because look, these three points are in a line and this banda and now lines can be formed, many lines can be formed, one line will be formed like this, then one line will be formed like this, many lines can be formed. Can be line will be formed like this, one line will be formed like this, many lines can be formed. Can be made but that line itself, look at this line, look at it, three points are going from the maximum number of points, it is fine in this, but if you look at the rest of the lines, like man lo, if you look at this line, then in it there are only two points, one and one. If you look at this line, it has two points, one this and one this. If you look at this line, I have found a line with maximum three points. I have this one, so it is saying tell me the maximum number of points, which is only one. I am available in straight lines, I am available in the same straight lines, it is okay till now it is clear, now let's take another example so that it becomes more clear, so see this is another example, in this I have plotted all the coordinate points. Okay, you have to tell the account of those points, the maximum number of points that can go on one line, okay, so I can make us from many lines like I take, if I make this like Look at these two, okay, make this one, okay, but look at one line, it is very nice, look at it, there are four points, look at this line, it is a straight line, look, there are four points in it, so my maximum answer will be four, okay. You must have understood the question. You had to understand the mentha question. Okay, now let's come to its approach. First of all, I will tell you about the fruits. Okay, I always say that the root force has a lot of importance, especially its interviews. I know it directly. If you make it optical, it won't leave a good impression, either they will feel that you have definitely come at night or you have already solved your question, you should be able to first solve it using brute force, that is this pick. It means that you know your basics, then okay, let's first go to the roots. Okay, this is our example. Let's look at it from a broad perspective. Before starting everything, first tell me, did we study maths in childhood? If any two points are given, X1 y1 and [ X1 y1 and [ X1 y1 and Meaning, it is clear that brother, at least two points will be required to make the slope. Two points will be required to make the slope. Okay, so let's take the graph. This is the graph. Okay, let's take two points. To make the slope, this is my X1 What does it mean if X3, which is the new point that has come, is also in the same line as X1 and X3 is fine of this point and I took it out of this point or I took out the stop of this point and I took out the stop of this point or will it be slow and removed from all slopes. Okay, so we will take advantage of this thing, let's see what we will do, we definitely know what we will do, what I said, we need at least two points, we need at least 2 points, so it's okay, no I = This is okay, one point I Will take from and take one more point j = 0 one more point j = 0 one more point j = 0 j &lt; i plus van se ok after this know what I will do so I got two points ok no And I can get the scope of these two, if I get two points then I can definitely get the slope, then I will get the slope easily, okay what was the slope given / DX is it Y2 -7 / what was the slope given / DX is it Y2 -7 / what was the slope given / DX is it Y2 -7 / Went from 2 points to 2 points so got it now I have to find the third point so there can be many points in the third point which are in the line so we will run a loop for that for this is equal to zero pay attention Dobara Hai Neither i nor jk should be equal. Okay, if it is not then great, we have found our third point. P3, what is mine? If it is out then I will check brother its slope which verse will come out slow wonder score this one was a stall so brother we will count plus 2 points so already we have taken it right, the first point was about I and the second was about point K. If the count is equal, you will keep 2 points, then we have already taken it in a line, for which I have made a slope, because what is a slope, it is made from two points only, so what did I do, after running a loop of 2 points, I got a slope, so that's why The value of the account is fine and as soon as we have checked all the third points and come out, we will check that our final result is neither max of result or count nor at the end we will return the final result, so simple. You see, we have done a very simple thing, we knew that two points are required to find the slope, okay, so let's take each of the two possible points, okay, that too is coming from the slope, meaning. If you have been in the line since, then let's count and see how much A is there. You must be clearly seeing that this is an off and on time solution. Okay, it will be accepted because the constant is not very high, so first reduce the brute by one. Let's code the force and by the way, I have told you the entire story of Puri here, but if I code the steel, then I will tell the story again so that it becomes clear. Again, let's code it, after that we will come to the optimal. Okay, so let's do the first thing. Let's start with the direct solution of the question, then you will understand what will happen. If it is a good question, then first of all what we do is as usual we get n = size and if there is only one point in the plane and then the answer will be maximum one. Only one point was given, there will be 1 point in Maths, ok, our final result, I take zero man, ok, I will start, for choosing the first point, i = 0 i &lt; n i plus, this is i = 0 i &lt; n i plus, this is i = 0 i &lt; n i plus, this is what we have chosen, this is our first point. Na P1 i.e. P1 i.e. Okay Van Mines Sorry Also, the division operator is a bit expensive, so why not use this one. Di / DX, whatever is slow, it should be Di / DX, whatever is slow, it should be Di / DX, whatever is slow, it should be equal. We will get the third point, which is slow. If we take its main, then Di / DX = DX - is. No, you then Di / DX = DX - is. No, you then Di / DX = DX - is. No, you can either write it like this * Sorry DX * DX Dash Didn't do anything simple, cross multiplied it, sent DX here and sent this DX Dash here, ok send it here, so it is clear till now. We will just compare these things, there is no need to divide, there is no need to find out dx. Let's come to our third point, right? 4 and k = 0 k ≤ i Should Should Should not be equal, you should Not be equal, you get zero minus, okay, and what is mine, y3 - y1, okay, X3 and what is mine, y3 - y1, okay, X3 and what is mine, y3 - y1, okay, X3 - You - You can do the slope is equal to something and then compare everything which is mentioned above, but what did I say? You can also do it directly like if, what did I say? Bring here * DX ten and send this DX Bring here * DX ten and send this DX Bring here * DX ten and send this DX there * DX is clear till this point If these two * DX is clear till this point If these two * DX is clear till this point If these two become equal it will end here I will go out from this so I will see in the last how many points I can get Got the maximum and it is ok to do the result. The code was simple, its solution is root four, it will be submitted, look, it is important, now we come to its optimal approach, ok, which will be made in off n square, let's look further, see we come to our I have taken this big example so that it is clearly clear. More points will be better. So look at this graph. I have plotted all the points carefully. It is okay, friend, I thought like I do, I just caught this point. What do I do by holding this point? I calculate the slope of all the remaining points from this point. Okay, what does slope mean? Just a little while ago I told you that Y2 - little while ago I told you that Y2 - little while ago I told you that Y2 - y1 is actually - X1. Can you do it comfortably, friend, if you - X1. Can you do it comfortably, friend, if you take body inverse Y2 -5 DX man, then theta would come out, the take body inverse Y2 -5 DX man, then theta would come out, the take body inverse Y2 -5 DX man, then theta would come out, the A axis of the angle made is okay, keep this in mind, it's okay, let's do this race, just keep in mind what I just said. That I take every point like a pakadunga, now I hold the eye, then I see the remaining points, how much angle they are making with this eye, widow I told you that the angle will be It may be 90°, it may be 90°, it may be 90°, it may be any θ, let's take it, okay, pay attention to it, and from the remaining points, I have taken all of them, okay, now let's reduce one, let's look at this point, checking this point. When I will come out with its angle then something like this line will be formed, okay, let's take the main of this too, okay in the code, don't take tension about this point, let's see about this point, when it will come out, some angle will come out, okay, let's take the main of this, then let's see its angle. So let's take it from the slope, so it also has theta three, then let's see its A, it will also have some angle, here I caught one thing, you know what has happened, it is a very good thing, look, pay attention to how many points are there together with the I. From how many points are making theta vane, there was only one point which was along with the i point whose slope was made theta, then I write here the angle of theta vane in the map and how many points are there in it, the one point is here. Mila and aai toh ahi hai bhai ai toh aapna hai, neither will be two points nor will be a total. Okay, now let's reduce theta 2 one, let's see how much point a was there, you have two points a, the only one for you is yours. There is one more, this banda was found, okay, how many two points are there in theta 2, okay, now let's reduce it, let's check theta 3, don't look at theta 3, if we got three points, then this was banda, and this was banda, got three points, then this was banda, and if That's it, there are three points, the one that is making theta 3 angle, okay, 3 points, those three, one line, all the points, I am checking with the eye, so let me give you how many points I got, two points, okay, so tell me which one. There is such a theta which has maximum points corresponding to theta 3. Okay, this is the maximum points, that is, this is an angle with theta three, this is a straight line, this is the maximum points, how many points am I getting, three points. If we are getting it then it is okay, so right now I must be feeling that three is the maximum, so okay, I will store three answers in the result, if it is clear till now, then it is okay, we have just selected this one, right now we have come. This one was selected, now let's select the rest later and see how many more can be found. Okay, so let's race all of them first. Whatever we have selected here, let's erase all of them. Okay, I will select this one now. Okay, so we will do the thing again. We will do the thing again. Let's find out the angle of all the remaining points from this eye. Okay, so if we take main, we will find this. Okay, if we have found this, then we will take the main of this. Let's go. Okay, this is what I have taken out of this, if I am the main one, let's take the theater, you will come theta, then okay, let's do the account again, let's see brother, how many points are getting in Theta Van Angle, the Theta will make one had come and the other one got this point. If 2 points were found which are in the line with theta van, how many total 4 points were found in theta tu which are in this straight line, what is the angle, if it is not three but four, then the maximum is understood in this way, it is like this, after that the rest of this I After that, I fixed it and from every other point, I will get the angle θ, I am not sorry, if I = G, then you will continue, they will become I = G, then you will continue, they will become I = G, then you will continue, they will become points anyway, no, you have to skip them, ok, continue in I = J ok, continue in I = J ok, continue in I = J and If it is not so, then what did I say that brother, we will calculate theta, right? θ=tan inverse of di / dx. Okay and I will right? θ=tan inverse of di / dx. Okay and I will right? θ=tan inverse of di / dx. Okay and I will write here what will happen to di. Points of Mines Will keep calculating then as soon as I will come out of this for loop, what will I do, I will check the maximum value in this map, then I will keep getting the maximum value which I had run for i=1, then I will keep getting the maximum value which I had run for i=1, then I will keep putting it in my result, which will be the largest value, so what can I say? I am in the for loop, when this for look is over, I will check again what has come in the map this time, ok, I will extract here, find the maximum from map S, I will update the result here. It is clear, it is simple, when everything is over, we will return the result in the last, my maximum store will be there in the result, I am not able to do it, then what will you do It is It is It is okay to take it out, so what I was saying is that how would I give? It was coming out, he gives you the answer, okay, but you are saying, let's do one less, don't we do one less, that too has an approach, I have a getter approach, see what will I do, what map will I take? So I will take the map, here I will store the account in the interior, now the question comes that what will I store in the string, now I will tell what I will store in the string, I will make a string like this, okay give X, whatever it will be, we will convert it into a string by stringing 200 scores. There is a function in C plus, we will convert it to DX and after understanding it, we will make a string, then now it will be unique, each DX and the di are ok, tan is the inverse of if man is lo four and the value of dx is that tu. Okay But how will I store it in the string, I will show it like this, DX and I will give it that is, I will do 2 underscore four strokes, okay, that's great, I will do it like this and I will make the account here okay tell me one thing 10 underscore 4 /2 can also be written like this, it has been tell me one thing 10 underscore 4 /2 can also be written like this, it has been simplified. Now let me take another example. Another such case has been given in which di is given and dx is 4. It is okay that it should be increased for timing. I want it, but I don't know what I will make of it, I will make it like this, I will make the rate 400 and will hit a new entry here, it will get messed up, whereas if I give the rate of 400, see what is coming, then I will give both of them here. I had to increment it but I am making a separate key which will be wrong, okay then I will do one less like this, no matter what comes to me and DX, I will simplify whatever I have, no I will simplify it like You came by four, so to simplify it, what does it mean? What is going? Let's write down 2/1000. Here, write down 2/1000. Here, write down 2/1000. Here, which case was there? The y was 8 and DX was my four. Okay, so reduce it by one when both are. What will have to be done if you simplify the photo? What will have to be done to simplify the photo? If both of them are their greatest comment devices, then divide both of them by you, what will become of you if you kill this, what will become of the van? If it is okay then you are done. DX has become van, okay, comment divider to both of them, who is the greatest comment device, this one also has four, so will you become one and this will become van, so you see, now both of them are from Di/DX, okay now both of them are from Di/DX, okay now both of them are from Di/DX, okay Now both keys are from D/DX, you and Now both keys are from D/DX, you and Now both keys are from D/DX, you and WAN, now I will create keys for both, DX will be added to the same place in the device map, okay, let's do one less, now when we code, there is a simple code to get the GCD. Or there is a normal one called GCD of C+Plus, normal one called GCD of C+Plus, normal one called GCD of C+Plus, it also has steel function, they will do it, anyone can do it, but you should understand that if you are not A102, you want to do it. 8 And if you want to do it instead of 12 functions, then you can also do this. Some people have given this solution in the discussion which I liked. Okay, so let's do one less, right now by coding from both the approaches, I will show it in more lines. If I tell the story by line, then listening to the line, there will be no line extra, which will be the story, it is exactly the same. Okay, so let's see the code, so let's do the solution of the optical process. You knew this and if N Van If yes, then we will return it, okay, the inter result is equal to zero, I had initialized it in the start, then what did I say that I will [ __ ] each and every eye, okay, I will take out that from them, I will take out theta, okay then as much and everyone else. In what will I store each θ account, I create an order map and create an order map, okay, theta will be this and its count will be this, it is clear till now, no problem, now let's go to the remaining points, this is equal. You will put &lt; of zero, see here double Okay, zero means X2 -5's 0, that is, X1, that is, what is X2 - Let's take -5's 0, that is, X1, that is, what is X2 - Let's take out theta, I should say, theta is equal to tan inverse of d/dx so equal to tan inverse of d/dx so equal to tan inverse of d/dx so a tan 2, this is the formula, which means sorry, this sal is like plus, you will pass di and dx in it will come out and give you the angle and what did I say? If the responding count of every θ will keep increasing in the map then it is ok then I have taken out all the keys and updated the map. Now let's see whatever is the maximum, we will update it in our result. So for you and it in this map. I am going and the result is equal, you are the result, sorry, maximum of the result, why do I repeat again, why are you doing plus van, I had fixed I and the rest of the people, I had done plus, okay. Aai too, there was one point, it is included in it, isn't it, like I take one point, and this was one point, so I took out its verse, I took out theta, its ok, how many points do I give, I take only one, isn't one Aai, that's my point. That's why I am doing Plus Van. Don't get confused as to why Plus Van is done. Okay, now A is gone, we will return the result in the end. It was a simple code, it seems like a hard question to read, but actually it did not do anything new, the whole thing. Whatever you tell me, I will submit it and see and let's go. This too will be a great submit solution. I will do it. Okay, everything will be fine here, everything will be fine, this will also be fine, the DX will also be fine, that's what I said that I It will happen, I will string it and take it, okay it is clear till now and what I have said, we will take out the GCD, okay the GCD will have to take out, I will put the GCD in it and pass the DX. What is the greatest common device of both, it will return, okay after that I will create what I told you, I will make the 200 score string a greater comment device plus I am creating a string like this, okay earlier I had done DX, keep it any, it is from everything, it is so simple, let's submit this also and see. I will repeat again that the diagram which I told in the second example is important, I understood it only by drawing the line. Okay, so draw the line and understand it by looking at the diagram. It is not direct, do not expect much from the question because Not much has been given in the question, it is a question of three lines, here is a small question of three or two lines, but you have to understand how to make a diagram, right, that's why the diagram helped me and I understood the diagram and remembered the concept of slope. If you are from school then this will not seem hard to you, right, you just need to understand that it is a slope from Han, which means that the points will be in line, so only the slope has to be counted. Okay, so let's understand this, now you will understand. Bhi Doubt Hota Hai Please Resident Performance Section Ultra Next Video Thank You
Max Points on a Line
max-points-on-a-line
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\],\[2,3\],\[1,4\]\] **Output:** 4 **Constraints:** * `1 <= points.length <= 300` * `points[i].length == 2` * `-104 <= xi, yi <= 104` * All the `points` are **unique**.
null
Array,Hash Table,Math,Geometry
Hard
356,2287
22
Hello Friends Welcome To Step Cornice Suggestion Gender Differences And To The Problem Exam Clear Give And Import Number And You Have To Generate In Thy Soul With Jeweled Prince Is Tomato Pilot Vs Rich Value For Solution For Any One To Three Stitch On Leather Belt Vikas Chaubey Opening Dress and 14 Printers Half Inch Nothing Like This is Not Disclosing The Now You To-Do List of Wealth Abroad Are Now You To-Do List of Wealth Abroad Are Now You To-Do List of Wealth Abroad Are Set to Lord Buddha is Sky Deck Problem and Patiently for Using Back Tracking and Person Vision to Solve Problem Wherever You Get Problem End Drop Problem Sanjeev Ko Diesel Variant Update Combination Of Number And Combination Of Directors And Springs And Second End Dissolution Mist So Let's Jump Into The Solution And We Will Guide You Through With Approach And One Thing That They Have To Keep In Mind While Dealing With Parents and visitors to generate Swift campus team hears pet hero who commits suicide at mid day in the country Kishan so let's see tremendous solution will see so they can have something like result list that and you can find your to-do trucks with that and you can find your to-do trucks with that and you can find your to-do trucks with extra which sea snake that Time When All From Printer And Returns The Result That Bigg Boss Me To Be Kanhpa Hai A Private Point Generate Value And Into Something 0.2 This Me To The Result Of Birth In Something 0.2 This Me To The Result Of Birth In Something 0.2 This Me To The Result Of Birth In A Particular Method In The Valley The Government Will Be You Need A Result The Next Thing You Require Any Medium To You Need To Keep In Mind Next Time You How To Do The Number Turn Off A Message And The Number Picture Required Years In 3505 Result And Number Black List 1000 And 500 Vriddha Skeletin This Benefit Result Will Be Amazed When The Subscribe And Share Effigy Of Having One More Thing Will Need Not Tree Will Be To Play The Thing Which Will Attend List Channel Subscribe The Number Of The Number Off Kar Do Aaj Tak Narendra Dev Paudyal Vedya Mithlesh Dubey And Return Result Notification We Need To Back And Subscribe To The Page If You Liked The Video Then Subscribe To The Number Of Vwe The Number And Subscribe To Hai So Vikas Administration In Not Equal To Will Start From Zero Index In Solid And Absolutely Result open this lineage and open plus one department subscribe and will welcome something what would you would change a time in the schedule subscribe now to receive new 2019 that Sudhir's number double strength that those who sit pinpointed contact number of due regard will se result and this time subscribe do that driver job is particular course will see that you can result in teeth cleaning and mihir opening and closing and has been passed and of me two parts name testing is first year with daughter in law should quit unstri dot Length Is Equal To Themselves Not Till Meanwhile Bluetooth Open And Sons Open 10 And His Three For Example Previous Record Years Will Have Resulted In The And You Will Regret Being Added Next Time Again Off But List Times Of Birth And Time Two In The Mornings And Lifted his argument in the Supreme Court and will return from this particular time can have something like this New Delhi and when they go for during that time he Govind Singh Nikal Paya only to earn profits youth mode and Ravan ne Bigg Boss 230 condition will not Be in the latest have GPS settings show what was submitted by a friend accept some drops of water should be difficult problem basically news dynamic programming also to solve weight reduce condition will remember the last do it voice against the length of long as they celebrate this day is Dynamic Programming That A Concept Can Be Used For This Of Which You Can Use Back To Solve This Problem But On Thursday Common Type Of Videos And Typing Subscribe To Back To The World Channel Different Kind Of Problem Which Involve Verification Number And Character Liquid Opinion Video Mein to dupatta to comment section or chapter 10 videos a
Generate Parentheses
generate-parentheses
Given `n` pairs of parentheses, write a function to _generate all combinations of well-formed parentheses_. **Example 1:** **Input:** n = 3 **Output:** \["((()))","(()())","(())()","()(())","()()()"\] **Example 2:** **Input:** n = 1 **Output:** \["()"\] **Constraints:** * `1 <= n <= 8`
null
String,Dynamic Programming,Backtracking
Medium
17,20,2221
42
so hello coders welcome to my channel and in this video i will be explaining the problem trapping rain water which is a difficult problem if you are doing it for the first time but once you understand the concept what is happening then the problem will become super easy so what the problem is basically saying is that i have been given like a array of heights and this the elements of this height represent the uh height of bars okay so it will represent something like one the height of bar one is this height of bar three is this and so on okay so if this rain happens in on this graph then some water will be trapped between these bars and i have to calculate the total area that is occupied by the water so in this case like six is occupied six units is occupied so you know this entire problem depends on one single concept so that concept is that if you are seeing any particular uh so suppose there are two buildings here i like to say them buildings so the water trap between these buildings will depend on what it will depend on the uh the height of the building that is the shortest okay of these two okay so in this case the water that will be trapped here the maximum level that the water can be trapped here is will be this much the height of the shorter building okay and suppose if there is another bar here okay so what this is what is happening in this problem then how much water will be trapped here it will be this much subtracted by this much okay so let's understand once again so for example how much water will be trapped above this bar so above this bar as it is clear the water trapped will be the minimum of the maximum height of the bar that is present on the left and the right okay so for example on left side the uh highest bar beyond behind this okay behind this the highest bar is of this size okay and the in the right side the highest bar is of the right sides okay this one okay so the minimum of these two bars is this one so it means that the water level can never go beyond this bar okay and so this much water will be trapped and this much water will be trapped but the height of the current building is also something so i will subtract it and i will get the bar okay so for example if you see this building alone okay i will go on to find that what is the highest building uh in the left including this so i will get an answer that okay the highest building on the left including this building is this building itself and on the right also there is no building so including this building the highest building is this only okay so it means that the maximum water that can be trapped on this building is only this much okay that is total this much but the height of the building is also this much so ultimately zero units of water is trapped here so what i have to do is that for any particular building i have to calculate the highest height of the building that is present on its left including that building okay so let's uh compute it as i compute the problem will become more and more clear to you so for example this is the height of zero building okay so zero now the maximum height is one still the maximum height for this bar is going to be one in the left for this bar including this bar the height maximum in the left will be 2 still 2 now the height will be 3 still 3 and 3 okay now my second mission is to find the for any particular building my second mission is to find the highest building present on the right okay so for example for this building of one unit the highest building on the on its right including this building is one okay now for this is to the highest now for this building still two is the highest so this for this building also two is highest for this building of size three uh three is the highest okay for this building three is still the highest threes so you know for every building on the uh left of this building will be the top most building so i just fill three okay now for any particular building what will be the what i said initially was that it depends on the minimum of the highest building that are present on left and right okay so for this building the highest building present on its left including this is of height zero and the highest building on its right is three so i have to choose the minimum okay so i choose the minimum is zero okay so zero and minus the height of this current building is zero for this one the highest building on its left is of height 1 and this right so is 3 so from this the minimum of 3 and 1 is 1 and so i will subtract 1 also here so this now still here it will be 0. now for this one the highest on the left is 1 and on right is three so the minimum of one and three is one and one minus zero will become one so for this building i will get zero for this building i will get the minimum of these two will be two so maximum two units of building can be water can be trapped here and two minus what the height of the current building is one so one unit will be trapped here and similarly uh here like two minus zero so two units height will be trapped here one unit here zero so for example in this case the highest building on the left including this is three and including this is on the right is also three so maximum water level that can be trapped here is of three units so three minus three will be zero here again zero here one zero and 0 okay so if you add this it will become 6. so you know let's uh code it quickly okay so how do i calculate it so to calculate it first i will do is that int n is equal to what n is equal to h e i g h t height dot size okay now i will make a vector of int called lb will be the left building or left bar whatever you say of height n and one building will be vector of int rb right building of height n okay so first i will compute the left highest okay h-e-i-g-h-t-s-t left highest okay h-e-i-g-h-t-s-t left highest okay h-e-i-g-h-t-s-t uh okay left highest so left highest okay so what i will do is here is that for int i is equal to zero i less than n i plus okay if i is equal to 0 basically if it is the first building then in that case what i will do is that lb uh left boundary i is equal to the height of the building itself h e i g hd height i and then i will continue okay continue so and if this is not the case then what i will do is that lbi is equal to maximum of the current height hei ghd height i comma what lb i minus 1 okay so what has hap what is happening here is that for example if you see well i'm filling the left one so basically at this point suppose at this point the current height is zero but its previous one is one so i will choose the maximum one so that is one so that's what i am doing here so like this i am computing the left boundary now i have to compute the right boundary so for the right boundary i will compute from the right side okay so for the right side what will happen is that for end i is equal to 0 i less sorry i is equal to n minus 1 i greater than equal to i plus i minus and then what i will do is that if i is equal to n minus 1 so basically it is it means that it is the first building from the right side so if that is the case then right building is equal to right boundary or building is equal to h-e-i-g-h-t height i is equal to h-e-i-g-h-t height i is equal to h-e-i-g-h-t height i and continue g continue and if that is not the case then what i will do is that rbi is equal to maximum of rb h e i g h t height i comma r b i plus 1 okay so this is so like this i have computed the uh what left and the right ones right boundaries now what i have to do i have to sum up the area so int area is equal to zero now how will i calculate the area is the forint i is equal to zero i less than and i plus okay to calculate the area will be what as i said area plus area above a particular bar depends on what the minimum of h e i g h sorry minimum of l b i and comma r b i so it depends on the minimum height of the building that is present on the left or the right of this current bar okay and from that i will subtract what the height of the current bar h e i g h t height i okay so like this my entire area is calculated and i will return my area so you know that's the code for you so it is accepted and now i will submit it hope everything is fine and it is it has been submitted okay so basically what this entire problem boils down to is that you have to pre-compute the to is that you have to pre-compute the to is that you have to pre-compute the left heights and the right heights so that's the problem for you guys so thanks for watching if you like the video please consider subscribing the video the channel and thanks and have a nice day
Trapping Rain Water
trapping-rain-water
Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining. **Example 1:** **Input:** height = \[0,1,0,2,1,0,1,3,2,1,2,1\] **Output:** 6 **Explanation:** The above elevation map (black section) is represented by array \[0,1,0,2,1,0,1,3,2,1,2,1\]. In this case, 6 units of rain water (blue section) are being trapped. **Example 2:** **Input:** height = \[4,2,0,3,2,5\] **Output:** 9 **Constraints:** * `n == height.length` * `1 <= n <= 2 * 104` * `0 <= height[i] <= 105`
null
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
Hard
11,238,407,756
542
hey what's up guys uh this is john here so today let's take a look at today's daily challenge problem number 542.01 matrix problem number 542.01 matrix problem number 542.01 matrix okay uh pretty straightforward right so we're given like a m by n binary matrix and we need to return the distance of the nearest zero for each cell okay and the distance between two adjacent cells is one right so obviously if the cell itself is zero then the distance for the cell to the nearest zero is obviously zero right so which means we need only need to consider the one scenario so this is the first one right all the other are zero and for one you know obviously this is one because from here in any directions we can have like zero right that's why the answer is one right pretty straightforward and for this one three example two here right so they are zero for this one is one for this one it's also one right because we have zero here for this one is two okay because the nearest zero for this one is either this one or this one and the distance is two right and for this one is one right so that's it and the constraints like 10 to the power of four and there is at least one zero in the ma in the matrix right so for this kind of problem know every time when you see the distance from nearest zero right the world's smallest uh distance uh first thing should always be a what the bfs search right but to do the bfs search uh if we do a drag a brutal force bfs search basically you know like i said we only need to consider one right so let's say for each one if we do a bff search for the for each one then the bfs search itself will take m times n right time complexity and the worst case scenario for each of the one here for each one we're gonna have like this time complexity that's why it's gonna be a n square let's say n big n right and square time complexity n is equal to the m times n right and this will tle so that's why we cannot uh brutal force do the bfs e for each one right so and then how can we improve that you know there is always like uh i think it's a common trick in this bfs search you know instead of search from the uh the source to the target you know we can also search from that target to the source which means that you know instead of searching one to zero we can search zero to one right so the benefit of searching uh zero to one is that you know we can add all the zeros in into a queue right all zero the coordinates of zero into the q and if we do a bfs search here you know we will every time when we reach a one then we can simply we are sure that you know that the current distance will be the smallest distance for this current one the reason being is that since we add all the zeros into this queue and we do a bfs search on all zeros right so which means that we have considered all the possible zero scenario and we simply just need to do the bfi search once and every time we reach one here we simply mark the distance for that one right and in that case you know all we need to do is just we just need to do a one bfs search okay um yeah i think that's it right pretty straightforward and for that i mean let's try to encode that thing you know so we have n is going to be the math zero okay uh and then we have a q right dq so we have directions right we always need to define the directions here one zero and actually after this bfs approach there's another like dp approach that will we'll be talking about later so the beginning everything is zero right excuse me gm we initialize everything to out to zero right so that we don't have to worry about all other zeros all we need to consider is the one case right for the first zero ones the answer will be zero and then uh we also need a visited right for the bfs template so let's populate the q then right for i in range of m for j range of n right basically if mat i j is equal to zero right we add the zero into the q basically the coordinates right and then we also gonna insert into the set okay and then we have distance right for the to maintain the current bfs and then just the bfs template here wow this one is not is that not empty it will this one length of the queue right and we do something later on we do a distance plus one and actually it's always a good habit you know to finish the uh the template first and then you fill in the uh the remainings because if you just if this part is coming along you may have forgot this part right so basically just try to implement the entire template while it's still fresh right your memory okay so now for the bfs right so now we have i j is going to be the q dot pop left right and then we check basically if the iron j is one right if this thing is one then we know okay we can up us update the answer of the current one with the current distance which is this right distant and then the remaining is just like the df the bfs okay so this we have seen this many times so i just quickly called this thing here right so for zero ui m and zero between the zero and n right for the new j and the new i and u j are not visited right and the q dot append this new i new j is visited right dot add this ui and new j okay that's it right i think that's it if i run this should just work okay a few typos there and submit cool so it passed right so this one's pretty straightforward right the only difference is that you know instead of uh do the bfs from the source from one to zero right we do it from zero to one okay and that's that okay so a second one is that you know we can also use uh dp concept to solve this problem now so what is the what does the dp concept mean so for a given like iron for a given cell right if we know all the minimum the nearest distance for all its neighbors right we have up left down and right so for a given like cell if we know all the minimum distance for all its neighbors so what's the minimum distance for this one obviously it's going to be the minimum of all its neighbors right the value so that's basically the concept of dp here and how can we know the neighbors right so for dp right so if we uh traverse this uh grid from top left corner to the bottom right corners you know we can always you know by the time we are at this iron j here right we know that you know the left one and above one right can be the uh we know that you know we can update the current one with the left one and the on the up one because we know if we traverse from this direction right then we know the up on the left one of the current one it will be the smallest right basically we can use that to update this one but if we traverse from in this direction we don't know this part we don't know the uh the below one and the right one so which means that you know with the first uh traverse we can only do a partial calculation basically we're only calculating the half of the of neighbors and in terms of the right one and the below one right what can we do easy right we simply reverse the traverse direction we re traverse it from bottom right corner to the top left corner right so if we traverse in this way now once we have at i and j here you know we already have the values uh for the right neighbor and the below neighbor right so right that's why you know we can simply just do uh this dp calculation twice you know first time from first one is this direction second one is this direction and we update the same like cell twice right when we just get the minimum of above all those four among all those four like neighbors and yeah so that's the idea here and okay i think we can start coding here so dp1 is also kind of straightforward i guess we need this one for the dp uh first one the answer right so now the answer is going to be the system max size because since we're calculating the minimum value right and we're gonna do this initiate everything into the uh into the system max size okay so the first loop is from the top left corner right in n right so first thing first is that you know if the mat i and j is equal to zero right we uh we update the answer of i and j into zero this is obvious right else what else we uh we check the left and up uh neighbor right but since you know here uh there could be no left or above neighbor right so we can do some little check here basically the left is gonna be the answer dot i j minus one if j is greater than zero right else system max right so basically if there's no left neighbor i'll just uh set this one to be the system max similarly for the up one right now this is gonna be a i minus one and j right if this i is greater than zero okay now i can simply update the uh the answer which is i and j with two neighbors right minimum of left and up right and then don't forget to do a plus one right because you know from the neighbor to the current one the distance is one okay so that's that right and then the second time is that which simply need since we already we only consider the left and up neighbor we also need to con calculate the right two neighbors right so for this one we reverse the uh the other okay minus one okay so here we have right and we have done right up and down okay so for this one it's going to be a i j plus 1 but this one is going to be if the j is smaller than the n minus 1 right so this one is like i plus 1 j if the i smaller than the m minus 1. okay but here so be careful we cannot use this one here why is that because we also need to consider this uh the previously calculated a i j answer here right because this one we are not considering the left and up we're only considering the down sorry right and down right so which means we have to do another a minimum of the already calculated neighbor with the current one right okay and then return the answer in the end yep so if i run the code this one this should also work right uh yeah because this one obviously time complexity is also like a big two of big n right because we have two for loop here um yeah i think that's it right i mean it's pretty uh classic either bfs or dp i think bfs is kind of okay things kind of is easy but for dp i think one thing for dp is that you know we have we need to have this sense basically you know uh given like this uh 2d grade right if we traverse in this direction you know we should we can always consider the above and the left neighbor right because you know we have similar db problems let's say we have different values here three two one when we want to know like what is the basically the minimum value if we can we want to traverse from the top from the left top uh top left corner to the bottom right corner right because we can always i mean in if the current uh if the current person can only move either to the right word or down below right that's why you know if we traverse this way we can utilize the uh the dp values of this uh up neighbor and the left neighbor right but in our case for this one actually no since we need to consider all four name all four neighbors right we also need a way to calculate find the right neighbor and the under below download down neighbor that's why we need a second idp for loop in a reverse direction so that we can calculate the other two neighbors yep i think that's it for this problem and yeah thank you for watching this video guys and stay tuned see you guys soon bye
01 Matrix
01-matrix
Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_. The distance between two adjacent cells is `1`. **Example 1:** **Input:** mat = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Example 2:** **Input:** mat = \[\[0,0,0\],\[0,1,0\],\[1,1,1\]\] **Output:** \[\[0,0,0\],\[0,1,0\],\[1,2,1\]\] **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 104` * `1 <= m * n <= 104` * `mat[i][j]` is either `0` or `1`. * There is at least one `0` in `mat`.
null
Array,Dynamic Programming,Breadth-First Search,Matrix
Medium
550,2259
237
what's up guys and they're quite here talking I do technical and stuff on twitch and YouTube check the description join the patreon join the discord and this problem is pretty I don't like to you know I almost want to dislike this one but I'm gonna like I just like everything but I don't know this problem is not very good honestly write a function to delete a node except the tail in a singly linked list given only access to that node so the list doesn't even matter don't just ignore the description honestly basically what you're given is a node and you want to delete the node so and there's always a node after that node so oh my god it's so dumb so look there's a list four or five one nine so you're given five you're given the node five and you want to delete node five so you have to basically turn node five into node one and then that's it and then you delete it and then that's it so to do that if you're deleting the node that you're given you have to say ok you have to basically just set make it the next node so you say note Val equals node dot next dot Val and then node dot next equals node dot next and then that's it that's the whole problem that is you know pretty much it I mean I don't know what else to say you take five in you wanted to leave five so you just turn the five into a one and then you delete the one so you just turn the node into the next node and then you just delete the next node by removing reference by setting this done next to this dot next which is you know nine by setting the five to nine look at this solution for this it's kind of funny and just for reference here you can look at this chart if you wanted to and then look at this that's so funny it's stupid everyone is so mad at this question it's kind of funny dude yeah I mean that's it I mean you give it an ode you want to delete it you set the next to the next and you delete the note after it set the value so let me know if you have questions about this you probably shouldn't and if you do you need to really evaluate what you're doing on leak code because it gets a little bit harder than this guys so thanks for watching I will see you in the next one and I appreciate all of you goodbye
Delete Node in a Linked List
delete-node-in-a-linked-list
There is a singly-linked list `head` and we want to delete a node `node` in it. You are given the node to be deleted `node`. You will **not be given access** to the first node of `head`. All the values of the linked list are **unique**, and it is guaranteed that the given node `node` is not the last node in the linked list. Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: * The value of the given node should not exist in the linked list. * The number of nodes in the linked list should decrease by one. * All the values before `node` should be in the same order. * All the values after `node` should be in the same order. **Custom testing:** * For the input, you should provide the entire linked list `head` and the node to be given `node`. `node` should not be the last node of the list and should be an actual node in the list. * We will build the linked list and pass the node to your function. * The output will be the entire list after calling your function. **Example 1:** **Input:** head = \[4,5,1,9\], node = 5 **Output:** \[4,1,9\] **Explanation:** You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. **Example 2:** **Input:** head = \[4,5,1,9\], node = 1 **Output:** \[4,5,9\] **Explanation:** You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. **Constraints:** * The number of the nodes in the given list is in the range `[2, 1000]`. * `-1000 <= Node.val <= 1000` * The value of each node in the list is **unique**. * The `node` to be deleted is **in the list** and is **not a tail** node.
null
Linked List
Easy
203
120
hello everyone welcome to our channel code with sunny and today in this video i'm going to talk about the problem triangle of lead code index number is one two zero and the problem is of medium type of lead code okay so basically this problem is one of the good problems of or you can see the one of the good problems of the topic related to dynamic programming and this problem is also the most frequent problem being asked in interviews okay so let's discuss this problem now and we will together find out the best solution of this problem given a triangle array and we have to return the minimum path sum from top to bottom okay so basically we have been given a triangle type orientation of an array and we have later on what would be the minimum cost for going from top to the bottom of this triangle okay for each step we have the following moves either we can move to an adjacent number of the row below that is if you are an index at i on the current row you may move either to the index i or index to the i plus one to the next row okay so let's understand this with the help of diagram that is let's say you can you are at index or you can say with a number at two you can either move to this three or you can either move to this four okay so in spite of that you can let's say you're at numbered at this five you can either move to this one or you are going to either move to this eight okay or let's say you are at this position that is the value at six you are either going to this four or you are either going to this one okay so these are the basically moves that you are going to do that is either move directly to the current column into the next row or move to the next column of the next row okay now what will the minimum path from top to bottom that is from going from this to this end of this you can say the end of this row that is the last row okay and we have to find out that minimum cost okay so let's look over the constraints because sometimes constraints might be helpful in figuring out what would be the best solution of this problem that this triangle length is going to vary up to 200 so we can have an o of n square solution and the values lie down to 10 power 4 and then the follow-up could you do this follow-up could you do this follow-up could you do this using only o of an extra space where n is the total number of rows in this triangle okay so let's find it out what with the best solution of this problem and analyze this problem with the help of examples and diagrams okay so let's move further okay so basically we have this we have been given this triangle but we can convert this triangle to this you can say oh and into an matrix how we are going to do that okay so basically you can see for this two i have placed this at position zero comma zero and for this three four i placed next to this 2 such that it would lie as a number of columns should be greater than the number of previous columns plus 1. okay you can see it will have two columns and similarly for the next one it will have three columns starting from you can see i have placed the elements like 6 5 7 from the left most side that is 6 then 5 then 7 and it would become an into n matrix okay now converting this to an n into a matrix is just simply like you have you are just figuring it out what should be the best solution by just modifying this statement because if you are representing this triangle with the help of this matrix it would become easier to understand and interpret the solution of this problem okay so what would be the okay so let's find out what are the possible moves after converting this triangle to this you can say this and into n matrix okay so you can see from this two you are going to either to three or to the four so you can see you can move to this either directly to the same column or to the next column okay from this current row to the next row okay so if this is done so let's figure it out from how what are the most possible from three and four you can also see from three either we are going to six or either you are going to the next column of this next row okay so if you are at four either you are going to the same you can say the column uh the row just to next to this one and with the and on the same column and if from four you can also go to the next column the next row okay so overall if you are at i and j let me write it down you can either move two either you are going to move from i plus one that is to the next row and the column remains same or you are going either move to i plus one comma j plus one okay so one of the solution of this problem that is either you are first going to convert this to a matrix or just understand this that i am just interpreting a matrix that is a 2d matrix of size n into n okay and just finding out the solutions okay so i think i have here to done some mistake it should be like three okay so now uh what we are going to do is just we are going to just modify my current you can see there's a triangle okay so there is a triangle given like that okay you can say a vector of vector anti-triangle it is just a 2d anti-triangle it is just a 2d anti-triangle it is just a 2d representation of this triangle okay so i'm just going to modify my this triangle the representation how i am going to modify that let's understand that okay so it is just basically a dynamic programming approach it's called the dp now you can see if we are at the second row that is this is the first row and we have this second row and it lets let's say we are at this element that is element three so for this element three we can either come from uh okay so how we can come to this element three okay so for coming at this element three we can either come to this element three directly from this one that is for the uh row just to evolve to this row or let's say we if you are at this three then we can either come to this uh that is for the row just above this row but the column is just less than 1 you can see this is out of 1 out of the bounds of this matrix this is not possible okay so it means that we are at this 3 then we can always come from this above 2 that is to the row -1 low minus one and the column row -1 low minus one and the column row -1 low minus one and the column remain same that is j remains same okay if i'm just talking about this three and what about say let's say we are at this five okay so how can we come to this file we can come to this pipe by coming from the row just above this row that is to be i minus one and the column remains same okay and now there is one more chance that we can come to this pipe and what is this chance that is from three okay so for i and j in general i can write we can come from i to j from i minus one always uh columns that is number of pro row number should be always less than one to this current row and we can always come from this i minus 1 to j or we can always come from i minus 1 comma j minus 1 okay if this j minus 1 is going to be valid okay for this triangle okay so just i'm going to modify my this triangle two day representation that is given to us starting from i equal to one if i have zero based indexing that is this is zero and this is one this is two starting from i to one and it goes up to i less than n where n is the number of rows of this triangle okay so for every i comma j and where j is always going to be like j should be less than equal to i okay so for every i comma g i am just going to check it out if what should be the minimum cost coming from either from this position or from this position okay so let's let me write out let me write down the dp relation that is dynamic programming relation for this 2d representation of this matrix okay so let me write it down okay so let me just write down dp of i j or you can also write it as so let me write you know let's say i have this triangle that is given to us that is i have just mentioned this vector of vector anti-triangle that is vector of vector anti-triangle that is vector of vector anti-triangle that is given to us i am going to just modify this triangle okay so how we are going to do that let's say this is named as t okay so i have this t of i j should be equal to that is plus equal to my current value that is if i'm if i want from uh what are the total distinct values that the total different ways i can come to this file either we can come from the row minus one and the column remains same that is from this or you can also come from this row minus one comma column minus one that is from three to five okay so i am i can come from like a minimum of since i need to find the minimum cost for reaching to the bottom of the cell at each time i need to take the minimum cost obviously okay so i can come from minimum of this t of i minus 1 always number always row minus 1 because i am i'm always just trying to come from this previous row and my j either remains same that is to the from the same column of the previous row or i can come from t of i minus 1 or to the previous column that is j minus 1 okay and if i take the minimum of these two values i must need to add to my current value that is 5 what is the minimum cost for reaching to my current cell okay so if this is done for the entire cells of this triangle what should be our answer should be like minimum of all the cost that we can have up to reaching all the cells of this last row okay because since you focus on this the question minimum path from top to bottom okay from top to bottom it has not been specified that bottom if we are reaching at the bottom of this triangle at which cell we are going to end we can end at we can end up to any cell that is either we are going to indent this cell and sell with value or sell with value one or sell with value eight or sell with value three but we don't know va which will give us the minimum cost either we are ending at this current cell okay so i need to take the minimum of all the values of dpo let's say dp or you can also say the t of n minus 1 is the last row and t of i up for all the values of i ranging from this 0 to n minus 1 for all the columns okay that is 4 1 8 3 this should be our answer ok now you can also see there is a one follow-up follow-up follow-up uh that we can use this o in of an extra space okay one thing that should be kept in our mind that in internally related questions uh we must not change the actual input data that is what i have done over here is that i have modified this triangle vector or you can say 2d representation of this triangle and i've just modified this vector to just to find out my answer without using any extra space but in interview related questions uh we are not allowed to modify the input values so we must either to solve this problem we must make either the 2d matrix what we grade for figuring it out the answers or we can in this case like in this 2d matrix what will be the my space complexity extra space it would be like o of n square and this is going to be washed okay so we must try to figure it out like how we are going to minimize the space complexity that is extra space so i am going to just uh just tell you uh how we are going to minimize this extra space without modifying my input values that is in the triangle 2d representation of the vector and what is the minimum extra space complexity that is i'm going to just tell you of an extra space and is basically the number of rows which is actually the follow-up that which is actually the follow-up that which is actually the follow-up that have been given to us at the beginning of this problem okay because you could use to do solid and open extra space yes i can solve okay let's try to figure it out what would be the o of an extra space solution how we are going to modify my entire problem statement and entire problem scenario of this problem to figure it out the open extra space solution okay so let's move further to find it out okay so here is one the dp relation that i have written over here so if you focus on this dp relation that is it only needs the values for ansi for answering for the particular row you just need the values for the answers for the previous rows okay that is if you need to answer for this row that is for the cell with three and four i just need the answer for this previous row okay so rather than maintaining entire 2d matrix for without modifying my actual values we just need to have a linear size array that is answer of let's say answer is the array and what is the maximum number of rows or you can say maximum number of columns that we can have it should let's say it is n that is here you can see here it will be four that is answer of course that i need to maintain okay so let's try to just answer the uh you can say fill the row and columns okay for the cells okay that is you can see here i will have maximum of four okay so if you are at this cell with value 2 what is the minimum cost for coming to this top most to this my current so that is from 2 to 2 it should be like only two okay and let's try to just answer for the some more cells like uh okay so let's let me fill it down like two okay let's try to answer for this three what is the minimum cost for coming to this three we can always come from this two to this three and what is that cost you can say two plus three it is going to be like 5 okay so let me just erase this stuff and let me just write it down the value equal to 5 okay and what is the minimum cost for this coming from or coming to this 4 you can always come from two to this four okay and what is that cost you can easily see the cost should be like two plus four six okay yeah one thing that should be noted here that uh for answering these two queries uh what is my previous answer vector that is still not modified you can see it is still only 2 and for entering this 4 i just need this value 4 okay now what is my new answer vector that is present over now you can easily see my new answer vector is nothing but you can say new answer vector is going to be modified and it is nothing but 5 and 6 let me fill out the values you can see this is 5 and this is 6 and let's try to answer for this row if we are trying to answer for this row let's try to answer for the cell with value six you can always come from cell with value six to this cell value that is from this three okay so you can say what is the minimum cost for coming to this rate is five and five plus six is eleven okay so the minimum cost is 11 and what is the minimum cost for coming for this cell here if we will have five i think i've just messed it up and what is the minimum cost for coming to this file minimum cost for coming to this will be either we are going to go from three to this five or we are going to go from this four to this five okay so minimum would be like minimum of this three cell with values three and four that is minimum of this five and six and minimum of five and six is nothing but five and cost of this current cell is five it should be like ten okay and what is the minimum cost for coming to this seven cell you can always come from this four to this seven okay and what is the minimum cost for coming to this four it is nothing but 6 and 6 plus my current cell value it is nothing but 13 okay so my new answer vector is this one and you can easily see i just need the values for the previous row that is only 5 and 6 okay so this gives me the idea so just rather than maintaining an entire 2d matrix we just need a exactly linear row let's try to fill up the values with the help of previous row that we have okay so let's move further to the coding part to analyze how this can be implemented in a best way okay so let's move further okay so i have already submitted the codes let me look over the code and let's try to just uh figure it out what i have done and let me explain over that okay so let me open up the two accepted code that is one that is i just modified with the input values which is not actually valid interview related questions okay so you can see i have this triangle vector uh the triangle representation of 2d matrix and you can see n is going to represent the maximum number of rows that the this triangle representation can have and starting with i equal to one and it goes up to less than and because of first row it is not required to just modify the first row because it is actually the beginning one okay and it holds only one while that is you can see it holds only value equal to two okay and let's try to just fill up the values what is my current minimum let's say anti-max and what is the minimum anti-max and what is the minimum anti-max and what is the minimum i'm just trying to fill out what is the minimum value for coming to this rather than just adding the values okay finally you can see i have just added the value of triangle of yj plus equal to the minimum that is minimum cost from which we can come to this cell and minimum would be like minimum of this my previous row and the column remains same and minimum of this previous row and column minus 1 that is j minus 1 if and only if j is going to be valid you can see if j is going to be less than i minus 1 and j minus 1 must be going to be greater than or equal to 0 because you can see this triangle is has the orientation like you can easily see every time the number of columns is going to be increased by one okay so i just need to take care of that okay so if j is going to be less than i minus 1 and j minus 1 should be greater than or equal to 0 okay so j when j is going to be less than minus one his condition is going to fail the condition will fail only when we are at this position you can this seven and this three okay so because if you are trying to pitch the exactly previous row it is not going to be valid okay and j minus 1 is greater than equal to this condition will fail for the just uh first column okay so finally and what should be our answer minimum offer for all the values for the last row okay or any of the columns can be gives us the answer for this last okay so just i need to find the minimum value just so that i have returned the minimum value for the last row and for any of the columns okay so this will have a runtime bits of 90.75 of cpp will have a runtime bits of 90.75 of cpp will have a runtime bits of 90.75 of cpp submissions okay so let's talk about my another implementation that is nothing but maintaining a vector of size and without modifying my input values because interval in interviews you can you cannot just modify the interview value and this is going to be invalid okay so i'm just maintaining rather than maintaining the entire 2d matrix as just maintainer you can say answer vector of size and linear array and this answer of 0 is nothing but triangle of 0 comma 0 and this is the which is the first value or first l value of the first row okay so just have iterated for i equal to 1 and goes up to i less than n or i just i am just trying to fill up the values from the back side okay so because if you try to fill up the values from the back side you can easily see for filling the values of truth for this cell i just need the values for this previous one that is answer of i minus 1 okay so if i have just modified this uh that is if i just recall filled up this values of this cell i just know i just don't need this cell anymore okay so if you try to fill up the values from the beginning of this cell you can see the values are getting modified okay so if you are trying to fill up this value just i need the values of this one and this one okay so if just i have just filled this value this cell value is going to be modified okay that's why i'm trying to fill up the values on the back side okay so without getting an error okay so just j from i and j is greater than equal to zero and j minus one if j is going to be equal to i my answer would be like j minus 1 plus the current cell value and if j is going to be exactly 0 the only way that i can come from is answer of 0 plus triangle of i j minus the current cell value otherwise we can have the two possible ways minimum of answer of j and answer of j minus 1 plus triangle of i j and we have to return the minimum element and finally after traversing all the rows we'll have the values for the last row okay that is minimum element of this one okay just i'll just write down this will also have an accepted code okay so if you have any doubts do let me know in the comment section of the video and i will ask the viewers to like this video share this video and do subscribe to our youtube channel for latest updates thank you for watching this video
Triangle
triangle
Given a `triangle` array, return _the minimum path sum from top to bottom_. For each step, you may move to an adjacent number of the row below. More formally, if you are on index `i` on the current row, you may move to either index `i` or index `i + 1` on the next row. **Example 1:** **Input:** triangle = \[\[2\],\[3,4\],\[6,5,7\],\[4,1,8,3\]\] **Output:** 11 **Explanation:** The triangle looks like: 2 3 4 6 5 7 4 1 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). **Example 2:** **Input:** triangle = \[\[-10\]\] **Output:** -10 **Constraints:** * `1 <= triangle.length <= 200` * `triangle[0].length == 1` * `triangle[i].length == triangle[i - 1].length + 1` * `-104 <= triangle[i][j] <= 104` **Follow up:** Could you do this using only `O(n)` extra space, where `n` is the total number of rows in the triangle?
null
Array,Dynamic Programming
Medium
null
86
hi guys welcome to tech geek so today we are back with the daily leadput challenge problem that's a partition list that's a lead code medium question lead code medium 86 so before beginning i'd like to request you to please like share and subscribe to my channel if in case there are any queries do let me know in the comment box queries related to interview experience queries related to upcoming placements or any interview question i'll be there to help you out and there's a link to my linkedin channel as well as my telegram channel do for that because for the upcoming placements it's not possible to create a video on each and every uh placement or opening so i directly share the links there so that's beneficial specifically for batch of 2022 and 2023 for full-time possessions 2022 and 2023 for full-time possessions 2022 and 2023 for full-time possessions and 2024 for internships okay so let's see this uh they say that we have been given head of a linked list and a value x okay the question says you have been given the head of a linked list and some value x now you have to pass partition this list in such a way that all the nodes less than x should come before the nodes greater than or equal to x okay so if the value is greater than or equal to x they come towards the right and if they are less they should come before okay that's towards the left you should preserve the original relative order that's a constraint that you have been given you should preserve the original order relative order to the nodes in which in each of the partitions so let's see its particular example is given one four three two five this is the original list this is the head that we had and the value that's given as three see this one it's less yeah so it's it will stay here now four it's greater so three it's greater or equal so four should be followed by three now two is less so it will come before again two is less and then 5. so this is the relative order is also followed and sorting part is also done ok now there are two methods to do this actually it's one of the same but how to implement this somewhere a two method process so i'll just explain you via this we had this necklace present with us and just change some values and then you try with it okay this is what you need okay now this is the list that we have been given and let's say the value that's given to us sorry the value that's given to us is 2 now the partition has to be done based on two so you guys must have heard a very common problem that's a common approach that's two point okay initially we are having a head here so we'll take two pointers one should be before after all less or more whatever you want to give the name so let's take it before and let's take this as after before means the ones that are coming in front that means they are less and after means the ones they should come towards the right okay that's what we have to do so we'll iterate this particular list and check now initially both are null in before now first we'll check is the value node value less than 2 or less than x yes before you will point this and now the four will point towards the next obvious will be done again come to two is it less flow why it's greater or equal to will come in after now your head is seven is it less no it's greater again bring it here now you know again it's less so we'll add this here and this one again point towards the null and in the same way we have three now once we are done with this the iteration is completed okay this will again point to that now how we will combine it the combining uh the combination should be in such a way that wherever it is before us okay and uh please keep in mind that the first node of this before should have some head or some pointer initially itself so that we don't have to go back again and get the point okay that would be for the first one the next of before okay should point towards the head of after let's give it two okay so what we'll do we'll join this in such a way that next stop before should point towards the after head so that's how our list will be completed and that's what the relative answer should be okay that's what is required in this now and yeah as you can see we are going in a specific order and checking all the nodes one by one so order of n is all that's required in the time complexity and space complexity is order of one okay now if you see this you can do it in another way also you can take a stack instead of making two pointers you can take a star and you can input these in a stack that would also be uh you can see you can say a good approach towards this problem you can take two stacks stack one stack two stack the four stack after any naming or you can take one by one you will insert them okay and you know in stack there's one thing last and first out okay so that's what would be the best thing okay why see last in let's uh go with the stack process here okay one is a stack for before that stack one and one is a stack for after we know last in and then first out remember this step so first one it's entered two should be here i'll just be a quick one seven in stack we push it above again it's first and then okay that's how you'll get now last and first out that means this should be a head and the next of this should be this so what we'll do we'll pop them we'll pop this element and the next of this element should be the head right that's what should be done now let's see this approach i have the first approach was easy so that's how i have done so if your head is null okay first of all don't go off with the process sorry don't go off with the solution because you have a process of two pointer also and that's quite easy to code the stack one could be still a little tricky for those who are not aware of this so that's why i'm holding this one now see this head is null again do nothing create two stacks now until here does null traverse the list and push them if they are left and push it and stack one otherwise push will start now head should point towards nine until stack two is empty we will go in the opposite direction stack two will pop the elements and then again head will become pop so that's what we are going in opposite direction now once stack two is there because you are building it in the opposite directions okay somewhere we are taking it this way this is how we are building so now we will come to stack one and do the same things and then eventually we will return the so the process is again the same going towards all the n also order of n is our desired time complex okay now if in case you feel there's something missing out or there's something you'd like to know please let me know in the comment box and do share it with your friends and your colleagues juniors seniors whosoever requires this thank you
Partition List
partition-list
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`. You should **preserve** the original relative order of the nodes in each of the two partitions. **Example 1:** **Input:** head = \[1,4,3,2,5,2\], x = 3 **Output:** \[1,2,2,4,3,5\] **Example 2:** **Input:** head = \[2,1\], x = 2 **Output:** \[1,2\] **Constraints:** * The number of nodes in the list is in the range `[0, 200]`. * `-100 <= Node.val <= 100` * `-200 <= x <= 200`
null
Linked List,Two Pointers
Medium
2265
814
in this video we will solve a binary tree problem and uh in this tree we have just one and zeros so all the values are either zero or one so this is not just a binary tree but even the numbers are binary and here we have to prune some of the trees so by prune we have to chop those branches or chop the entire subtree rooted at that node so we have to chop or prune multiple such sub trees from this original tree so if any subtree so this is root node and there are many children and this is binary so at max two children and if let's say this is 0 this root node and all its nodes are 0 and this may be part of a bigger tree so we have to prune this entire tree we have to remove cut this entire sub tree from the original tree and we will have multiple such sub trees we have to remove all of those but let's say if we have some node coming from root which was one then we have zero then we have 0 and this side we have 1 so we cannot chop out this entire tree since there was a 1 here at this point so this entire subtree cannot be pruned but if you go further you see that this subtree has only zeros so this can go away but this will remain so this will be converted to zero one zero 1 so the same way let's see it formally on a bigger example so this is the root and the function is prune tree i am writing pt here and we pass root node pointer to root node and it returns a node pointer so by node i mean tree node so this node will have as usual left a pointer to left a pointed to right and a value these three values so how we can do it so uh first i would say that if you know how to write a traversal of a binary tree recursively be pre-order recursively be pre-order recursively be pre-order post order or in order if you are familiar with traversals and you know how to write them recursively you are good to go that is the prereq for this understanding this lesson so you see that the same way when we are wasting a node we call it recursively on its left children when this call terminates it visits all the nodes and then it terminates back to the calling node then we call on the right node it again recursively the same thing will happen here so it will call on the left this subtree and then this will visit a lot of nodes every node in the left sub tree and terminate back here then we will call right it will edit all the nodes in the right subtree and terminate back to here and then this entire thing will terminate back to the root so this is how it works this recursion the same concept is here so we call proon tree on the main route so what it will do it will pass the same thing on children and now it's it passes this function p t and 0 so i am not writing here pointer but this 0 denotes this root node so we called p t of 1 let us give them some numbers also if you want this is node 1 this is node 2 node 3 node 4 5 and 6 nodes are there so we called pt 1 so this will call pt 2 this node whose value is 0 and it will be rest assured that once this call terminates it would have already chopped out or pruned all such subtrees which are completely zeros so this is the job of now this function call to take care of how this will happen at a management level what you do if a task come to a senior director he forwards it to different directors under him then the director delegates the work to managers respective managers and the managers delegate those work to different leads and then they are just passing whatever comes to them from upside and they are passing it to people under them and now it's your job how you get that work done it's your job i'm not bothered the same thing it here it is here this job came to prune tree to the root node it forwarded it to its children so in this case first it will call on the second node which has a value of zero now it will say that you it's your task how you do it i just want all those subtrees rooted under you don't have to worry about other branches just worry about yourself and anything below you so tree is starting from you just give me the result this will again call its left child so this will call on pt this node is for pt4 now it does not have a left or right side so what it will do if we reach a leaf if it's a leaf it will be the zero one since it's a binary the values are binary not binary tree means at max two children but the values are also binding so now we are at a leaf now root now leaf itself is a subtree with just one node so if it's 1 we will not chop it if it's 0 we will remove it so it will return null to the calling function so this leaf belongs to some parent we don't know what its values the child does not know what is the value of this calling function but the child says that if i am one i will return back myself the pointer to myself because i will exist if it's same condition but in this case the node is zero so the node sees that i don't have left or right so i am at the lowest level i am just responsible for myself and i am zero so i need to be chopped off so it will return null to the parent so this is the main difference here so if a leaf node is 0 it will return null since it has to be cut if a leaf is 1 it will return the pointer to this node itself so if this is n it will return n now this level is handled and if it returned null and there was no other children then this itself becomes a leaf because this is now gone but if it return the node itself now this is safe because there is something hanging from me so i am safe i cannot be chopped out because i if i am chopped out this one will go away now this is safe and so what we are doing here let's say we are at a node n so what we are doing n dot left equal to proon tree of uh this n dot left remember this function returns node star that is this function is called on a subtree rooted at root and after this call finishes it returns the root of the prune subtree if there is no node it will be null implicitly so it will be either null or it will be some value similarly n dot write equal to p t and right so these two calls we are making in each node are precisely within this function and what else we are doing if so we are blindly calling it so maybe that it's already leave the note for which we are we have entered this function so it will call it for n dot left which will be null and dot right this will be null so if the root is null then return so what will happen the call if it's called for a leaf it will call pt and left that is pt null so it will return null so its left will be null it was already null so for leaf these pointers are not changing anything then what else now after these two calls are made we will check that if n dot left is there or not or n dot write is there or not if any of the its branches survived if let's say for this mode this node here node 3 if any of these two branches survived that is there was somewhere one in between and luckily that branch survived luckily or unluckily i don't know for example in this case node three this will be chopped this will return null here so after the end of this these two lines its left will be null so then it will check what did one return so one return this pointer to the node itself pointed to node six so now one of this condition is true so this node is safe it will not check its value irrespective of whether it's in 0 or 1 even if it's a 0 it will exist because 1 is below it and it survived so blindly it will return the pointer to itself to its calling function so if this is the case return root whatever is the node it was called on but so if none of them was uh not normal so if both of them was null then it will go past beyond that this return will not execute so we will check if root value is dot valve is equal to 0 then return null because there is nothing below it and this itself is 0 so it has to return null back to the calling function but if it is not the case we will return node itself that's it as simple as traversal so what will be the time complexity just like traversing a tree we are traversing all the nodes so pt1 it will call p2 pt2 will call on this node 4 and then it will start returning and it will look at its right side nothing so it will return now it will return back this node will again call on right subtree it will come on left subtree it will call on its children which are null then return then this will call on its right subtree return so it will visit all the nodes once so time complexity is o of n where n is the number of nodes in the tree and what is space complexity it can be of the order of height because if we have a very long tree all the nodes are in just one line left or right then this will call this one and so on and all of these are lying in the call stack so the worst case can be in this scenario when the tree is not very far from balanced then it will be often if tree is fairly balanced roughly log in then at max at a given point of time in the stack we will have login nodes but we will take the worst case and it's on for both time and space now let's write the code for this in c plus java and python it should be very simple sometimes these recursion based code these are written in three four lines but it takes you some time to run through an example and then understand for yourself how this is working so that's why i said you should be familiar with writing recursive traversal no matter whether you're writing pre-order post whether you're writing pre-order post whether you're writing pre-order post order or in order and you should also understand how the nodes are getting traversed when you write that traversal code so if root is null return null pointer otherwise root left equal to so remember that analogy we are just delegating the work we received to our subordinates people under us so people under this node is left and right children and they will get the job done for you don't have to worry so after the this pruning action if any child survived any subtree below it survived then the node also survives we return the root pointer don't need to compare value if it goes this execution goes past this line that means this line was not hit so both were null so both are null then you survive only if you are non-zero if it's zero return else return root and that's it very simple now let's try on our example so this expected matches so let's submit and the solution is accepted and you can check whether where you stand so it's where other people stand so mostly most likely people will come up with this owen approach and this i don't think we can do better here now let's write this in java and python also in java we have just null ptr and the java solution is also accepted finally we will write it in python and the python solution is also accepted
Binary Tree Pruning
smallest-rotation-with-highest-score
Given the `root` of a binary tree, return _the same tree where every subtree (of the given tree) not containing a_ `1` _has been removed_. A subtree of a node `node` is `node` plus every node that is a descendant of `node`. **Example 1:** **Input:** root = \[1,null,0,0,1\] **Output:** \[1,null,0,null,1\] **Explanation:** Only the red nodes satisfy the property "every subtree not containing a 1 ". The diagram on the right represents the answer. **Example 2:** **Input:** root = \[1,0,1,0,0,0,1\] **Output:** \[1,null,1,null,1\] **Example 3:** **Input:** root = \[1,1,0,1,1,0,1,0\] **Output:** \[1,1,0,1,1,null,1\] **Constraints:** * The number of nodes in the tree is in the range `[1, 200]`. * `Node.val` is either `0` or `1`.
null
Array,Prefix Sum
Hard
null
474
hello everyone welcome to another episode of coding decoded my name is sansa today i am working as technical architect sd4 at adobe and here i present day 23rd of may lead code challenge the question that we have in today's banks and zeros this question is based out of the concept of dynamic programming for all those who have been associated with the channel may know that we have already solved this question in the month of april 2021 and the like says it all the comments says it all it was a long video coding part was worth going for i have solved this question using two approaches one bottom-up approach other bottom-up approach other bottom-up approach other top down approach so the question is of 3ddp the question is based out of 3ddp concept and if you have never solved any question of 3ddp then this problem is for you it also the underlying concept is same as the knapsack problem so i would urge you guys to go through the knapsack video first and then come back to this one because it will get give you a better understanding of the concept also i have an announcement to make dynamic programming is one of the toughest concept to understand when it comes to dsa to help you guys i have created coding decoded dynamic programming sd sheet so if you have an interview scheduled very soon and you don't know how to revise dynamic programming then use these questions as a subset and it covers a variety of problems that are asked in interviews 2 dp longest increasing subsequence of 1dp 3d dp and i promise you guys after going through these set of questions you will get the confidence that you are ready to go in the battlefield of interviews and in case any questions arrives of dynamic programming then you will be able to solve it up i'm attaching its link in the description below so do check this out also in case if you have any doubt you want to ask anything from me 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 let's wrap up today's session i hope you will you're gonna enjoy the other two videos thank you
Ones and Zeroes
ones-and-zeroes
You are given an array of binary strings `strs` and two integers `m` and `n`. Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_. A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`. **Example 1:** **Input:** strs = \[ "10 ", "0001 ", "111001 ", "1 ", "0 "\], m = 5, n = 3 **Output:** 4 **Explanation:** The largest subset with at most 5 0's and 3 1's is { "10 ", "0001 ", "1 ", "0 "}, so the answer is 4. Other valid but smaller subsets include { "0001 ", "1 "} and { "10 ", "1 ", "0 "}. { "111001 "} is an invalid subset because it contains 4 1's, greater than the maximum of 3. **Example 2:** **Input:** strs = \[ "10 ", "0 ", "1 "\], m = 1, n = 1 **Output:** 2 **Explanation:** The largest subset is { "0 ", "1 "}, so the answer is 2. **Constraints:** * `1 <= strs.length <= 600` * `1 <= strs[i].length <= 100` * `strs[i]` consists only of digits `'0'` and `'1'`. * `1 <= m, n <= 100`
null
Array,String,Dynamic Programming
Medium
510,600,2261
252
you guys this is just has everything going this in this video it's again about an easy problem 2 5 2 meeting rooms or it could be an array of bending times intervals consisting of start and end times uh-huh you tell me if a person could uh-huh you tell me if a person could uh-huh you tell me if a person could attend all meetings like there is a meaning from 0 to 30 there's a meeting from 5 to 10 then this is a overlapping right so it's this person could not attend our meetings of course you can just acquit as some specific time and join another that's not allowed here and for 710 to file for it's not overlapping so it's possible Wow so the basic idea I think it's obvious we just to check if there are some overlap intervals right to check if in an interval there be to check all intervals I think we better sword up like we have into like this if we sort it we might may have something like this right if there's no overlapping it would be something like this and then or something within another interval so we could after we sorted we could just a check if the first one and the second one if they have this have interested have overlap if not we just if not then I mean the first one we could just pop it from the way right yeah so let's do it so the idea is sword first loop through the intervals and check against a previous one the mean adjacent intervals well so actually we don't need to pop the array just to use the index to check against the previous one cool so I think we need to you two functions only one which is overlapping interval one interval to how can we do how can we be sure that they are overlapping well the only case that they are not and without being would be interval one's the end of interval one is smaller than interval to start right or interval zero to one start is figure than interval twos and this is only two cases okay one that they're not overlapping so we return the fourth value of the of it so we're not this overlapping works now then we need to do what we sort right so we sort in double by aligning their start index start number so sort a and B we return a zeros will then be zero so it will be sorted with the start I'm cool now we traverse to the move through the intervals start from the one right because the first one will now not have any overlapping with the previous one I suppose then I plus if it's over diving with a previous wall then we just return false it's uh we cannot attend all the meetings and then we return true right I think this should work it's an easy problem let's see the time complexity know what true ah I see so the equal is not overlapping right separate time we've sorted so it's a log n log N and plus the before loop here so it's this interval it's n log n space we don't use any extra space so it's constant cool that's all for this one I hope helps see next time bye
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
1,065
they hello there so this week I'll be practicing the question of topic of try so to start since easy I got this question times 65 index pairs of a string so we have a text string which can potentially I guess be a very large text of corpus and we have a list of words that we want to search for the occurrence inside this big corpus so for every word inside this list of words we want to find the starting and ending index of that word inside this text so we ask the result we return a list of pairs of indices where the each in each pairs of industry is corresponding to word in the word list that inside this big text so as an example we have the story of leaf code and me we won't find that the starting and ending index for three different words story fleet and decode so story start with three and that index seven so that's the trouble that the Paris indices with 307 year means so the second example the Texas a baa-baa the search words are a B a and a baa-baa the search words are a B a and a baa-baa the search words are a B a and a B so the first word ABA happens twice here 0 2 and 2 4 so that's those two notice that the indices are returned in this sorted order inside this list so that's that so just imagine that the very first kind of solution would just be for every word inside this word list we're gonna do the fine operation final all kind of operation and for with between this world and the text corpus so in the worst case it would be the total length of the text corpus multiplied by the total length of the search term that's the worst case would be very bizarre input like a all the way that's the text and the search term is just a lot of a and a single be there so when we do the matchings between this war search engine that the text in the only we're only in the rear end will notice that it's not a match so that could potentially be those two less multiplied together so that's the worst case and but that's the worst case for the for a single word search so for how many words we have we can potentially have how many of those so the total run time complexity which is speed those three different factors multiplied by together in the worst case so that's a no so idea a better solution is to use try what we would need to do is to create a tri data structure with all the words we have so for every location every position in inside this search text we just going to do a try search try to traverse inside this tri data structure use that the starting text as the starting charactering the different location as the initial character that we use to traverse inside this try so let's say that the maximum length of the search term is L the total number of characters for the search engines and the total run time if we use try it's going to be those two multiplied together so we've dropped the number of words inside the word list pretty much so that reduced the runtime complexity in theory by a lot but in practice I guess this search turn this search are easily parallel bore paralyze ball and on the reasonable number of words we want to do this search I guess it doesn't really matter that much but in theory using a try could be faster and the thing about that the search is that if we just search word a word by word inside this text and it's called the space but if we use a try the try takes up the space as corresponding to the lens of the characters inside the searched and the length of the searched and multiplied by the number of wars we have so that takes some space but you can argue that if the input word list that can be put into memory or something like that there try could be also put into the memory so we're treating basically trading space for a runtime complexity so yeah that's pretty much the knowledge so just gonna try to put this off the first thing first is true title code up of the try data structure I'm using a actual object to try node so basically the try node is a character to use a mapping between character to the try nodes objects so the benefits about using this default dictates basically it's like a in place so it's constructing a new try new object with the value provided yeah it's creating the try note object as the value and has that to associate with the inserted a key if the key is not inside this hash mark so it does two things it could potentially do two things at the same time sorry I think I have the misspelled it's children so the node will also have a termination flack meaning that it's the end of the world so just going to call this end of war so that's the definition for the individual try nodes inside this trying to destructor the tree data structure so the constructor for the try it's basically we create a root node inside this tree that's just going to be our empty try node and we what do the just Adam on insert function yeah so here we're basically for every word we want to insert into this tri data structure for we enumerated over the world character by character we try to find the create the character to try nodes Association so just building out the tri level by level node my little note by note according to the character ordering inside this word the end at the end of the word we turn on the boolean flag indicating that there is a word ending here yeah so that's pretty much that let me just do a quick quality of life in province here so this thunder contained over eyes the was this implementation we can use the English or to test do we have a character as the key inside this children so we don't have to call node or children in the later code also maybe something like a good item yeah so basically just checking and getters for the stuff inside the hashmap all right so let's code the actual solution for this so obviously the first thing first is to populate this try and before the word inside this word list I was just going to insert that into the try so the total run time is basically K multiplied by L time and space k is the number boards how is the maximum ends of words yep so is that we should we just started the search so for this contains try search crew team function you basically treat use this eyes character inside the search text the text I as the entry point into the try and just try to look for the J's locations and see do we still have a match do we still have match inside the try and along the way we'll collect all those IJ pairs and puts push those onto the solution so that's gonna be for J Ranch maybe she is a while loop so I will need to use very initially the J is equal to I so we are looking at the single character there we got a note from the Tri start out the root and just try to a traverse a deeper and deeper it's a end off word we just push this IJ pear onto the solution yeah that's it that seems to be pretty much the majority portion of the curve let me do some quick checks okay so on the trial structure we define a tri node which is every tri node contains a character to find out its mapping so it's the character that's following the current try node inside this tri data structure so this character to node my thinking allow us to traverse inside this tri data structure for every tri node we also have end of world flag indicating a end of a actual word so that we know when we should push the I J pair on to these solutions here is just the contains and gate item makes this text you know character you know checking a little bit slightly less the code I guess but it doesn't really matter the ignition it initialization for the Tri class it's basically just to have an empty root node so there is no character nowhere sovereigns are inside area the insert is for the forgiving word we try to process this character by character if there is not a note with that character we try to create that and use that know to use the newly created Association to go further inside the strike data structure once we reach the end of the word we turn on the boolean flag so it looks okay here for the try Clause so let's look at the actual code here we initialize the try so it's empty right now then what we do is to insert all the words one by one inside this tri data structure the wrong time for this is the number of words multiplied by the length of the word then we have another iteration this loop iterating over the all the index inside the search term so this is the order of M multiplied by L so the L part comes from the Tri search because when we started with a character we use that as the entry point and just try to go as far as possible as deep as possible inside this try until we either at the leaf node run out of the leaf node or we've reached the end of the search text or that the character is no longer a value pass inside this try data structure until that so the maximum is pretty much the length of the turns we have so it's gonna be up usually be upper bounded by like this condition here so once we reach the end of the maximum length of a node inside this try this will be about invalid so this will be a null pointer and yeah so what we would do is to just to keep travursel character by character and whenever we find we have a end of word flat it would push the idea pair onto the ocean so doing this it's guarantee that the IJ pairs inside the solution as in the sorted order so we don't need to do a second pass of sorting no selves okay so I got the problem nothing being pushed onto the solution what's the reason for that okay I was thinking about using a for loop when I was coding this function but in the end I changed my idea and decoded up my loop so for that reason I should increment the did Jake by myself so let's see if this time it works yeah himself okay all right so it's working it's using more memory than other people's most majority of other people's solution so I guess they used a search but the wrong time is okay I guess yeah so that's pretty much it with the try I think that round I think Cerreta call you know Cerreta was speaking is should be less compared to do the blueforce word search you know search for the words position word by word inside this text and the code is easy to understand as well yeah so that's this question I guess use try it's definitely not easy level but and also doing for the amount of code you had to come up with maybe over cure for this question but I think in the case of the lot of repetition in the crops and the word search tan similar that this copy could be used for guess so that's the discussion today
Index Pairs of a String
binary-string-with-substrings-representing-1-to-n
Given a string `text` and an array of strings `words`, return _an array of all index pairs_ `[i, j]` _so that the substring_ `text[i...j]` _is in `words`_. Return the pairs `[i, j]` in sorted order (i.e., sort them by their first coordinate, and in case of ties sort them by their second coordinate). **Example 1:** **Input:** text = "thestoryofleetcodeandme ", words = \[ "story ", "fleet ", "leetcode "\] **Output:** \[\[3,7\],\[9,13\],\[10,17\]\] **Example 2:** **Input:** text = "ababa ", words = \[ "aba ", "ab "\] **Output:** \[\[0,1\],\[0,2\],\[2,3\],\[2,4\]\] **Explanation:** Notice that matches can overlap, see "aba " is found in \[0,2\] and \[2,4\]. **Constraints:** * `1 <= text.length <= 100` * `1 <= words.length <= 20` * `1 <= words[i].length <= 50` * `text` and `words[i]` consist of lowercase English letters. * All the strings of `words` are **unique**.
We only need to check substrings of length at most 30, because 10^9 has 30 bits.
String
Medium
null
64
so you want to know how to do minimum path sum well you came to the right place so let's get to it so it says given an m by n grid filled with non-negative numbers find a path from non-negative numbers find a path from non-negative numbers find a path from top left to bottom right which minimizes the sum of all numbers along its path well what is it without them uh putting words between well what uh what happened to the what's up with these leak code descriptions so aside all of that you can only move either down or right at any point in time find a path from the top left to the bottom right moving only down or right so they show here that to get from here to there the shortest sum is one plus three four plus one equals seven which is smaller than one plus one two plus four six plus two eight oh that's already bigger than seven so we need to find once again um the smallest minimizes so we want a min function those who know my videos which is maybe hey one person know that i like writing a max and min function when available um and the reason is it gets me into the groove and it doesn't take long so that's it for the min function then what exactly are we doing well we know that this is one is the smallest path for everything that goes let's see that's the minimum that you could get here because it's the minimum of one plus right which does not exist and one plus down which does not exist but this two over here while the minimum to get to uh with one included and we can't have any values below is two plus one which is three so you already know that it's three here and at any given point it's the minimum between whatever it is plus right or whatever it is plus dowd so at this point we take the minimum from this plus this or the minimum or this plus that's what it would be here the minimum we could get is two because it could only go down one plus one equals two so at this point you would have to choose between two which is that or uh 5 plus 2 which is that which is 7 or 5 plus and this would be 3 at this point this one would be 3 because that's the smallest you could get from here so 5 plus 2 or 5 plus 3 it would choose five plus two and here this the shortest path as of this point would be seven so you get the idea it's another dynamic programming problem okay let's just do a little um just move the cursor there a little sanity check if the grid is empty then return zero you can't get anything after an empty grid then we want to immediately start working out of this box over here so if uh let's see now so we're gonna loop going like this from down here then here and at each point we're always gonna have our value so if uh let's see now so four inch i equals grid dot size minus one i bigger or equal because we're going down then 0 i minus we're starting at the top which is really the bottom this is an abstract representation for int j equals grid 0 dot size minus one again all right also j bigger equal to zero add j minus okay so at any given point um we're looking for the min between the two paths if they exist so how do we check if they exist well okay so let's see if they don't exist so let's see though if i plus one um bigger than uh sorry equals grid dot size that means we've already gone overboard and um j plus one equals grid zero dot size that means we have nothing to play with and so we do nothing so let's just assign it to itself grid let's just have uh yes i know that's redundant and i could have done it the opposite direction um actually you know what we don't need that let's just save that for last let's start here so if i plus one um smaller than grid dot size and um j plus one smaller than grid zero dot size so that means we have two values here that means grid let's see now grid i j equals now it's the minimum my min of grid i j plus grid um what is this i plus 1 j or right after that comma or um or plus i j plus one okay don't try this at home kids okay now if so if only one of them exists if i plus one smaller than grid dot size and let's see though what is this and j plus one equals grid zero dot size so we only have the i plus one available b dig going down grid i j equals uh then we don't need any min here so it would be this over here okay else okay sorry we wanted else if um okay so here we want the contrary so if i plus one equals grid.size and j plus one equals grid.size and j plus one equals grid.size and j plus one smaller then we take grid i j equals actually we could just do plus equals so we want that j plus one there okay yeah so that's good over there and actually let's just do that same nomenclature over here um let's just make that a little cleaner here okay so we have that and if they're both out there that actually we don't need to touch anything so at the end of all this um we should return grid zero and if this miraculously works i'd be surprised huh okay we have a winner well that's it folks have fun
Minimum Path Sum
minimum-path-sum
Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. **Note:** You can only move either down or right at any point in time. **Example 1:** **Input:** grid = \[\[1,3,1\],\[1,5,1\],\[4,2,1\]\] **Output:** 7 **Explanation:** Because the path 1 -> 3 -> 1 -> 1 -> 1 minimizes the sum. **Example 2:** **Input:** grid = \[\[1,2,3\],\[4,5,6\]\] **Output:** 12 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 200` * `0 <= grid[i][j] <= 100`
null
Array,Dynamic Programming,Matrix
Medium
62,174,741,2067,2192
1,742
let's solve lead code 1742 maximum number of balls in a box so the question can be a little confusing but what they exactly saying I'll explain here so they are saying that you'll be given a low limit and a high limit okay and you need to take the sum of go from low to high okay and take the sum of all its digits okay for each number you need to take the sum of all its digits and see which uh which sum of digits has the highest occurrence in that range so I'll word it out here you need to find maximum occurrence of sum of digits of numbers between low limit and high limit I'll explain this with an example let's take an example between 21 and 33 right so we have taken all the numbers between 21 and 33 inclusive of 21 and 33 so and now we'll see the sum of their digits right so sum of 2 + 1 is 3 how digits right so sum of 2 + 1 is 3 how digits right so sum of 2 + 1 is 3 how many times it has occurred so far one time right sum of 2 + 2 is 4 how many times right sum of 2 + 2 is 4 how many times right sum of 2 + 2 is 4 how many times it has occurred so far one time sum of 2 + 3 is 5 how many times 1 sum of 2 + 4 + 3 is 5 how many times 1 sum of 2 + 4 + 3 is 5 how many times 1 sum of 2 + 4 is 6 1es sum of 2 + 5 is 7 happened once sum 1es sum of 2 + 5 is 7 happened once sum 1es sum of 2 + 5 is 7 happened once sum of 2 + 6 of 2 + 6 of 2 + 6 is 8 how many times once some of 2 + 7 is 8 how many times once some of 2 + 7 is 8 how many times once some of 2 + 7 is 9 how many times once sum of BL 2 + 8 is 9 how many times once sum of BL 2 + 8 is 9 how many times once sum of BL 2 + 8 is 10 how many times once sum of three and 0 is three and so we'll add it here at three so now three has occurred twice right so far the maximum occurrence was 1 now the maximum occurrence is 2 okay sum of 3 + maximum occurrence is 2 okay sum of 3 + maximum occurrence is 2 okay sum of 3 + 1 is four right I'll add one more to four same the maximum occurrence is still two same as three sum of 3 + 2 is 5 I'll add same as three sum of 3 + 2 is 5 I'll add same as three sum of 3 + 2 is 5 I'll add 1 to five sum of 3 + 3 is 6 I'll add 1 to 6 five sum of 3 + 3 is 6 I'll add 1 to 6 five sum of 3 + 3 is 6 I'll add 1 to 6 so what is the maximum occurrence 2 okay there are four numbers four sums such that the maximum is two the occurrence is two so we'll return two in this case so that's how we need to solve so how am I going to solve this simple first of all we need to store this sum right we need to store this sum and the count how many times that sum has appeared in that range right so how am I going to that do that we can look at one of the constraints which will help so constraint is that low limit and high limit is going to be in the range of 1 and 10 to 5 is nothing but 100,000 right one with five zeros so 100,000 right one with five zeros so 100,000 right one with five zeros so 100,000 mean the maximum that can be the 100,000 mean the maximum that can be the 100,000 mean the maximum that can be the maximum sum that can be is 5 * 9 right so 5 * 9 that is 99,999 right and the sum of 5 9 is 45 so 99,999 right and the sum of 5 9 is 45 so 99,999 right and the sum of 5 9 is 45 so the maximum sum can be 45 right so I can create an array of length 45 and considering the index to be the sum of the digits okay so index one would be where I'll store how many times some of digits has been one index two will be where I store how many times the sum of digits has been two and so on till N9 uh till the sum of digits is 45 right so 0 to 45 how that is a array of size 46 right so let's do that so I'll create an array I'll call it count it's of size 46 I'm taking 46 because there is index zero also so index 0 to uh index 45 gives me 46 places and then I'll take a maximum I'll maintain a maximum and I'll keep it as zero as then when I'm updating count I'll update my maximum also so that I don't have to go through count again then I can start by it trating from left to right from low limit to high limit + one because I want to reach high limit + one because I want to reach high limit + one because I want to reach till high limit I'll do plus one because the last one gets skipped in range function and then I'll create a variable s where I'll store the sum of the digits of that number so starting with say 25 if the low limit is 25 I'll store the sum of 25 then 26 27 and so on then I'll figure out what is the I'll take out the digits and add it to some how will I do that I'll divide I by 10 until it gets to zero and I'll keep taking the remainder and adding to the sum which is s in our case so s+ i% I person 10 which gives me a i% I person 10 which gives me a i% I person 10 which gives me a remainder if after I divide I whatever the remainder is that is the last digits last digit of I and I'm adding that last digit to the sum right after that I divide I by 10 so it takes off the last digit then again the while loop will run the second last digit which is now the last digit I'll take that and add it to the sum again divide it by 10 until highest zero okay this will happen which means I have got all the digits in s now I'll add increment the count at s by one okay because I found a sum uh so I'll increment the index of that sum and count by one okay and I'll update my maximum also maximum will be Max of earlier maximum and the current sum okay current uh sums occurrence how many times the current sum has occurred right so the count and maximum whichever is the max ma Max will be updated with that and finally I'll return the maximum okay I could run this or I could have also done instead of if I didn't have to do this maintain the maximum I could have removed this part and I could have just taken a Max of count even that would have worked right so let's run and see that works I submit it 224 millisecond beats 100% of users it 224 millisecond beats 100% of users it 224 millisecond beats 100% of users with python so our solution is the best solution according to this front time I could have simply maintained maximum as well that would have worked also so I submit it and see that works and that works too all right so that's how you solve the problem 1742 maximum number of balls in the Box see in the next video
Maximum Number of Balls in a Box
widest-vertical-area-between-two-points-containing-no-points
You are working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number `321` will be put in the box number `3 + 2 + 1 = 6` and the ball number `10` will be put in the box number `1 + 0 = 1`. Given two integers `lowLimit` and `highLimit`, return _the number of balls in the box with the most balls._ **Example 1:** **Input:** lowLimit = 1, highLimit = 10 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 2 1 1 1 1 1 1 1 1 0 0 ... Box 1 has the most number of balls with 2 balls. **Example 2:** **Input:** lowLimit = 5, highLimit = 15 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 1 1 1 1 2 2 1 1 1 0 0 ... Boxes 5 and 6 have the most number of balls with 2 balls in each. **Example 3:** **Input:** lowLimit = 19, highLimit = 28 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ... Ball Count: 0 1 1 1 1 1 1 1 1 2 0 0 ... Box 10 has the most number of balls with 2 balls. **Constraints:** * `1 <= lowLimit <= highLimit <= 105`
Try sorting the points Think is the y-axis of a point relevant
Array,Sorting
Medium
null
1,905
alright guys welcome back to study planner theory day three problem two okay in this problem we have two great grade one and great so and we want to return the number of islands in greece that are considered as some islands okay for this island this red one is somewhat of this island because we can add one here and then have this island and for this one this is not a sub island because there is no island here and in here this is assam island for this island and this is also somewhere for this island okay now let's try to call this we need a helper to make it fs and first let's check if we are out of boundaries so if e is smaller than zero or is smaller than 0 or equal to the name of grade 2 and or this is equal to the length of credit two zeros and let's add another check if our grid is equal to zero in this case this is immediately a surveillance so we'll return to otherwise let's make our various name sound for surveillance let's make it true and let's check if our grid this is should be equal to zero and check if our grid is four so zero if it is so the island in the great so it's bigger than the island in the big one and it's not it's it cannot make a sub surveillance from it so it's false and let's make the grid so because to zero to let's make an affinity loop then let's call this function again for all the names so let's make sub equal to a helper plus one and sub let's take care of the neighbors plus one minus one okay this one and finally some zone i guess that's it now let's return the sum of grid so if it is equal to one and if the helper is true so in this case let's make four a range of length of grid so for the same range of the land of grid zero i guess that's it let's run the code english so okay this is shown before what's wrong with this line i'm not closing our line so type a mistake again okay let's submit and the water i hope this video was useful for you and see you soon hopefully
Count Sub Islands
design-authentication-manager
You are given two `m x n` binary matrices `grid1` and `grid2` containing only `0`'s (representing water) and `1`'s (representing land). An **island** is a group of `1`'s connected **4-directionally** (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in `grid2` is considered a **sub-island** if there is an island in `grid1` that contains **all** the cells that make up **this** island in `grid2`. Return the _**number** of islands in_ `grid2` _that are considered **sub-islands**_. **Example 1:** **Input:** grid1 = \[\[1,1,1,0,0\],\[0,1,1,1,1\],\[0,0,0,0,0\],\[1,0,0,0,0\],\[1,1,0,1,1\]\], grid2 = \[\[1,1,1,0,0\],\[0,0,1,1,1\],\[0,1,0,0,0\],\[1,0,1,1,0\],\[0,1,0,1,0\]\] **Output:** 3 **Explanation:** In the picture above, the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands. **Example 2:** **Input:** grid1 = \[\[1,0,1,0,1\],\[1,1,1,1,1\],\[0,0,0,0,0\],\[1,1,1,1,1\],\[1,0,1,0,1\]\], grid2 = \[\[0,0,0,0,0\],\[1,1,1,1,1\],\[0,1,0,1,0\],\[0,1,0,1,0\],\[1,0,0,0,1\]\] **Output:** 2 **Explanation:** In the picture above, the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands. **Constraints:** * `m == grid1.length == grid2.length` * `n == grid1[i].length == grid2[i].length` * `1 <= m, n <= 500` * `grid1[i][j]` and `grid2[i][j]` are either `0` or `1`.
Using a map, track the expiry times of the tokens. When generating a new token, add it to the map with its expiry time. When renewing a token, check if it's on the map and has not expired yet. If so, update its expiry time. To count unexpired tokens, iterate on the map and check for each token if it's not expired yet.
Hash Table,Design
Medium
null
1,642
Hua On On On discussing those symptoms, subscribe to this video channel, first and second part of A Hua has been done, anti second, we have become the account of villagers, that in the past, this is life, 427 60 to 0.5 inch lashes, 0.5 inch lashes, 0.5 inch lashes, now we are the first here. But to reduce jumping, keep in the condition that if you are on a tall building and you have to pay the bill on the ground level, then no one will feel like doing anything below. If you are on this building, you can add it from any building, it is not so. Now what is the condition between these two that how many trees can be used, how much land can be used like on two How many leaders can it take to go to the face, then how many can we write, then what is the distance of the writer on the other side, five means seven - 250, so whether five means seven - 250, so whether five means seven - 250, so whether we use fabric or we use a layer, if we have to walk on a building. So, in the condition that we use, which is our life, we have to send 11 players first, if any building is below then there is some building above it, if it is above us, then we can put this, then you can put it. What is the condition for breaking height of I - Height of business. As many as one I - Height of business. As many as one I - Height of business. As many as one tree will have to be planted. It's okay. What is the meaning of 'and'? tree will have to be planted. It's okay. What is the meaning of 'and'? tree will have to be planted. It's okay. What is the meaning of 'and'? One letter will do. No matter how many heights are placed between them, it is okay. Now do it in our question. We have to use these bricks and ladders additionally to reach the maximum intact that we can reach, like we live in this example, I will send this one in the next pic, jump down and keep it down here. From above here we are doing ok so I have 28 - 21 so I said I have installed the bristol etc pipe reached here now the tree at what time my zero balance account is finished because we will put the fabric ok zoom from now on Is there any light on 76065? Look, I have relations, so I will put it here. Okay, if I put it here, then subscribe. In this video, you can think what is New Delhi, but we know from here, we can buy bread from here. And From here we can also take a lighter. Okay, so we can take bread or a lighter. We can decide the means. At this point, unless we know anything about the father, if we do not know anything about the father, we cannot decide them. Can, okay, he can, we Brett Lee, I am caressing the letter MP, he can, take the letter, then the tree, answer is needed that something like this, those who do it will use it in it, frog is one thing is sure, what is the objection that whatever min For the file, we will use the tree we have like this is fine, then for the pipe, if we use whatever is minimum, then for those which are of larger height, we have the lace, it is fine like There is a lot here, so we will use it. Okay, so this means that we are going to use it for them, it is made only for us to use them, so if we give it from here to here, it will take us a minute. Added five to us, then we, there is nothing here, meaning, the difference between these two, Baikunth, something like this, then where is the phone, so I did not do anything in it, see the meaning, we worked hard, these things needed three fives, 315 kilometers. If we had thirteen Dikshuddhi, our work would have been done. Even if we had three leaders, our work would have been done. Okay, so look, now we have to do it, except that yesterday I got time difference, I did it, I was appointed in ad minutes, top Oh, now I am the next time and I said that now I have a letter, it is the latest one, it means that the size of my chip has also become England, all the chips are of size one, it means that I had an increment that the size of and It means I have an increment side, okay now I have a size on the key, this means I have an increment like this and I have a letter one, so I can do an increment like this letter system, okay now I have an increment free. I added it here, it's okay, please remind me. I saw that it has been included in the science syllabus. Means, we can join two increments with one letter. Okay, but which withdrawal will we do, which are the beaches? I mean Catherine, we will do rickshaw. Sure, because we have sufficient trees, so this friend, we will check this internet facility again, look at this, first of all, this mixed typing of digits is fine, now I have done this, now I have subscribed to the recipe So I have done this. Subscribe to the channel Channel hua tha jab saif to pipe will go in it or if it doesn't then let's fold it [ fold it [ fold it Jhal hua tha Ajay ko Jhal Okay ok Priority is there The calling team is that Loot this medical search Om hey equal that run these three from Ireland let's take it jhal that let's take it here also let's take it acid subscribe plus app ire call ok so come here first take out in difference Do the folder where you live, your height is the first if it is different, do n't forget to subscribe, it is going to clarify, whatever is the topper in the cheap, means whatever is the minimum in Dortmund, if it is not mine, yes brother, I will do it, okay, nothing else like this. So just from here I started the airplane mode start length, are you worried about why nodi is often looted, the principle is given priority, what is the score at a time, after reading the answer, why is the net running slow, is this debit so normal? What work has been done, first of all, store it for all the people who trust us, Air Force, once we take it, I put it in our Play Store and stop it, all the people who trust me, if there is a difference, then I like it and comment, if it is practiced. The size goes more than the letter, enter the tree pointing to it, which is the minimum one, it was the media, the back does not superheat, due to which the tube means returns of five zodiac signs, if it reaches the end, then add the answer exactly, okay, do it.
Furthest Building You Can Reach
water-bottles
You are given an integer array `heights` representing the heights of buildings, some `bricks`, and some `ladders`. You start your journey from building `0` and move to the next building by possibly using bricks or ladders. While moving from building `i` to building `i+1` (**0-indexed**), * If the current building's height is **greater than or equal** to the next building's height, you do **not** need a ladder or bricks. * If the current building's height is **less than** the next building's height, you can either use **one ladder** or `(h[i+1] - h[i])` **bricks**. _Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally._ **Example 1:** **Input:** heights = \[4,2,7,6,9,14,12\], bricks = 5, ladders = 1 **Output:** 4 **Explanation:** Starting at building 0, you can follow these steps: - Go to building 1 without using ladders nor bricks since 4 >= 2. - Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7. - Go to building 3 without using ladders nor bricks since 7 >= 6. - Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9. It is impossible to go beyond building 4 because you do not have any more bricks or ladders. **Example 2:** **Input:** heights = \[4,12,2,7,3,18,20,3,19\], bricks = 10, ladders = 2 **Output:** 7 **Example 3:** **Input:** heights = \[14,3,19,3\], bricks = 17, ladders = 0 **Output:** 3 **Constraints:** * `1 <= heights.length <= 105` * `1 <= heights[i] <= 106` * `0 <= bricks <= 109` * `0 <= ladders <= heights.length`
Simulate the process until there are not enough empty bottles for even one full bottle of water.
Math,Simulation
Easy
null
6
hello friends today let's solve zigzag conversion problem we are given a string s and the integer number rows we want to convert this string to our zigzag like string and it has the num has the number rows of rows so let's see this example what is the zigzag it just we want to write a z so it's z here so how to get this uh shape we just try to go down and if we have four rows we change the direction we go up and then until we reach the row zero we then go down and go up until we exhaust all the characters so what's the possible way to solve this problem i think one straightforward solution is that we try to build a 2d array we want we can calculate how many columns we can have and then we just fill this zigzag string into that 2d array this is one possible way how about you may also want to find some rules here like you may want to count how many characters between this p and i is five so how can we get these five we have two characters between it we have one character which is empathy character here so maybe you want to try to find some rules to build this zigzag string but is that unnecessary no we can just situate this process to get this zigzag string like i said before we can go from here and go down until the row 4 we change the direction and we go up and when we reach row 0 we change the direction and we go down so we can use this way to build our result because finally we just want to return p i n p l s i g which is characters under same rows we they will be together so for this example we can first build a string builder list why because for stream builder we can append the character there so what i mean here is that we can build a string builder a list which we can call it rows a new array list then for um yes we want to know how many number of rows here so rows will so for each list here we can add it and we add a new empty stream builder so that's it so in the end how to get a result we can also get a stream view that we call it a result a new stream builder then we iterate the every stream builder in this rows result will append this sb which has the return result 2 string so that's it so how can we get this rose information we just simulate this progress so for every chart in the string chart array we have to know the current index then we decide whether we should change the direction so we have the curve row at first it's zero so when the curl is in the zero because this is when we go from up down to up when it's zero then we should change the direction or the current row is number rows minus one it's uh we reach here so we should change direction to go up then we have changed the direction so maybe we can call it uh um change direction um maybe going keep going right keep going first is force so in here if we reach these two boundaries we the going will change the direction okay so here if oh no it's not if because we want to also reflect this change direction to the current row if it's going right it's going then the row index should uh increment by one if it's a change direction we go up then we should minus one the row index this is the row index so i think we can just can go down just follow the same name can go down can't go down this is just circle can't go down okay can go down this is the direction how about we should put a row scatter the current index right current row and append this c so you may wonder why at the very beginning is false because let's see if you set it to true then it will go from or go into this if expression so then can go down will become force but if it's force here we should minus one that means it should go up that's wrong so the reason why we you we initialize either to force is to we want to use this if condition collectively so if you we set it to false then we go to this if condition it will become true if it becomes true it can literally go down so it's plus one so you should notice here okay is that enough no we also should think about the special cases we first get the an equal to a star length we have two special cases if the s will just have one column what does that mean it's just if the number of rows greater than so it will be one column the opposite if we only have one row if it only have one row that means the number of rows equal to one both of case it will just re return this original string so that's the edge case you should notice okay i think we have finished it thank you for watching see you next time
Zigzag Conversion
zigzag-conversion
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); **Example 1:** **Input:** s = "PAYPALISHIRING ", numRows = 3 **Output:** "PAHNAPLSIIGYIR " **Example 2:** **Input:** s = "PAYPALISHIRING ", numRows = 4 **Output:** "PINALSIGYAHRPI " **Explanation:** P I N A L S I G Y A H R P I **Example 3:** **Input:** s = "A ", numRows = 1 **Output:** "A " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. * `1 <= numRows <= 1000`
null
String
Medium
null
509
in this uh part we're going to do fibonacci number question 509 of leaked code so for fibonacci numbers uh the first two is are given here and we need to calculate the rest so each one would be dependent on the previous two um the usual normal way is recursive but i'm not doing recursive because that's going to be too much of complexity so we're going to do uh something else i'm going to use a dictionary that's what comes to my mind and i'm going to say let me think uh let me say edge map equal to the dictionary and then um i want to loop through this for example if you have number three let's say number four n equals to four it would output the value of the uh fibonacci number which uh of number four which would be three which because two plus one is three so um so it's basically dependent on the previous one so you have to like make the dictionary until that particular number so the first thing i want to do before looping through is that we know that two numbers in the dictionary uh the first two numbers that will be zero equal to zero and one equal to one yeah so it's like f zero is equal to zero f one and crystal one we're going to append it again and again until we get to a particular end here uh with uh considering that uh we have these two already in so we have a loop here for let's say uh num and range uh we want to do from 2 to n plus 1 and y in plus 1 because this is uh not inclusive here so it won't um if we do n it won't uh get n it won't take n here so we're trying to take n here by making n plus one exclusive so this is the loop and what we're going to do for typing the um edge map numbers is that we want to say so how do we calculate it the first thing is we get actually let's say i here or idx um yeah so idx edge map of idx that would be -1 -1 -1 plus edge map of idx minus 2 and that would give us the value so this will be a value here for now i'm just going to say val and then you might want to make it more efficient in terms of cooking so val equals this math idx minus one plus math idx minus two so if we have uh two here uh it would add zero and one together then what would it do it would say uh i want to create this number inside the etch map that would say edge map of n um actually idx equal to that so that would give us the added another element to the edge map and return after that edge map of again here this will give us the result but i wanna instead of this i want to just say this equals to this eliminate this part yeah so that will make it uh more efficient in terms of coding here let's run this and see if that works yeah it worked so in return etch map and it means like after we have created the whole dictionary 0 1 2 3 whatever then we can just use the dictionary and just return that and you know that going over the dictionary is of complexity uh all of one so that would help us a lot and if we submit this let's see what happens you can see that it's very fast and it accepted it so that's how this will be solved
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
100
hey there everyone welcome back to lead coding today we are going to solve the question same trees so i was getting so many requests to start with the topic trees but before we proceed with this topic there's another important topic that you should know you should be comfortable with the topic recursion for those who don't know recursion there's a very compact video in the description that video covers the basic theory and few important questions on the topic so you can go and watch that and once you are done with this you can proceed with trees so let us read what this question says given two binary trees write a function to check if they are same or not two binary trees are considered the same if they have the same structure and yet they have the same values in the node so for example we can see that these two trees if we overlap them with one another they are going to be identical if we look at these two trees although the values in the trees are same but if we try to overlap them then we will find that they are not totally overlapped similarly in the third example we can see that they will be overlapping but the values will not be same at the same location so two will be overlapping with one which is not allowed if the trees are identical so we have to solve this question and we will be solving this question recursively now let us say that we have a tree like this it contains the value 1 2 3 4 5 and there's another tree which contains the value one two three four five and six if you want to check that if these two trees are identical or not by looking at this structure we know that the answer for this is false but if you want to check it recursively we will do it step by step so first of all we are going to compare this tree with this tree so in order to do that we will be comparing these two nodes if the values of these two nodes are not same then obviously we are going to return false and let us say if the values of these two trees are same then what is the next step that we have to do so we have to disconnect this and now as we are done with this much part we will be focusing on the leftover part now we have a left sub tree and a right sub tree of p so let's say this was p and this was q and similarly we have a left sub tree of q and a right subtree of q now if we want to compare p and q first of all we compared the value of the root if the value of the root is not same we are going to return false and if it is same then we will have to check the same for the leftover tree so now we have four parts now this is the part that we will be comparing with this part as we can see that there are new trees so this is another tree which we can say p and this is another tree which we can say q we can compare these two using the same logic that is why we will be sending them to the same recursive call to which we sent the parent p and the parent queue we will be sending both of these to the same recursive call similarly for the right subtree let us say this is the p this is the queue we will be sending these p and q's to the same recursive call so now when we are sending the left subtree will look like this is three this is four this is five this was for p and for q it was three and four and five now same thing is going to happen because it is the same function it will compare these two values if these two values are not same it will return false otherwise we will disconnect these two nodes and we will call this p and this as q and we will again send them to the same recursive call so now when only one node is left we will be getting true so the left part is going to return two and similarly the right sub part is going to return true because both these values are same and that is why this recursive call will return true so we will be getting true from the left side of p and q when we check the same for the right sub tree so we know the structure of the right sub tree for p it is three and for q it is three and six we will compare these two values are same and that is why we will be sending the left child of p with 6 and the right child of p with null so as we can see that these two values are same because these are null so we will be returning 2 from this side but these two values are not same because this is null and it is 6 and that is why it will return false and if any one of these is returning us false the function is going to return false to its parent function so we will be getting false from the right hand side and as we discussed if any of the side is returning us false and so the left side was returning true in this case and the right side is returning false this function will return false so finally we will say that these two trees are not same so let us try to implement the same using recursion so as we discussed if both of them are null if p is equal to null and q is equal to null then return true if one of them is null and the other one is not null so if p is equal to null and q is equal to null then return false so the first case is when both of the values are null and when we come to the line number 17 we are sure that both of them are not null so if any one of them is null we are going to return false now checking the value if the value of p is not equal to the value of q in this case we are sure to return false from here otherwise we will not return true we will check for the left sub tree and the right subtree so we will be returning is same tree p is left and q is left and is same tree p is right and q is right so now let us try to run the code if it is equal to null and if this is equal to null it is giving us correct answer let us try to submit if p's value is not equal to q's value then return false okay it should be an or here so in the line number 17 we want to check if either of these two values are null in the line number 16 we check if both of them are null then we are sure to return true but if one of them is null and the other one is not null we should be returning false and in the line number 18 we are checking their values if their values are not same then also we will be returning false and if the values are same then we will be checking the same recursive function by passing the left hand side of p with the left hand side of q and the right hand side of p with the right hand side of q so this is it for the video actually solving questions on trees helps you improve your recursion as well if you like the video please subscribe to the channel thank you
Same Tree
same-tree
Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. **Example 1:** **Input:** p = \[1,2,3\], q = \[1,2,3\] **Output:** true **Example 2:** **Input:** p = \[1,2\], q = \[1,null,2\] **Output:** false **Example 3:** **Input:** p = \[1,2,1\], q = \[1,1,2\] **Output:** false **Constraints:** * The number of nodes in both trees is in the range `[0, 100]`. * `-104 <= Node.val <= 104`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
4
hello guys welcome to the lead course series today's problem is medium up to sorted array we can find a million of two sorted up from array here is the sum problem given and uh also given an output and put here is the conditions we can execute in this program okay let's start first create a variable end with two number one given him added that length gated to error length check which is greater array and assign that to Temp array let's and assign length to the temp Liam length into two okay point I mean Mini Max and more reset in file Loop check I mean Anonymous event and check the if engines uh assign that value to it divided pop-up values you check pop-up values you check pop-up values you check Min and Max condition else if Min and Max are and minus one let's check else into max Lane equal to zero is condition check that we have to check this find out the median of the array written 0.08 h 0.08 h 0.08 h let's run it okay case one case two are executed submit to the elite code is problem solved successfully thank you so much to watch more videos uh on lead code series and also watch on videos are angular Python and more layer programming let's learn with the software Tech ID now visit definitely check out software our website our website our website this code also available on website thank you watch more video
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
381
Do it According to Sonu Nigam's YouTube channel, in today's video, how to make your own just classification of the person who requests a friend of an insult, then in this also there are 3 options, if you want to support and you will get the tid confession of West Remo Gas Cylinder. Art it and remove it, you will get equal if the president is some random handsome president then call him exactly that how did you define the [ __ ] just how did you define the [ __ ] just how did you define the [ __ ] just because duplication is louder so if you have 6804 thirty then you have added this then Your probability of fear and update will be equally divided among all. Is it so that these three together made 50% of Chang Yan so that these three together made 50% of Chang Yan so that these three together made 50% of Chang Yan and 3000 of 20% of tears? It and 3000 of 20% of tears? It and 3000 of 20% of tears? It is not so, this is the individual probability of all the brothers. Now, the arrival of this train. Probability of 1.79 Its 1.00 Tarpan Probability of 1.79 Its 1.00 Tarpan Probability of 1.79 Its 1.00 Tarpan 71.71.71.71 Technical year This is the probability of singh30 coming for which one will become and two daughters of getting tested will become porn stars but it is popular to want these and to set the application to low and divide to infinity Everyone will start becoming everyone will have their own equal probability and you will have the total time intact. Plate Monday. Now how can we do it, so we have told all this that you, let us feed you, we are already in the studio, slapped controls because everything is there, I want it in the oven. So add and remove his elephant will do why smart has some things theorem keep list to take out time for this that brother if Anandpal why half the list because salt index will be used backward index will take out the time of these world random boys Will find out the reason for that and active unlimited, right click here, I am given the tone, I am not getting it next year, I am not lucky, I will find them, okay, I will be able to index in the set, because last time there was no duplication of hips, so neither gas nor interior, they used to make semolina. Click on this, you have to step India vs. There are some stories, are you smoking or this pattern word, this very country, I said SO stay for the first time, I had earlier thought that I had done the first one, so I did not keep the edit from here to Nirkhyou index And Kospi application, let it be index story, tubeless straight list is ready, just why are you keeping it, I have again said that you can't keep points in this system that if you want then why not hate, okay then let's talk later, first let me tell you. Why can't you do the East, I will tell you, I am a superman return or kept but then according to one students report tanker then third said if you say side effect then it played then now third tips and said is the length of 3830 is the last Chhati was diverted click 30 grams so as long as its belt add that list off bj doctor in this video there is a statement that you have now someone has said in this from now on who told me to remove the tanning where would I free to do it If the dog has refused, then someone can remove the service tax, then there will be more pores because the administrator, you would like to remove the contact from the end. Jurisdiction is over 9th, so I remove the contact from the end, where you ca n't do any harm to the mark, it is here that I met the daughters. Why can't we? If you watch this video, what do we do? So here I will give thirty of them on the last methods. I will give some of the things which when removed, get removed, which increases when the first elastic shaker is removed. Now we will have to do that on the index, will we have to correct the things in the list before that, now this thirty first, last index, father tight, then first elastic tree, and so you must be feeling that brother, meeting zinc is always established at the end, yoga tight is the base. If I mix fourth then I will remove the fourth index brother, 3814 is not on the next and will you add two in its place, what are the third tips, I have done the next, look carefully, this is not the start of the play list that you can take it again if I have started removing the skin. I said again to Tim Uppal, Rolan is a shirt, Copper said in the benefits exchange, so main, you remove the removed contact, remove the invented, friend, listen to the voice messages of the Kailash tree, I pin thumbs up, if you want to remove the state, then I will maximize the fastest one. Removed from here how can't remove the track I will chat with the first last and now we stuffing now goes on remove index that I third quality ponting will also have to be corrected that the third index of the bell which is the currency of first has become 3310 expectation rice last There are no black flags, friend, in the end there is no free band, you had to remove it and just add Tennis A, if there is no clear shot then you will have to make rice to 350, then you will have to shop for it and you will have to do Rinku from it will not be there either. So two guys, only then show it in a very small size, but if it is possible for science then now the manuscript will not remain in the oven, first of all take the update, if you remove the last guy then it will be wrong, I used to make the same mistake, I thought it meant. My subscriber, I looted the butt, is there any problem later? No, if there is no party, then you cannot watch the last one, if you want to do the third one, then do rice in it and withdraw from it, so that I can remove the electronics on this side on the index. Advised to pass the money or will it increase again if you do snap rice then right now there will be more butt in two minds now please science and what do you do to keep it in just stories so let's have multiple sexual one balance here It is not there right now, it is sector, you tell me about the website thing which is useful, then I will give you this issue, now I told you to remove it, you told me to remove the turn light, this is only for you, if things happen in Renu model, then some or some are there. Become take out speech in lakhs I and any relation will come out first let him remove products come out from zero that these people are false and in well come set and in one first one I will just go for bond next I will set that You can fire someone can punish someone, have you become the number three idiot or not, how am I not cracking the skin now, subscribe remove it in Delhi, here in Delhi, stop it now 230 subscribe me Prabhjeet and subscribe place there and in it You can try that one, now you can see again, till now you said to remove tanning, your moment Africa, this is anyone who came close, removed the noose 310, business dot remove is a number one operation, I need a guy, someone to do that There is no need to travel for this, if you keep it in your hand, then it will be difficult for several days, then make the last index disappear, then 30k is removing express, so thirty earlier there used to be 3DX, so okay you see, you can do that. Use Android as much as you want to travel, now you and I will be able to do all the work, you will not need to do rice, no need to turn it on, see, cannot work in Puranas, the far southern part is important and BSP has appointed If the staff was needed for storage, then instead of running staff and management in girls values ​​​​aspect on a values ​​​​aspect on a values ​​​​aspect on a specific, fold it quickly, torch light, coat it with inch lungi, and there is something else, I am hua tha, zoom, I want that, Song Hello viewers welcome to Syed Tanveer return without the way things should be if you are without dresses subscribe this video you have watched this video 16 subscribe turn on support Ajay ko jhaal mein help hai last one What are the things in the department of palat suit, interference in personal life, assistant aa phone, where to measure penis, if we do it in life, then there is a settings feminist list, a top in tears, Bluetooth two, that new research, that I surrender last scene, I pin slide again. Jaldi jate sun hai pimple to new fair settings death requestin you am married ki reeva stories today is equal to so a new rule is that all right fruit equal to what next in exchange of list subscribe start the list that Prime Minister is If A and B are to be insulted in a dream situation then first of all for justice what if already introduced then Mitthu has asked to attend service is from this but this item and not placid into if present for his very brief canceled Bune Leg Slide So you check that I have torch content off well which is from Lalit Sha content that if tension that Aligarh to if tension that Aligarh to if tension that Aligarh to Ghaghra is something to call is you online website must not present su if not present then track Subscribe by calling here or not often. Now here, you just have to make it, just make this hotspot of these teachers and acts SA, select it here, if present all it's nothing but cut it from the map, set it up in the map. This guy has to be kept equal, I will gift him in the straight already present, for the first time in the pimples noddy test match, Sonic, if he is not already present, then my set up will be the phone, someone new, you have developed a, you have done this, now turn this way. Make two sets and add to the abuse list those who gave on 23rd April. Spread your hair straight and before going out tell your black truth. First start the list. Simply type in which contact you add the depth and then cut the actual start size. You will just appoint me in the list, add me to the list and I will shift the potato to the map, will you forgive me ma'am, now I will pack the last Kodi and this sector and will do it from here, if I was worthy of this then I would be in this line. I took the tissue and the President will put it on the fruits and vegetables in the tag so that he can provide private security to open it and remove it now remote when I have to remove it then it has to be done by the chief appointed to do it from the part wells it is from the city towards the head in these Teacher, now look at the tense's off well presented by a scientist, Shravan, keep it aside, then why am I now having half a square meter of land, because if the President will not be there, then do it from here, it is the day to remove it, then it is right. I What to return immediately Roast item Vice President If there is no President then at the call center If there is a President then you also need to remove A Need to be removed Take out the straight I Start at the best A Ajay is coming It removes in the modern form of both the words that from now on, first of all the issue which had to be removed was removed and I fitted my two sets and removed this paste of 12% on myself. Now removed this paste of 12% on myself. Now removed this paste of 12% on myself. Now what to do to remove it from the list. If you talk about Juice Remove Index in the last place then subscribe to its list, then you do not need to do anything, all you have to do is subscribe to Bigg Boss. Well, if it is not in the last place, then you have to shop specifically for us. What do we have to do now that we are sister want to remove hair want to remove these taxes then remove index page set this front list dot set remove intense pain in stomach acid I will list Update list start at least size - 121 list start at least size - 121 list start at least size - 121 make yesterday's games 200 this is what I have done for you half a minute from now I have set it now I can remove I start remove from the name of the list this is going to install 21 million complete Increase is seen in the last video, what will you do? If the marriage is not done, remove the person with intake, then keep the person who is last in the list, now you will keep him last, you will remove him, remove the person with good glass, now this The one who has maintained the minimum from zero balance, the one who has spread the new balance, the pound in of his house map which is set, there is a need to change it, he takes it out from his loved ones, who is the person from the bell new balance sellers. If you set a reminder on , who is the person from the bell new balance sellers. If you set a reminder on , then subscribe to it and subscribe. Is there anyone on whose old electronics which team is the last index? Now because you have because it is suitable for you because after you have remembered the thirty, the old Akram third day of the thirty. After the bright now after the skin you have removed it then 30k older comments know now according list size Kepler beach itne bande 3 banne to spend before that with the third index so you torn in the map which contacts will I tell in corresponding take that Current list WhatsApp imo light clouds list off List size before mobile Who was I but because we kept the head after the ribbon So let's talk time I will give you time I will remove the tanning How will I add in the district ice cream emerging Then how will I add To do this next also he has to see that and then go back to left the map, the reading point near the tube well, Jyoti also does not have its tempered glass and from here, the Gandharva Vivah, then the commission is here, then do it from here, then this is the last one. Wicket Select C Request is Ajay to Ajay Jhal's Ajay to Ajay I have taken a cup of sugar I have length belt collection match T20 match collection that springs present one of the best quickly submit Jhal Ajay to A website in shirt I made some mistake that if flag it is right meaning from Paul if the president has already been insulted time mode is on a return to inspire was not present 165 taste good to Ajay to flash lights of birth certificate some words like this become I have kept it to do justice, after that I told you 800 points can be taken out first, I removed it from my hand and again to do justice I told you in the map because one already present app is the president in the map and its corresponding size is the set. Bhi Roy, ok ma'am, the President has been raised in the guys like chords, I can do it around in stomach 6, I can think rationally, remove it from the map, when the facial is done, have you passed me, now I have shown the serial to you, so is there anything? Here, when you remove, set the remote birthday time table, charge map dot a well data is them, now the bank which is removing its for your purse was released when the murder has been done, then remove from the map. Do a snapshot on the remote Chalmu, then at this time you will be able to talk to A Fan 147. Husband call Ajay, then your boy has done it in Sovan. Deleted the inside of the train number plate. See you in the next video. Till then bye- bye in the next video. Till then bye- bye in the next video. Till then bye- bye make a call
Insert Delete GetRandom O(1) - Duplicates allowed
insert-delete-getrandom-o1-duplicates-allowed
`RandomizedCollection` is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element. Implement the `RandomizedCollection` class: * `RandomizedCollection()` Initializes the empty `RandomizedCollection` object. * `bool insert(int val)` Inserts an item `val` into the multiset, even if the item is already present. Returns `true` if the item is not present, `false` otherwise. * `bool remove(int val)` Removes an item `val` from the multiset if present. Returns `true` if the item is present, `false` otherwise. Note that if `val` has multiple occurrences in the multiset, we only remove one of them. * `int getRandom()` Returns a random element from the current multiset of elements. The probability of each element being returned is **linearly related** to the number of the same values the multiset contains. You must implement the functions of the class such that each function works on **average** `O(1)` time complexity. **Note:** The test cases are generated such that `getRandom` will only be called if there is **at least one** item in the `RandomizedCollection`. **Example 1:** **Input** \[ "RandomizedCollection ", "insert ", "insert ", "insert ", "getRandom ", "remove ", "getRandom "\] \[\[\], \[1\], \[1\], \[2\], \[\], \[1\], \[\]\] **Output** \[null, true, false, true, 2, true, 1\] **Explanation** RandomizedCollection randomizedCollection = new RandomizedCollection(); randomizedCollection.insert(1); // return true since the collection does not contain 1. // Inserts 1 into the collection. randomizedCollection.insert(1); // return false since the collection contains 1. // Inserts another 1 into the collection. Collection now contains \[1,1\]. randomizedCollection.insert(2); // return true since the collection does not contain 2. // Inserts 2 into the collection. Collection now contains \[1,1,2\]. randomizedCollection.getRandom(); // getRandom should: // - return 1 with probability 2/3, or // - return 2 with probability 1/3. randomizedCollection.remove(1); // return true since the collection contains 1. // Removes 1 from the collection. Collection now contains \[1,2\]. randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely. **Constraints:** * `-231 <= val <= 231 - 1` * At most `2 * 105` calls **in total** will be made to `insert`, `remove`, and `getRandom`. * There will be **at least one** element in the data structure when `getRandom` is called.
null
Array,Hash Table,Math,Design,Randomized
Hard
380
896
hey everyone welcome back and let's write some more neat code today so today let's solve the problem monotonic array we're given an array that is either monotone increasing or monotone decreasing and that means that either the values are strictly in greater than or equal order meaning the values are pretty much sorted in ascending order now we could have values like adjacent values that are equal to each other this still counts as monotone increasing and of course you could have the opposite so basically take this and reverse it and you'll get four three two one this is monotone decreasing so to put it simply the values are sorted either in increasing order or decreasing order where yes adjacent values can be equal which is also true when you're sorting values just thinking of it in terms of sorting is a lot more simple than kind of this like very specific definition now given an array nums which may not be monotone increase increasing or decreasing we want to determine if it is one of these two things if it is we return true if not we return false so it's not like a super difficult problem like the very straightforward way is to kind of have two Loops like the most simple way would be to have two Loops one to determine if it's monotone increasing if it is we return true if it's not then we have our second Loop which checks if it's monotone decreasing if it is we return true if not we return false now there's actually a couple more simple ways to do it and we already talked about how one monotone increasing when you reverse it becomes monotone decreasing so one way to solve this problem would be to take an array and if it's let's say in this form meaning that like the two end points because that is the easiest way to check if it should be monotone decreasing like if these two values if you take the difference but between these and it's negative like if you take 1 minus 4 and it's negative then we're going to take this and reverse it and put it into possibly a monotone increasing form now there's no guarantee by taking the difference of the endpoints like in the middle we could have some really big number like nine that's not a problem though because when we take this and we reverse it we're expecting the array to be monotone increasing so at that point like the reason I'm saying if the array is in this form meaning like the two endpoints the difference is negative we take it and reverse it is because then we only need a single Loop we expect it to be monotone increasing and if it's not monotone increasing then we return false if it is we return true what if the endpoints are not like negative the Delta is not negative or if the array was already in this form well then yeah we would still expect the array to be monotone increasing what if the two endpoints were equal well technically if all the values are equal that still counts as monotone increasing so that's a very simple way to do it technically by reversing the string you are looping over the array twice one to reverse the string and then once for us to determine if it's monotone increasing which by the way how would we do it we would just compare adjacent values and make sure every adjacent pair is the left value is less than or equal to the right value we do that for every single pair so let me quickly show you this solution it is linear time complexity no extra memory so like I mentioned we're gonna first take the Delta of nums of length the rightmost value and subtract nums of the beginning and actually in Python you don't even need to take the length you can just use the negative one index both of these are equivalent and basically if this is less than zero let's call nums dot reverse and reverse here right now we expect the array to be monotone increasing let's go over every pair in the array and the reason I'm going up until the length minus one is because for I we're going to expect I plus 1 exists because we're going to compare of course adjacent pairs so we're going to check if nums of I is less than or equal to nums of I plus one this is good this means it is monotone increasing but what if this was actually not the case the easiest thing at least for me to do is just take this and find the negation of it if this is not the case then we are going to return false it's not monotone increasing if it is like if we go through the entire array never execute this then out here we're going to return true let's quickly run it to make sure that it works and as you can see on the left yes it does it's pretty efficient but there is one more solution I want to quickly show you and that is theoretically we could iterate over this array once and we could actually check two comparisons instead of just checking if this is the case like the pairs are less than or equal the adjacent pairs we could also simultaneously check the other thing that they're greater than or equal we expect at least one of these to be true so we're going to Loop and we're going to have two if statements inside of the loop one checking this and another checking this now in my opinion if you have two if statements in the loop it's kind of equivalent to the previous solution that we had where we had two Loops anyway but it's not really a big deal this is just a different way to do it now how do we keep track of which one of these was the case and it's actually possible that both of these are valid that would be if all the values were equal of course then it's technically monotone increasing and decreasing like what if at some point it was not the case like maybe at this point the less than or equal did not hold up or maybe at this point the greater than or equal did not hold up how do we know how do we keep track of that the easiest way is to have two Boolean Flags one flag is gonna check if it's monotone increasing initially we're gonna set that to True same for decreasing we're gonna have this flag and initially it's also going to be set to true in other words we're assuming that it's both monotone increasing and decreasing and we're gonna iterate through both of the arrays and as long as this equality holds in the array we're going to assume that the array is monotone increasing but if one of these did not hold we would set this increase value the Boolean we would then set it to false like if we found a single one where it doesn't hold we set this to false same thing with a decreasing if we find a single adjacent pair where the quality does not hold the comparison does not hold then we'll set decrease to false by the end of the array at least one of these should be true like if one of these is true we're gonna return true if both of them are false we're going to return false and this is a very precise way not only to know if an array is monotone increasing or decreasing but it technically could be both and this solution actually would tell us that if both of these are true by the end of our solution so this is a similar solution and technically this is one pass same time complexity same memory complexity let's code it up now okay so I'm gonna have my two booleans increase and decrease and they're both going to be set to True initially and then we're gonna do the same thing we kind of did iterate over the array of the length minus one because we're going to compare adjacent Pairs and in here we're going to do our comparisons and then by the end you tell me what are we going to return increase or are we going to return decrease or are we going to return that increase or decrease like if at least one of these is true we return true if neither are true we return false so that's what we're going to return now as far as the comparisons it's also again pretty simple the first one is going to be the same as before nums of I is less than nums of I plus one if that's true then it is monotone increasing well if it's less than or equal and we can do these comparisons multiple ways like you can do whichever one you prefer this means it is monotone increasing so I can put a not in front of it this means it's not monotone increasing or I could have just changed the comparison I could have just done this also means if and if I get rid of the negation this also means it's not monotone increasing you can do whichever one you prefer I guess this is kind of the most simple but if it's not for you feel free to do the other one so this means it's not monotone increasing so we change increase to false and same thing here with monotone decreasing we expect the left value to be greater than or equal to the one to the right but if this is not the case then it's not monotone decreasing and we set decrease to false technically only one of these would execute in a single iteration so we could put else if but it doesn't really matter so this is the whole code now let's run it to make sure that it works and I forgot to put the equal sign here sorry about that but as you can see it works it's pretty efficient the runtime is a bit different but I wouldn't really pay much attention to that thanks for watching if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io and interviews check out neatcode.io and interviews check out neatcode.io and I'll see you soon
Monotonic Array
smallest-subtree-with-all-the-deepest-nodes
An array is **monotonic** if it is either monotone increasing or monotone decreasing. An array `nums` is monotone increasing if for all `i <= j`, `nums[i] <= nums[j]`. An array `nums` is monotone decreasing if for all `i <= j`, `nums[i] >= nums[j]`. Given an integer array `nums`, return `true` _if the given array is monotonic, or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[1,2,2,3\] **Output:** true **Example 2:** **Input:** nums = \[6,5,4,4\] **Output:** true **Example 3:** **Input:** nums = \[1,3,2\] **Output:** false **Constraints:** * `1 <= nums.length <= 105` * `-105 <= nums[i] <= 105`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
1,619
today we are solving questions 619 mean of array after removing some elements within lead code so let's go ahead and learn and code together in this question we are given an integer array called array and we are tasked with removing the smallest 5% and the largest 5% of the smallest 5% and the largest 5% of the smallest 5% and the largest 5% of array once we have done that we can then return the mean of array and that will be our answer so um first we're going to import numpy as NP and the reason that we're doing this is because we need a very exact float value and this will help us give us that so first we need to initialize uh the 5% of array so we'll say five is equal 5% of array so we'll say five is equal 5% of array so we'll say five is equal to int um length of array times 05 and the reason we're doing integer around there is because we need an INT and rather than a float uh to get a range from so we'll say 4 I in range of five we'll go ahead and say array. remove Min uh array so what this is going to do is going to remove the minimum or the lowest value within array we can do the same thing inversely with the max value this will remove the max value in Array and this will do uh this will go on until we hit the 5% Mark that we on until we hit the 5% Mark that we on until we hit the 5% Mark that we initialized earlier once we're done with this we can initialize our answer and we'll say um answer is equal to NP so that numpy um float and then we'll do the sum of array and then we'll divide that by our length of array and then we can return our answer that should give us the answer let's go ahead and run this that does work for all three of them so let's go ahead and submit this and we can see we get a terrible runtime and terrible memory that is because we are importing uh this package um and we have to call out package so it's kind of the downside of using the package but this is the answer uh let me know if you guys learned anything if you did go ahead and subscribe comment like the video hit the notification bell all the support you guys have given us are me is super um great and I really appreciate it so um with that we'll see you tomorrow and have a good one bye-bye
Mean of Array After Removing Some Elements
path-crossing
Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._ Answers within `10-5` of the **actual answer** will be considered accepted. **Example 1:** **Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\] **Output:** 2.00000 **Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2. **Example 2:** **Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\] **Output:** 4.00000 **Example 3:** **Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\] **Output:** 4.77778 **Constraints:** * `20 <= arr.length <= 1000` * `arr.length` **is a multiple** of `20`. * `0 <= arr[i] <= 105`
Simulate the process while keeping track of visited points. Use a set to store previously visited points.
Hash Table,String
Easy
null
1,015
Hello hello everyone Topiwala doing well today im back with andheri challenge acid number-10 smallest and you will like it is number-10 smallest and you will like it is number-10 smallest and you will like it is question i don't personally don't see the question subscribe this video plz subscribe Channel and 996709 Here's the example and what's well explained So let's quickly ranges from 12345 subscribe The Amazing till this 3D printer number only living in live with subscribe The subscribe like and subscribe 3510 torch start oh switch god in novartis fire in the discretion in the and paste a Printable Chuke Hain Ko Last-11 Last-11 Last-11 Hua Tha Aunty One Second Or Visible And Single One More Share And Subscribe And Share And Subscribe 2 And Power But Not Ranbir Will Replace Kar Lunga Quest For Best Interior Types Of Evil Forces Flag De Also Settled near noida also not withdrawal subscribe and subscribe the channel tan more withdrawal the number will be able to 90 numbers don't forget to subscribe this divisible by id m id a huge site in mode off question impatient and subscribe problem the amazing to do Subscribe and mid-november reminder so then gita reminder 182 established in medical term work hai ushe zor quarter loot plus 2 and the number valve remind me to the question subscribe reminder that in 210 0 plus one she role model oy padhansh Video subscribe and subscribe the Channel Please subscribe this Video give That Reaction Reminder All the Best Set the Reminder Agro Industries Turn on the Counter FIR Gautam Reminder Question Chairman N Sheela and Girls Just Simply Click on Continue Items Just Simply Continue Through To 100 West Indies T20 Definitely Reminder Subscribe My Channel Will Not Go Beyond Thee Ko She has returned home Under the K and Five Separately and Digestive Se Zor Reminder Subscribe Digit Number End Subscribe Video Ko 100 Vid Oo Ki Agar Yeh Kya Hai Play Store Number One Test 230 There are five stunts on this website but submit loot I hope you all understand your contacts from tomorrow thank you a
Smallest Integer Divisible by K
smallest-integer-divisible-by-k
Given a positive integer `k`, you need to find the **length** of the **smallest** positive integer `n` such that `n` is divisible by `k`, and `n` only contains the digit `1`. Return _the **length** of_ `n`. If there is no such `n`, return -1. **Note:** `n` may not fit in a 64-bit signed integer. **Example 1:** **Input:** k = 1 **Output:** 1 **Explanation:** The smallest answer is n = 1, which has length 1. **Example 2:** **Input:** k = 2 **Output:** -1 **Explanation:** There is no such positive integer n divisible by 2. **Example 3:** **Input:** k = 3 **Output:** 3 **Explanation:** The smallest answer is n = 111, which has length 3. **Constraints:** * `1 <= k <= 105`
null
null
Medium
null
709
Good picture video only middling will someone to the problem me this school tour festival to return district after placing a letter with the same letter no this you daily missions to do the question Tuesday language support conversation for the person with what is the function subscribe and subscribe the Channel and subscribe the that avatar per case of British 65293 of the lower case of meditation 97212 sorry for the fonts riots pilot meet 100cc son of speech capital settings that they leaf 65 is token and too low are you to add 30228 to You will get 6532 gifts 2017 so similar in just 120 you convert capital at a distance of html5 service of increased demand of vitamins is 832 you will be able to convert suite it simply set subscribe button capital shares capital norge iv 12232 10 You Will Get 12232 This Particular Problem And A View In Tubelight So Let's Start Hydrating Over 10 10110 Characters With Support For Testing Weather It Is Not Proper K Song Subscribe Now To You To Subscribe 3202 Finally Bigg Boss Quentin Place Nazar Pregnancy Test Negative Solution So It's Final Submit Subscribe
To Lower Case
to-lower-case
Given a string `s`, return _the string after replacing every uppercase letter with the same lowercase letter_. **Example 1:** **Input:** s = "Hello " **Output:** "hello " **Example 2:** **Input:** s = "here " **Output:** "here " **Example 3:** **Input:** s = "LOVELY " **Output:** "lovely " **Constraints:** * `1 <= s.length <= 100` * `s` consists of printable ASCII characters.
null
null
Easy
null
909
Hello friends today I'm going to solve liquid problem number 909 Snakes and Ladder so in this problem we are given n by an integer Matrix board and the cells are labeled from one to any squared starting from the bottom left of the board and alternating on each row alternating directions so it starts from the bottom left it keeps on increasing from left to right and on its alternate row it keeps on increasing from right to left and so on and the result that we want is what do we need outcome is starting from label one we need to reach the largest label that is n by n is and by and label which is close to 36 so from Level 1 how can we reach 36 in the least number of moves so that is what we need to find the least number of moves where if you look here uh we can make a move one to the two and then from here we reach 15 right and film 15 if we make a move to 17 we will reach back to 13 and from 13 we make one move we reach 14 which leads us to 35 and from 35 we reach 36 so how many moves are there uh well these move uh moving to two which leads us to 15 is counted as one move from 15 we moved to 17 which leads us to 13 which is the next move so total number of moves so far is 2 from 13 we move to 14 which leads us to 35 so the move now is equals to 3 from 35 we take one more move and we reach 36 so external of four moves right which is our answer here now we know how like the moves we could make visually but now how can we solve it programmatically where there are few uh conditions given for us to make a move so let's look at this condition and how can we make a move all right let me increase the font size cool so the first condition is that we choose a destination Square next with the label in the Range current plus one comma minimum of current plus six comma and squared so what the what does taste mean so we start from suppose we are starting from the first label which is label one and we need to move to the next label now how do we choose our next level it could be two in it could be 10 or we could directly reach to 365 making one more right but what is how do we do that so the next points next um positions can be determined by this formula so our next position would start from if we are starting from one then which is our current so if this is our current value then our next value would range from current plus when that is equals to 2 that is current plus one I'll just represent it by C current plus 1 2 minimum of current plus six comma n is correct so what's current plus six each is equals to current is equals to one so that would be equals to 7 and what's N squared it's 6 times 6 which is equals to 36 and the minimum of these two is equals to 7 right so that would range from uh two to seven so this would be our range so this will be our for Loop where we start moving making our next moves now also um we need to keep in mind that when we make a move to a square two what's happening is it's it has a ladder so we climb the ladder and we reach the uh reach 15 right as it's given here in these um area as well so this minus one value is four one level one this is for label two which leads us to 15. so our next value actually is not equals to 2 but now is equals to 15 here so what would our next we when we start from 1 so it would be 15 comma 3 4 five six and seven right so this would be our next values since 2 is leading us to 15 so that would be our next value here now what we do next is um we make we choose uh the first element so we this is a queue actually we are using a queue now we pop out the first element from the queue and we make the next move from this so the next this becomes our current so far so this is our current now so what's uh the next move that we could make that would be equals to current plus 1 which is equals to 16 to the range of uh current plus 6 comma and square the minimum of these two values so what would be current plus 6 15 plus 6 is equals to 21 so 21 and 36 21 is list right so this would be our range and then what we do is now we push the values of these values into our Q which is this Q so we pop this out and then what we have in this queue next are okay so we pop this out from our queue this is our Q so what do we have remaining so we make a move to 16 so 16 doesn't have a ladder or a snake next when we move make a move to 17 we are moved back to 13. so we are going to push 13 and then again 18 19 20 and 21. so this is what will make a push and then what we do next is we again pop our value three and then we make next moves right now we know what we need to do we are actually you make making a breadth first search why bet first search because we need to find the cert uh the minimum number of moves right that is the thirdest part to reach our destination here which means BFS will give us our shortest passed in the quickest time we could also use DFS but that would not guarantee us um the fastest uh answer so that is why we are going to use BFS and while we are making moves while we are popping out values from our array we also need to keep track of the number of moves we are making to reach that uh cell so what are we going to do is we are going to use a minimum array where the array ranges from value 0 to N squared plus 1 y plus 1 because we are not going to use the index 0 since the label starts from 1 and ends at 36 so that is why we are going to use on uh only indexes starting from 1 to 36 so the length will be equals to this one right 36 form for an array to have the index 36 it should be at least of length and square 36 plus 1 right which is 37 that is equals to N squared plus 1. so this is what will make um and also to um uh we are given a board and the board has these values and it's not been labeled right but we are only given that from this point we move to the label 15 but we don't know which level is 15 so we actually need to compute that value so what are we going to do is we are going to use this formula here uh basically we need to alternate right we need to alternate so we start from this and we see we check if the difference n minus I is equals to um if this difference is divisible uh by 2 that is if there is no remainder uh this the value of n here is equals to 6 right and what's this index here the row index is equals to 5 so the remainder is equals to 1 right so if the remainder 1 when divided by 2 is equals to 1 then we move from left to right we increase our label from left to right if not then the alternate label would be equals to zero right the remainder will be equals to zero that then we will move from right to left so similarly if this is 5 then this is obviously 4 and this is obviously three right and three means again it will have the remainder equals to 1 so we'll again move from left to right so that is what we are going to do now let's try to code our solution so what do we need here we need um we need the um we need an array where we label our cells so we need an array to label ourselves we'll name that area cells and then we also need an array minimum distance to keep the track of the number of moves we have made so far and we need a cue as well so now let's start writing array will be of length n times n plus one because we need to keep all of our labels right and then starting from uh I is equals to zero I less than and I plus and then for like J is equals to zero J is less than n and also what was the condition was that the remainder difference of the remainder uh should be equals to 1 right if it's one then that is what it will do so and um n minus I Motors 2 is equals to one then we start from left to right increase it from left to right and J plus okay let's uh Define our label starting from value one so in this case the value cell plus will be equals to I comma J eels our J will start from n minus 1 and will be greater than equals to zero and this would be equals to zero and J plus minus sales all right so now that we have created our cells let's create our minimum moves array it will be of length n times n plus one and we'll fill all the values with minus one and our label one which is our starting label will have the number of move which is equals to zero now we will create our Q all right the queue will have the value one because that is when we start from right and now that we have everything set up uh let's start writing our function uh while loop so we are going to pop out our current value right current is equals to first value from our queue and then we need to take get the next values from our cursor so the current value next value will start from current plus 1 and a two wheel range from minimum of current plus six or uh the N squared value and plus all right so actually these value and this next value both are labels of our cell now what we need to check is we also need our indices i j which is the index in our board so now that we have our label we have our index representing this label in our cell we check if um the board i j is not equals to -1 then our destination will change right so all right so late destination equals to next if it's not equals to -1 then destination equals to -1 then destination equals to -1 then destination will be equal to the value of the board here in this case like in this case the value is not equals to -1 right so that value is not equals to -1 right so that value is not equals to -1 right so that is when we change our destination a destination is not actually close to 2 which would be this case but that will be equals to the value of the board which is equals to 15 because it has a ladder all right and then now if we also need to check if it's minimum move is greater than minus one if it's greater than minus 1 we don't need to do anything if it is equals to -1 uh then we need to compute it because -1 uh then we need to compute it because -1 uh then we need to compute it because if it's greater than minus 1 which means that we have already reached that cell in the minimum number of moves so if it's -1 that is we are so if it's -1 that is we are so if it's -1 that is we are moving to that cell for the first time so we need to push it to our queue and then we will set the minimum moves of our destination value equals to the minimum moves from where we reach that plus one that is we reached for example um from 1 we move to 2 which leads us to 15. so how did we reach 15 we reached 15 from 1 right so the number of moves from to reach 1 is equals to zero so zero plus one leads us to 50. so that's how we update our minimum moves and then our base condition what if our cursed current is equals to the N times n then what do we do is we return our minimum moves to reach our current position else we are going to return -1 let's try to run our code and see if everything is fine all right so something is wrong here okay so this is equals to cells label okay minimum moves of what of our destination okay so there's one more mistake we always uh label our board from the bottom left right bottom left means it's the um it's the bottom most row which is um starting from n minus one so this value will be equals to M minus 1 and will be greater than equals to zero and our range here so P equals to this value because it's an inclusive range here cool now let's submit our solution great so the time complexity of this solution would be uh for these four Loop sticks and of N squared time complexity also here this Q in this queue we are the worst case complexity would be of N squared because we are only looping over one cell only once right if we have visited that cell previously we are not visiting it again so the worst case condition would be of N squared hence the total for this solution with o of n square and the space complexity is also of N squared
Snakes and Ladders
stone-game
You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to `n2` in a [**Boustrophedon style**](https://en.wikipedia.org/wiki/Boustrophedon) starting from the bottom left of the board (i.e. `board[n - 1][0]`) and alternating direction each row. You start on square `1` of the board. In each move, starting from square `curr`, do the following: * Choose a destination square `next` with a label in the range `[curr + 1, min(curr + 6, n2)]`. * This choice simulates the result of a standard **6-sided die roll**: i.e., there are always at most 6 destinations, regardless of the size of the board. * If `next` has a snake or ladder, you **must** move to the destination of that snake or ladder. Otherwise, you move to `next`. * The game ends when you reach the square `n2`. A board square on row `r` and column `c` has a snake or ladder if `board[r][c] != -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1` and `n2` do not have a snake or ladder. Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do **not** follow the subsequent snake or ladder. * For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do **not** follow the subsequent ladder to `4`. Return _the least number of moves required to reach the square_ `n2`_. If it is not possible to reach the square, return_ `-1`. **Example 1:** **Input:** board = \[\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,35,-1,-1,13,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,15,-1,-1,-1,-1\]\] **Output:** 4 **Explanation:** In the beginning, you start at square 1 (at row 5, column 0). You decide to move to square 2 and must take the ladder to square 15. You then decide to move to square 17 and must take the snake to square 13. You then decide to move to square 14 and must take the ladder to square 35. You then decide to move to square 36, ending the game. This is the lowest possible number of moves to reach the last square, so return 4. **Example 2:** **Input:** board = \[\[-1,-1\],\[-1,3\]\] **Output:** 1 **Constraints:** * `n == board.length == board[i].length` * `2 <= n <= 20` * `board[i][j]` is either `-1` or in the range `[1, n2]`. * The squares labeled `1` and `n2` do not have any ladders or snakes.
null
Array,Math,Dynamic Programming,Game Theory
Medium
1685,1788,1808,2002,2156
203
hey what's up guys the quite here I do tech encoding stuff on twitch and YouTube I do the premium Lea code problems on my patreon if you wanna check that out and if you want to reach out to me discord it's a good place to do that I try to get back to everyone this problem is called the remove linked list elements a lot of likes I'll give it like remove all elements from a linked list of integers that have a value Val so they give us a linked list and they give us a bow well they give us the head of a linked list and then they give us an integer Val and we want to go through the linked list and anywhere we see that value we want to remove that node so in this case the value is 6 so where we would give we would be given 1 the head of the linked list and we would traverse it and we'd say ok is the next node 6 ok well let's get rid of that let's skip over it and we get rid of all the sixes so you can see the output is the same as the original inkless - the sixes so if you original inkless - the sixes so if you original inkless - the sixes so if you didn't know how to get rid of or delete a linked list node what you do is you traverse and if you find the value as the next node so in this case if we're at 2 and we see a 6 we just set the this node so 2 we set to dot next equal to 2 next because - next dot next is next because - next dot next is next because - next dot next is equal to whatever 6 dot next is 3 so we just want to set the dot next equal to the dot next if that makes sense 2 dot next equals 2 dot next so 2 dot X was set to 6 but now it's going to be set to 3 and that's kind of how you do it but here's the only problem with this problem is how do we handle what if the head node is the value what if it was what if the value is 1 in this case and we get 1 passed in it's kind of difficult to you know set we can't just set we can't get rid of the reference and skip over the node because it's not the next note so here's the trick while head is not equal to null and head dot val is equal to the Val so if we get passed in a node with the head node is the value we want to remove we just say okay I had equal sign done next so while the head node is the value we just changed the head node essentially we change it to the next node so we just basically by changing the head to the head next node it's like we just get rid of it from the length list and that's exactly what we want to do so we do this until we have a head node that isn't and that has a value that is not equal to the one that we want to remove and once we have a head node that is normal we can just set a current node equal to that we can do a loop and we'll say while current node is not equal to null just a regular traversal but also within this condition we're going to say Walker node dot next is not equal to null and this is because for removals you want to check that if the next node is the value you want to delete we'll say okay if current node dot next dot Val is equal to Val that we want to remove so if the next we're traversing and if the next node is the one we want to remove we'll just set the current nodes dot next like I explained at the beginning to current node dot next and it basically just skips over that node if it's not something we want to remove then we'll only true we'll just keep continuing with our regular traversal current node equals current node dot next so just traverses to the end removes all the nodes we want to delete and then we'll return the head at the end a lot of people use a dummy head approach because you could get past and they had node what that has a value on it delete but as long as you have this condition up here where you just change the head node change it to the next node you don't need a dummy head you can do it as simply as this I think this is a lot more readable a lot neater and easier to deal with less variables and everything so linear scan through easy problem not too difficult let me know if you have questions really beginner level question here but yeah thank you guys for watching and really appreciate everyone that watches my videos and I will see you guys in the next one see ya
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
58
in this video we'll go over lead code question number 58 length of last word given a string s consisting of words and spaces we need to return the length of the last word in the string for example if the string was Hello World then the last word is World which has a length of five characters so we would return five however we also need to be able to handle multiple spaces in a row as well as leading and trailing spaces for example this could be the string which reads Cat in the Hat but notice that there are two leading spaces a single space here three spaces here and two trailing spaces the last word here is hat so we would return three now one way we could do this is by using the built-in split method to separate the built-in split method to separate the built-in split method to separate all the words in Python the split method will split a string based on a character that is given and put each string segment into an array if there is no argument given like in this example then it just splits the string on any white space so in this example the variable array looks like this where the string has been split on all white spaces and each word becomes a separate element in an array we can then just return the length of the last element in the array and in Python you can access the last element by using an index of negative one so the last element in this array is the word hat so we would return three now this works but in an interview they will probably ask you not to use any built-in string Methods and to implement built-in string Methods and to implement built-in string Methods and to implement the function yourself you can also see that if you had a very long string with a lot of spaces this would be very inefficient because you're splitting every single word when really you only need the last word so now let's look at how you can solve this without using the split method let's use a new string which will be a big cat as you can see there is one space here two spaces here and two more trailing spaces we're going to start by declaring a variable called length which is going to hold the length of the last word in the string and initialize it to zero we'll then use a variable called I to Traverse the string and we'll initialize it to the length of the string -1 so since the length of the string -1 so since the length of the string -1 so since the length of the string is 12 I will point to index 11 of the string which is the last character then we'll enter a loop that will Traverse backwards in the string until we hit the last word so we'll check for two things first we want to make sure that we haven't gone out of bounds so we'll make sure I is greater than or equal to zero next we'll check if the character at index I is a space character right now the character at index 11 is a space so we'll decrement I and move backwards in the string then we check again the character at index 10 is still a space so let's decrement I again now when we check this condition we see that the character at index 9 is not a space so that makes this Loop condition false so we'll break out of the loop now that we know that we've hit the last word of the string it's time to start counting its length so this Loop will keep iterating and incrementing the count of length as long as the character at index I is not a space we can see that the character at index 9 is indeed not a space so let's increment the length and decrement I the character at index 8 is still not a space so we'll increment length again and keep moving backwards the character at index 7 isn't a space either so let's increment length to 3 and decrement I again but now when we check this condition we see that the character at index 6 is a space that means we finish traversing the word so we can break out of this Loop and the only thing left to do is to return length which is three since the last word in the string was cat and the length of cat is three and we're done
Length of Last Word
length-of-last-word
Given a string `s` consisting of words and spaces, return _the length of the **last** word in the string._ A **word** is a maximal substring consisting of non-space characters only. **Example 1:** **Input:** s = "Hello World " **Output:** 5 **Explanation:** The last word is "World " with length 5. **Example 2:** **Input:** s = " fly me to the moon " **Output:** 4 **Explanation:** The last word is "moon " with length 4. **Example 3:** **Input:** s = "luffy is still joyboy " **Output:** 6 **Explanation:** The last word is "joyboy " with length 6. **Constraints:** * `1 <= s.length <= 104` * `s` consists of only English letters and spaces `' '`. * There will be at least one word in `s`.
null
String
Easy
null
848
hello everyone welcome to day 8 of september eco challenge and today's question is shifting letters here we are given a string of english lowercase characters and we need to shift those characters by certain amount and the amount is given by another array so this address states that the first character needs to be shifted by three units the second element of the iris states that the first two characters a and b needs to be shifted by five minutes the next entry is nine since it is at the third index it means that the first three characters needs to be shifted by nine units ahead so without much ado let's try and look at the presentation that i have created for this it's a fairly easy question although it's medium on lead code because of one twist which is missing out of here so i'll be telling you about that in the ppt shifting let us lead code 848 and let's reiterate with the same example here we are given the input string as a b and c so let's try and calculate by how much amount will a needs to be shifted at first by three units so we need to add three more to this then we have five since it is at the second index uh both the characters needs to be shifted by five minutes starting from this first one so we'll need to add five more to this and be in it needs to be shifted by five minutes next we have nine and since it is at this third index uh we need to shift the first three characters by nine units therefore we'll add nine here as well and here as well so by what total amount does a needs to be shifted it is 3 plus 8 5 is 8 plus 9 is 17 by 17 units it needs to be moved ahead b needs to be move ahead by 14 units and c by 9 units so what is the task for you guys you need to first of all identify by how many units each character needs to be shifted and once you know that information you increment its value or by that much units so how do you calculate this value so you need to go in the reverse direction and find the cumulative sum as you progress in the backwards direction so first element is 9 it stays as it is next we have 5 so 9 plus 5 turns out to be 14 so b needs to be shifted by 14 units and then we have 3 so 3 plus 14 is 17 and a needs to be shifted by 17 units so we are calculating the prefix sum in the reverse direction once we have iterated and calculated the prefix sum in the reverse direction we know by how much amount does each element needs to be moved ahead therefore it's pretty simple now you simply add this amount to your variable and calculate it now comes the hidden part of the question whenever there is a scenario that the value of the character plus the increment that needs to be made goes beyond 26 then what should you do you should take the modulus because uh you have to maintain that each element each character should be in lowercase english character so consider that this as a cycle once you exceed 26 you need to move and start from a itself the z the first character of english lowercase alphabets so how will you solve this uh this will can be solved by taking modulus once you find out the total sum and once you add it to your character then at both those points please consider taking modulus of 26 so as to get the correct result so for this case a plus 17 is r this gives me r b plus 14 gives me p and c plus 9 gives me l so the answer becomes r p and l just remember this identification where we have to take model is because this wasn't specified in the question and the interviewer may be expecting you to ask this corner case if you don't ask you lose out your points so this is the trick that was there in the question now let's move on to the coding section which is pretty simple and straightforward so let's start solving this question here i have identified a new variable shift initialize it to 0 and i have updated my input string into a character array so that i can set its value at any particular index because strings are immutable in nature next we have uh the iterator which is going from the rightmost index to the zeroth index and the responsibility of this iterator is to calculate the shift needed at each position so what i am doing is i am updating shift to shift plus i plus 1 and taking modulus of 26. i have my updated value of shift i'll add it uh to my current character and this equation is slightly tricky uh what i'm doing here is i have extracted the s the difference between the 8th index and the str of 5th index the sky value difference and added to the shift i took the modulus of 26 and whatever the remainder is there i added to the 8th character and i converted into a cad data set and set its value at it index once i am out of this loop i create a new string using the same str so let's try this up accept it and the time complexity of this approach is again pretty straightforward order of length of str this brings me to the end of today's session i hope you enjoyed it if you liked it please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded i'll see you tomorrow with another fresh question till then good bye
Shifting Letters
shifting-letters
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length. Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`). * For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`. Now for each `shifts[i] = x`, we want to shift the first `i + 1` letters of `s`, `x` times. Return _the final string after all such shifts to s are applied_. **Example 1:** **Input:** s = "abc ", shifts = \[3,5,9\] **Output:** "rpl " **Explanation:** We start with "abc ". After shifting the first 1 letters of s by 3, we have "dbc ". After shifting the first 2 letters of s by 5, we have "igc ". After shifting the first 3 letters of s by 9, we have "rpl ", the answer. **Example 2:** **Input:** s = "aaa ", shifts = \[1,2,3\] **Output:** "gfd " **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters. * `shifts.length == s.length` * `0 <= shifts[i] <= 109`
null
null
Medium
null
649
hey everybody this is Larry this is day four of the melee go daily challenge May the fourth be with you I suppose Mr button oh man hit the like button the Subscribe button join me on Discord let me know what you think about this bomb doted to send it I think this was actually one of the earliest prom I ever sold on the code uh mostly because you know I'm uh especially like four years ago or whatever I used to watch a lot of DOTA so uh so yeah all right let's but I don't remember the problem though I just remember DOTA because you know it's donut oh let's see uh let's see what this Farm is about Okay so each valued Senator can exercise one of two weights Ben one senator's right we can notice and lose all his rights in this and all firing around so basically like kick someone out maybe and now it's victory if this Foundation okay I mean I feel like this seems like um a heuristic type uh problem um and way I think without really thinking about it quite deeply yet my Surface intuition is that it's going to be greedy but um but you know greedy is just a word right greediest a word is something that describes an algorithm but it's not the solution right and what I mean by that is that there's so many ways to kind of be greedy and part of greedy when people talk about it is based off intuition but not everyone has the same intuition and sometimes your intuition is just wrong so that part is interesting all right so let's kind of think about this a little bit first and then round two okay so basically I think that uh I mean the first principle makes sense right so you want to ban someone from the other party I mean duh right like otherwise uh yeah uh is it majority wins oh no you have to get you have to have conco killed everybody uh right yeah so it's not just majority okay um so you have to you want to get some on the other party and then the other thing the greedy on is that you if possible you want to ban someone who um who still has a vote right because that means that they'll ban one fewer in this particular route um and you know you want to do that as early as possible Maybe yeah no I mean because um and you could kind of prove to yourself that if you really want to by using the exchange argument right meaning that um you know if you have something like uh drd and then you're at the uh and you could ban either the D or the second the first year the second D and here if you ban the second d uh then the second round goes otherwise if you bend this D then the D will just ban your oil something like this right so you can kind of it's not quite exchange augment that is as it is traditionally used but it is kind of that argument of okay well you have two choices how do they affect future outcomes right uh blowing it down okay um I think the other thing that you can kind of think about is that I mean we're right now we're talking about rounds you know we're going like one round two round three round but really it um but really you can just use a q right like a circular Cube because the ranks that actually doesn't matter because the step two the announced directory doesn't end at like the uh the rounds really don't matter where there's no rules that really determine what matters as well there could be a natural um break at the end of everything anyway right at the end of every step and not every round so the runs don't matter so I'm just gonna use a q to represent this um right so I'm going to do two things first one is always you go to uh send it that count of all uh what's the other one diet Senate that count of d um right and then now maybe for X in the Senate we have a keyword Forex and Senate Q dot a pen x this is just to populate it I don't know if you maybe you could just I don't know if you could just do something like this but yeah maybe uh maybe that's fine let's see let's print it out at worst lab you learned something new okay that actually works so okay fine uh okay and then basically the idea is just having a buffer right so basically while we have well R is greater than zero and D is greater than zero um okay so then if Q of zero is you go to all then you pop a d and how do I want to represent it I mean you could do it in a couple of ways uh make sure to say PD for pending D is equal to zero uh PR for pending R is equal to zero so this is that then PD will increment by one um maybe this is not quite right because if PR is equal to zero then that means that um this one we add a pending to the D otherwise PR subtract by one because that means that it got voted previously off right that's basically what this is saying um and here let me think about this for a second um if this is zero and that means that we this person wrote it and if this person wrote it then we want to um I think there's a rotate thing too but maybe I'm wrong I don't know uh so you could actually maybe do this in one line or one up it's not like one operation it's just malfunction but for now the idea is still the same right uh and then from here I think we can do the same for the other uh thing right and also if we there's a zero damage that okay and this means that we removed one R so then we can subtract R right and then else I guess else then it's equal to a d and then if p d is equal to zero then again we rotate this to the end but not before we set PR as you go to one and then L is P D minus one right and then at the very end if R is there then we return Radian else we return dire I mean that should be okay maybe looks okay here but these two examples are kind of crappy to be honest uh you know these are very simple things I don't know that you know it's uh indicative of what we want uh but it looks okay let's just give us a million YOLO oh no maybe I misunderstood this then I'll put radian that doesn't make sense maybe I have typos though it's very easy to type though huh but okay so the first one it is a d right so it goes here PD is zero huh I do I might have I may have missed a case the case that I might have missed is that um this should be this minus PR and this minus PT oh well then I have to change the center that's all sorry okay the reason it is basically um oh wait that wasn't a case that I got one what was the case that I got well but basically it may back up this stage doesn't a little bit better um still wrong why is that but basically Okay so hmm so if the first one was D then we pop and then we put it at the end that's fine and then we set PR is equal to one right let's just print it out I'm confused q r p r d p d I'm confused by one all right so we start with three R and 3D okay the D gets popped oh I am dumb I forgot the actual uh yeah okay I forgot to pop left on removing the other ones um and because that means that everything pops left I can move it here wow that is a very silly mistake uh let's give it some it oh and now I'll put limited because I forgot to remove the prince Daemon a lot of silly mistakes today apparently luckily this is not the contest um but yeah the big thing that I missed was that I just forgot to delete uh of all of these things I just forgot to delete and remove it from the queue I don't know Lobby's just being dumb today uh yeah um I'm trying to think to be honest so what I'm doing now is I'm trying to think like and how do I prevent myself like am I what uh one thing that I do want to think about uh oh I did it with mask in the past of Delta I mean same idea but um the thing I'm trying to think about is like how do I improve myself right I mean you know you saw me make two silly mistakes and okay fine yeah they are same mistakes but and I'm trying to figure out like why it is right like is it because I'm explaining and sometimes I do make mistakes on this kind of stream where I am explaining while coding because to be frank I just forget stuff right like I'm like oh I need to do this I need like but if I'm typing when I'm coding for a contest um or like normally or whatever sometimes I have like five or six things in my head and then I like kind of clear the buffer as fast as I can but when I'm talking sometimes I like delay that buffer uh querying because I'm like hey this does a this does x y z and that's why you know but sometimes after I talk I forget like one of the steps like in this case right um and maybe that's okay if that doesn't affect my comfort Real Performance but it's still like you know like I'm not embarrassed by it like people make mistakes all the time right uh you know being a good engineer is not necessary about not making mistakes and those of you who strive to be a senior engineer will know this it uh will hopefully get to it anyway um is it's not making a mistake is getting your system in a way such that when mistakes happen um the impact is minimalized right um and in this case I guess in that world I'm just trying to figure like I mean yeah this doesn't matter in gram scale things um but you know I'm not gonna lie I am still you know hoping to do better like I'm not like you know like I'm always pushing myself in a no event and maybe not always but you know but I see something silly so I don't know I mean the print statement was just print statement I just rushed it after it's fighting it and forgot to run it again uh but yeah I don't know it is what it is so what is the complexity here right um it's tempting to say linear but it is clearly not um the easy answer is gonna be n log n um maybe huh actually maybe I'm wrong this one initially I thought it's going to be n log n because the idea is that this maybe it still is though because my let me have a case for a second um some the case for analog again is just that if you have n items uh n people in the Senate uh and every iteration uh every Ram if you will it will eliminate half to people and in that case uh and in that case well it's just gonna be analog again because there'll be like n Realms right so this should be n log n time and Earth and space for the queue um but I think and I think you can do this with uh someone like this and I think that would you maybe and maybe like some variation of this I don't know how to like enter leaving it so that you can't get one but you can see that if I did something like this um D will you eliminate oh I'll eliminate D and then you know you have someone like this um I don't know how to kind of expand it to more iterations because after second but well just like you know all blow up but in theory right so I don't know but I'm trying to say that is analog and even though I don't have a case I mean I'm sure you could construct a case um backwards because like even from here um yeah you construct it here and then now you can backward construct a case that gives you this answer after the first iteration um so maybe like given and I don't know right but you can so I think it's gonna be n log n and that's pretty much it and login time of n space and that's all I have for this one still a lot what is silly mistake huh but you know my intuition was right in that the example was like crap uh I mean that example is a bad it's just that they're bad for validating whether you're correct or not so all right anyway um that is all I have for this one let me know what you think and yeah stay good stay healthy take your mental health I'll see y'all later take care bye
Dota2 Senate
dota2-senate
In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise **one** of the two rights: * **Ban one senator's right:** A senator can make another senator lose all his rights in this and all the following rounds. * **Announce the victory:** If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game. Given a string `senate` representing each senator's party belonging. The character `'R'` and `'D'` represent the Radiant party and the Dire party. Then if there are `n` senators, the size of the given string will be `n`. The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be `"Radiant "` or `"Dire "`. **Example 1:** **Input:** senate = "RD " **Output:** "Radiant " **Explanation:** The first senator comes from Radiant and he can just ban the next senator's right in round 1. And the second senator can't exercise any rights anymore since his right has been banned. And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. **Example 2:** **Input:** senate = "RDD " **Output:** "Dire " **Explanation:** The first senator comes from Radiant and he can just ban the next senator's right in round 1. And the second senator can't exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator's right in round 1. And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. **Constraints:** * `n == senate.length` * `1 <= n <= 104` * `senate[i]` is either `'R'` or `'D'`.
null
String,Greedy,Queue
Medium
495
771
hi there so we're just going to quickly talk about today's legoland challenge question it's called jewels and stones we have two input strings j and s j represents these songs that are joules s represents the stones so basically we want to count how many of the stones are joules so for each character in the string we want to check whether it's in j or not that's pretty much it this question is also case sensitive so small and big a capitalized a they should be treated differently so we don't need to do any kind of thing like a lower upper conversion and just treat them as it is so it's a pretty straightforward question so let's code a solution up very quickly uh we're going to initial a variable to keep track of the total number that's a stone and then of course we want to return it the most distributed way it's pretty simple so it's just gonna be one loop uh we're gonna grab the stones from this input string s and just directly check whether that's in j or not so um this algorithm uh it will be uh you know for each of the characters we want to do one pass scanning the j and the returning uh add the counter by one if we find it in j otherwise it will be uh you just increment by zero so it's a unchanged in the end we return that total this will be order of 52 multiplied by n that's the worst case n is the number of stones in here and the 52 is the potential maximum size for j actually it's 50. it's kind of a peculiar because we have a to z and the big a to big z it should be 52 i just don't know why it's 50. um and the space is order of one because there are no other things being allocated or otherwise if we want to decrease the time but able to utilize a little bit more space we could create a hashmap it will be a hush set that is enough uh all we know all we need to do is to have constant check for the stone whether it's that's in j or not so let's just call it jaws it's how we sell it sorry my bad english spellings so just gonna push all the jaws in onto the harsh set and then what we can do is just change this part to be uh what is this stone here yeah so with this change we use this uh set which we use a little bit more space but we can uh you know decrease the time complexity from 50 and 52 and to um directly to one multiply by hand because we got a constant lookups uh here with this what's this set here so let's just comment it very quickly so that's pretty much the two kind of way of summing it depends on whether you want to constant space or not so slightly different oh it's not okay uh what's the problem okay no initialization so it's a random value in the memory location that's being uh incremented and returned all right so that's a that's the question today
Jewels and Stones
encode-n-ary-tree-to-binary-tree
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`. **Example 1:** **Input:** jewels = "aA", stones = "aAAbbbb" **Output:** 3 **Example 2:** **Input:** jewels = "z", stones = "ZZ" **Output:** 0 **Constraints:** * `1 <= jewels.length, stones.length <= 50` * `jewels` and `stones` consist of only English letters. * All the characters of `jewels` are **unique**.
null
Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
Hard
765
443
hey everybody this is Larry this is day two of the Marshall Eco daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Farm uh yeah string compression 443 uh I got home kind of late today so but don't know because I think I've figured out my tiredness I mean I'm a little bit mentally tired but not I don't know I think that's another topic for another time but in any case uh yeah welcome uh let's do this together uh we have a thousand ish day streak so definitely we'll be keep on doing it if you're new to the channel definitely keep on uh I don't know keep on keeping it I don't know all right let's take a look 443 string compassion so you can uh characters of uh okay so you basically wanted to do with this only one okay so this is of course um the one two is kind of weird but I guess that's fine but yeah uh but the way that uh I would think about this is kind of um this is actually something called one length encoding uh and it actually comes up a lot uh does it actually let me try to think I mean it comes up enough that I know what it is uh by its other name but it comes up like randomly because it just seems like a very interesting thing for people to kind of play around with and then you have um and the other thing that's kind of relating to this is this idea of a Huffman tree right um which is in this apartment five out of scope I think it's is it Huffman with an uh you or oh hmm Huffman chairs for you oops it's a daisies uh for stretch go so if you want to you know just if you're into compression and stuff like this these are the two kind of uh first thing to kind of look at right there are other things of course that are more interesting as well as you get deeper but I think these are kind of like very basic things and the cool thing about Hoffman unit is actually unrelated this part is that it is also a greedy algorithm so you could definitely um a human Ivan used it or heard of it or play with it in like a long time just that knowing that fact means that I can actually recreate it from scratch um you know uh just from that first principle right anyway uh and I don't mean to sign as a brag I think I'm just a little bit off tension a little bit but anyway one thing for coding right so I mean I don't think there's anything that tricky about it I'm not sure why this is a medium but in fact in uh in what language in Python there's a thing called goodbye obviously um or maybe not obviously but in any case I'm not going to use this because uh oh wait maybe I misread this hang on so you're supposed to modify the input away okay so maybe that makes it a little bit more interesting and maybe that justifies medium rating um I mean I think the idea is still kind of the same uh I mean I don't think there's anything that complex about it per se uh it's just that now you have to kind of make it in place right which is a little bit whatever but I think it's like this when you're doing things in place the only thing that I worry about is kind of uh reading your rights right or get away around rather you don't want to read your rights you want to make sure that when you write you don't need that space anymore right so that's basically one and I think in this case um it should always be good because basically they're really only re-edge basically they're really only re-edge basically they're really only re-edge cases technically more but we could divide it into three which is that there's one character with just one so it only goes from one to one um and then there's you know up to uh up to ten or up to nine sorry um then it would be it could be compressed to two digits right and then more than that let's just say I don't know 15 or something right this is going to be uh obviously with two additional digit or three numbers or three spaces in total it's gonna be less than 15 over this isn't 15 but that's for 10 it is but you know I didn't really count it right so with that's just I mean maybe this is obvious to you but for me this is something that I try to visualize a little bit so that I could you know be sure that I won um read the poem correctly because if that's not the case that means that maybe I misread some point or maybe they tell you in the problem how to address it right so okay so yeah so or you know dealing with all that um yeah why is there so many downloads hmm I'm curious maybe there's some like really bad edge cases I guess we'll see but yeah that's basically the idea um so let's kind of get started I suppose uh so I was gonna use I but maybe let's make it more uh explicit where you know right pointer maybe right pointer is your zero a read pointer is also equal to zero right so then while read pointer is less than n that if I could have been a for Loop but I just kind of like to write it this way but uh but yeah uh sorry I got a point ping but uh yeah so okay so then basically now we read the current uh thing right so c as you go to this um and then we need to keep track a couple of things but I just kind of was lazy about it one is the current character let's say it's none and then the current run is equal to zero right so basically now if C is equal to current character and this will always be forced to begin with then current one is equal to one and then current counters you go to C but then we also have to write to the right buffer because that means that the current character changed so then basically we want to write something like um oh and also after you read a character always increment so that you don't forget um what was that going to say oh yeah um so if current character is not none so that's basically the only case then we write to the right buffer right um the choice of right pointer is equal to um the previous current character so they're just a current character before we update it and then we have to kind of do the string and encoding of the current run right um yeah oh after we turn the length of the array that's fine we that'll be just the right point so we actually already handled it um yeah and then basically yeah I'm a little bit lazy so let's just uh turn into a thing for X in uh this then charge of right pointer and we have to implement even previously but right and of course we actually have to um we actually have to uh make sure that current one is greater than one right because if it's one then we don't need to do it yeah okay otherwise oh wait I messed this up I meant this is not equal to sorry if you got confused by that so it is you code two then all we have to do is turn one increment and that's it yeah and then at the end we return white pointer and I think that should be it uh unless I missed a thing somewhere and I did clearly oh yeah I did actually know I did have a mental note to kind of not forget but then I forgot so yeah so basically if the current character is not none at the very end we have to write the last buffer basically so um maybe I could uh something like flight buffer right I do also like change this to non-locos I do also like change this to non-locos I do also like change this to non-locos or something but yeah baby and that should be good uh looks good for these three Let's uh let's um maybe I was gonna say maybe the empty string but it seems like we have at least one character why people swimming downwards let's I guess we'll find out let's see what oh guys I actually I got it right in the first try 1066 day streak um I do wonder what are the edge cases what did I what did Pastor Larry fell on uh oh okay seems like I tried to do the same thing but Maybe I guess I started on this first one that makes it a little bit cleaner actually maybe I don't know what does this get well on it doesn't really tell you anymore maybe this was so long ago that doesn't tell you or I feel like they used to tell them um I mean I guess I ended so what I did is that I appended this thing so that I don't have to uh so I don't have to do the thing that I did um but I do but I mean the idea is to stay the same so what's the complexity right uh the complexity is gonna be linear time all of one extra space um we don't really use any extra space we other than you know uh the pointers and stuff like this um because we write directly into the thing in place so uh yeah just slightly smaller so you could see all of it um that's all I have for today that's all I have so let me know what you think stay good stay healthy to good mental health I'll see y'all later and take care bye
String Compression
string-compression
Given an array of characters `chars`, compress it using the following algorithm: Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`: * If the group's length is `1`, append the character to `s`. * Otherwise, append the character followed by the group's length. The compressed string `s` **should not be returned separately**, but instead, be stored **in the input character array `chars`**. Note that group lengths that are `10` or longer will be split into multiple characters in `chars`. After you are done **modifying the input array,** return _the new length of the array_. You must write an algorithm that uses only constant extra space. **Example 1:** **Input:** chars = \[ "a ", "a ", "b ", "b ", "c ", "c ", "c "\] **Output:** Return 6, and the first 6 characters of the input array should be: \[ "a ", "2 ", "b ", "2 ", "c ", "3 "\] **Explanation:** The groups are "aa ", "bb ", and "ccc ". This compresses to "a2b2c3 ". **Example 2:** **Input:** chars = \[ "a "\] **Output:** Return 1, and the first character of the input array should be: \[ "a "\] **Explanation:** The only group is "a ", which remains uncompressed since it's a single character. **Example 3:** **Input:** chars = \[ "a ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b "\] **Output:** Return 4, and the first 4 characters of the input array should be: \[ "a ", "b ", "1 ", "2 "\]. **Explanation:** The groups are "a " and "bbbbbbbbbbbb ". This compresses to "ab12 ". **Constraints:** * `1 <= chars.length <= 2000` * `chars[i]` is a lowercase English letter, uppercase English letter, digit, or symbol.
How do you know if you are at the end of a consecutive group of characters?
Two Pointers,String
Medium
38,271,604,1241
145
hi everyone it's Orin today we have a problem when we are given root of a binary tree and we need to return the postorder traversal values of all nodes so let's say that we have this binary tree two one and three right and we need to return the postorder traversal values so what's the postorder traversal in the postorder traversal first we are visiting left sub tree then we are visiting right sub tree then we are visiting Road road so let's write down here left right then we are visiting left and we are visiting right and then we are at last we are visiting road so in this case it's going to be one right it's going to be three and it's going to be two so how about the this one right the example one that we are given in this case we need to first visit left there is no left right so we are visiting right but the right has its left sub tree here three right so first we are visiting three right then we are visiting right there is no right here again and we are visiting two right and the lastly after visiting right sub tree we are visiting our root which is one right okay first thing that we are going to do we are going to create a list of integers where we are going to store our result let's just call it a result send you array list and um we are going to return that so let's return our result now we can go and Traverse our tree Traverse our binary tree and add the result to our add the values to our result let's just call it post order traversal post rsal we are passing our root here and also we are passing our result let's create our method it's going to be a private so it's void and we are calling it post order traversal and what we are passing here we are passing a tree note and we are passing here our list of integers right our result integer result so what's our base case the base case is if our node is equals to null right if our node is equals to null in that case what we do here we are just a backtracking right returning and then we are recursively calling our method post order traversal actually just call it Traverse and we are passing here our node first we are visiting left node right left child and then let's pass it our result here result and the same way we can copy paste that here and it should be right okay so let's change the method name okay and after that so first we are visiting a left sub left child right left sub tree then we are visiting a right child and then we are visiting our room Ro right so let's add to our result here add we are adding node value right node value okay let's run it okay great it works as expected what's our time and space complexity in this case the time complexity is we are visiting every Noe so the time complexity is of n the spa and the space complexity is the determined by the result so we are visiting every note and adding every note value so it's going to be also ofn okay um that's it for today hope you like my content if you like it please hit the like button and subscribe my channel see you next time bye
Binary Tree Postorder Traversal
binary-tree-postorder-traversal
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[3,2,1\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of the nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
94,776
808
hello everyone welcome back here is when I'm saying in today's video we are going to delve into a really intriguing problem called soup serving so this problem uh is an excellent opportunity to explore a dynamic uh programming top-down approach also known as top-down approach also known as top-down approach also known as memorization so if you are new to this technique or if you are looking to deepen your understanding you are in the right place so let's get started in this problem we have two types of soup A and B and we start with n milliliters of each type and there are four operations so those are four operations of serve different proportion of soup A and B and we choose an operation at random uh each turn so our task is to find the probability that soup ah will be emptied first plus half the probability that both Su A and B will become empty at the same time so the first uh let's Implement if n is greater than 4800 and return one uh so it's a clever shortcut so for a large values of n the probability of soup a being emptied first approaches one so we can return one directly to serve uh and optimize computation so next we dive uh and divide and by 25 and round them up so this is because the serving size of soup in our operation are all multiplied of 25 milliliter so this step effectively reduces the size of the problem without losing accuracy so let's implement it so if and greater than return one and plus n divided by 25 without remainder and memo will be addicted so we then Define a dictionary member for our memorization strategy and this will hold the computed probabilities for each a possible state of remaining amounts of soup A and B helping us avoid redundant computation so devdp foreign if i j in memo return memo i j so next we Define a helper function so dpij and this function computes and return the desired probability when there are I servings of soup a and day serving of soup B left so uh let's break uh so yep and we have a memo that return already computed uh probabilities if we have completed them so then if I less than 0 and J less than 0 return 0 half and if I less than 0 return 1 and J Less Than Zero return 0 and memo will be i j 0 25 DP I minus 5 or j d p i three J minus 1 plus DPI minus 2 J minus 2 DP I minus 1 J minus 3 and we return the memo of i j and finally we return DP of n and n so let's break down the line of memo I j025 times and this whole equation so the right hand side of this assignment represents the expanded value of the probability that soup a will be emptied first given the current state of i j so this expanded value is calculated as the average of the probabilities obtained from each of four operations so for each operation we recursively call DP with the new state of soup a and B after performing the operation this new state are I minus 4 j i minus 3 J minus 1 I minus 2 J minus 2 and I minus 1 J minus 3 and the factor of 25 0 25 comes from the fact that each operation is chosen with uh equal probability so our memory dictionary is a way to store the result of previous computations for the state of the system and the remaining amount of soup A and B and state is represented by upper i j where I is the amount of soup a remaining and J is the amount of soup B remaining so the line memo 0 25 i j is where the we calculate the probability of soup a emptied first given the current state considering all four possible operation each operation altered the amount of soup A and B in specific weight so for example if we serve 100 milliliter of soup a and zero milliliter of soup B so the first operation so this operation decreased the amount of soup a by four servings since we counting in 25 milliliter servings and leave the amount of soup B uh unchanged and in the context of our function this is represented by DP uh I minus 4 J and serve 75 milliliter of soup uh a and 25 milliliter of suit B so this uh operation decreased the amount of soup a by three servings and soup B by one servings and this is represented by DP I minus three uh J minus one so we can make a marking here so if you see here so here we have four so it's yeah this link to the first here we have the second part third part and fifth apart and uh if you see for example for fourth part it's 25 and 75 so that's why here is free and here is uh one so 75 here we have 50 milliliters so 50 and 75 25 so it's 75 25 and here you have exactly the same so 100 and 0 and because those are serving so minus four and minus zero so uh just Just J okay uh and same with serving 25 milliliter and servings of 50 milliliters of soup uh A and B respectively S4 statements so each of this DP function call uh return the probability of sub a emptying first for the new stage after performing the correspondent operation and we take the average of these probabilities because each operation is chosen with equal probability and this calculates the probability uh and is then stored in the memo dictionary with the key as the current state ID and this means that if we encounter the state again we can directly retrieve uh its results from a memo instead of pre-computing things and memo instead of pre-computing things and memo instead of pre-computing things and the mind function soup serving simply cause DP and to calculate and return desired probability so uh basically we have I is how many uh serving left of food of milliliter of soap a and uh soup B and we run it with an anso enemy liter of A and N milliliter of B and there we have it we can run it for uh this uh test case so yeah two test cases passed all good so uh yeah zero uh six to five okay so now we can run it also for unseen test cases uh to verify uh everything work so yep let's see and our implementation in Python a bit 92.92 percent with respect to runtime 92.92 percent with respect to runtime 92.92 percent with respect to runtime and also 79 with respect to memory so it's quite efficient and there you have it the top down dynamic programming solution to the soup serving problem and this problem wonderful uh and illustrate how memorization can help us avoid redundant computation and solve problem uh efficiently so remember if you are coding in a different language we got you covered so check out the description below for the code in other languages so we solve it also in uh C sharp JavaScript Java and C plus so yeah C plus implementation is quite fast so it beats 100 so really good and yeah I hope this video helped you understand the solution and as always I don't hesitate to drop your question in the comment section below and if you found this video helpful give it a thumb up and don't forget to subscribe and turn on notification so you don't miss out on the upcoming videos and coding tutorials and stay tuned for more interesting coding problem and as always keep practicing stay motivated happy coding and see you next time
Soup Servings
number-of-matching-subsequences
There are two types of soup: **type A** and **type B**. Initially, we have `n` ml of each type of soup. There are four kinds of operations: 1. Serve `100` ml of **soup A** and `0` ml of **soup B**, 2. Serve `75` ml of **soup A** and `25` ml of **soup B**, 3. Serve `50` ml of **soup A** and `50` ml of **soup B**, and 4. Serve `25` ml of **soup A** and `75` ml of **soup B**. When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability `0.25`. If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup. **Note** that we do not have an operation where all `100` ml's of **soup B** are used first. Return _the probability that **soup A** will be empty first, plus half the probability that **A** and **B** become empty at the same time_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** n = 50 **Output:** 0.62500 **Explanation:** If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 \* (1 + 1 + 0.5 + 0) = 0.625. **Example 2:** **Input:** n = 100 **Output:** 0.71875 **Constraints:** * `0 <= n <= 109`
null
Hash Table,String,Trie,Sorting
Medium
392,1051,2186
33
okay let's solve leak code 33 search and rotated sorted array so we're basically given an array that was originally sorted like this one but it then it became rotated like this one and by rotated they mean that they took a certain pivot or index of the array like right over here and then they cut it in half and then swap through the portions right so you can basically think of this right-hand portion being think of this right-hand portion being think of this right-hand portion being swapped over to the left side over here right that's what happened as you can see here right these two halves were put in the opposites position and we're also given a target value in this example target zero and we want to check if our array contains this value if it does we return the index if it doesn't we return negative one the most straightforward way to approach this problem is literally just check every single value is this our target and eventually we get here this is our target and then we return the index for now this is just too trivial of a solution right the time complexity isn't bad it's o of n but can we do better in this problem they literally tell us to find a solution and that's of log n so obviously we can and basically anytime you're looking for a solution that's log N or better than linear almost every time you're going to be looking for a binary search type solution so since this array was originally rotated can we use that to our advantage to potentially find a binary search type solution for this problem let's try to analyze it and see what we can find so given that the original array was sorted if we wanted to represent that as a graph we would basically have a continuously increasing line it might not necessarily be linear but it would always be increasing right and then we took some pivot like over here and then swapped these halves around right so let's draw what that would look like so let's say the left side was exclusively greater than the right side because that's what it means by rotating the array right so I think this is a pretty good way to visualize the problem to kind of understand what it would look like and you can use this to your advantage to find potential patterns that can help us find a binary search solution so with a problem like this you really have to break it down into discrete cases and then use those cases to form a solution so the most obvious thing is that there are two portions of the array right there's a left portion and a right portion both independently are sorted right so it's like we have two halves that are sorted and so we know that a binary search usually has three pointers a left pointer a middle pointer and a right pointer the left is always going to be less than or equal to the right this is just something you kind of know from binary search so let's say our middle value was six at some point right this means that we're in the left sorted portion of the array so can we use that to our advantage so let's say our target was greater than six in that case we know for sure since we're in the left sorted portion of the array none of these values are greater than six so we can basically say these are eliminated let's run binary search on this portion now right so that's pretty easy if we know that we're in the left sorted portion and our target is greater than the middle this is what we can do what if our target is less than the middle value so what if our target was less than six well these two numbers are less than six and these three numbers are less than six so how do we know which way to go do we go left or do we go right because we can't go both directions in a binary search the key is to see that in our left sorted portion the smallest value is right here right or on our graph it's right here so if our target is even smaller than this left value for in that case we know that we don't have to search for we don't have to search five we don't have to search six week binarysearch over here but if our value is greater than or equal to four then that means we're gonna run binary search on this on these two values right it's less than six but it's greater than or equal to four so we can run binary search on these two values we can eliminate all of these from consideration so all of that is if we were in the left sorted portion of the array right now what happens if we're in the right sorted portion of the array let's say our middle was one and let's say we knew somehow that we were in the right sorted portion of the array what if our target was less than one well then we know we have to search the left the only value less than one is right here so we're gonna search the left portion of this array we're not gonna look at one we're not gonna look at two anymore any value to the right of one is greater than one so we don't have to look at them we're just gonna run binary search on these elements we don't necessarily have to know where the pivot even is we just know we have to go left but what if our target was greater than one well then our solution could possibly be two it could also be any of these four values so then where do we go again we can use this rightmost value or the edge basically of our right to our advantage so if our target is greater than one and it's also greater than two that means we can again search this left portion we can eliminate these two from consideration but what if the opposite is true what if our target is greater than one but it's less than or equal to two in that case we only have to run binary search on the right portion of one every value to the right of one meaning we can eliminate all of these from consideration so that was a lot of discrete cases and it might be confusing I think it'll be a little easier to understand once we actually write the code but I think it's also important to visualize it and actually understand what's going on before you even write a single line of code and knowing what we just learned let's just go through this example of the target equal to zero and given this input array so initially our left pointer would be here our right pointer would be here our middle would be here so how do we even know if we're in the left sorted portion or the right sorted portion well the way I check is just if our middle value is greater than or equal to our left the actual value at that index if this is true then that means our middle value belongs to the left sorted portion if this wasn't true that means our middle values in the right sorted portion and we would write our if statements accordingly but knowing that we are in this left sorted portion right let's run through it so our target is zero that means our target is less than seven so our target is less than seven that means we could be looking here or we could be looking here so let's compare it to four now is our target less than the leftmost value well zero is less than four okay so that means we're all good we just have to search every value to the right of our middle value so we can eliminate all of these we can cross out our middle and left our new left is going to be here and our new middle is going to be here now in this case are we in the left sorted portion or the right sorted portion well among these three values the entire array is pretty much sorted so according to our thing according to our if statements were basically going to say that middle belongs to the left sorted portion because the entire thing is sorted so now we compare middle to target well our target is less than one so now we have to go left and if we compared it to the leftmost value zero our target is greater than or equal to not so we don't have to check anywhere else we only have to go left so we can eliminate these two from consideration and we're left with one value over here and that's our solution so this is kind of a visualization for it now let's actually look at the code to better understand what these cases are going to look like okay so when you're doing binary search first thing you do is initialize your pointer so we have a left and we have a right left is going to be 0 right is going to be the length of the array minus 1 our condition is while left is less than or equal to right because imagine we're given an array like this with just one value let's say it had one left and right would be equal in that case and we still have to check that one value so now we can compute the middle value middle is just going to be left + right / to the just going to be left + right / to the just going to be left + right / to the average of them and it's possible to the middle value could be the target if it is we simply return the index if that's not the case then we need to check which portion of the array are we in the left sorted portion and like I mentioned before we can check that if the middle value is greater than the left value well greater than or equal right because it's possible that the middle value in the left value could be the same value the else condition would be that we're in the right sorted portion so the simplest case is that our target is greater than the middle value in that case we're going to search right so we can say our left pointer is now going to be mid plus 1 so if the target is actually less than the middle then we need to do something else so if the target is less than the middle but it's also less than the left most value in nums then we also have to search the right portion so we're gonna do left is mid plus 1 now notice how these two cases are evaluating to the same thing that means we can condense them we can get rid of this and say instead if the top if target is greater than the middle or if the target is less than the left-most if the target is less than the left-most if the target is less than the left-most value then we have to search the right portion so we can get rid of this and if this isn't true that means the target is less than the middle but it's greater than the left that means we search the left portions so we can update our right pointer I had a typo over here we don't we're not calling it left we're just calling it L for short and so this is if we were in the right sorted portion of the array the easy thing is if target is less than the middle that means we go left so we can update our right pointer to mid minus one so if this isn't true meaning target is greater than middle and the target is greater than the rightmost value that means we have to go left as well so write equals mid minus one notice again how these two are doing the exact same thing so we can condense them we can say at the top if the target is less than the middle or if target is greater than the rightmost value then we're going to search the left portion so we update our right pointer so we get rid of this and the else condition is that the target is greater than the middle value and the target is less than the right value in that case we only have to search the right portion of the array so we update our left pointer to mid plus one these are all of the cases right so if we find our result we're going to return it up here but if we don't find it we'll exit the loop and we'll return negative one and just as I expected because I just finished this problem like a half hour ago it worked perfectly so this is not an easy problem the code looks pretty easy but you really have to understand the discrete cases like are we in the left sorted portion or the right sorted portion and then what's going to happen as a result which part of the array do we have to check based on the Harrison conditions you really want to dry it out and kind of look at the picture before you write the code I hope this was helpful if it was leave a like and subscribe and thank you for watching
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array `nums` sorted in ascending order (with **distinct** values). Prior to being passed to your function, `nums` is **possibly rotated** at an unknown pivot index `k` (`1 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,5,6,7]` might be rotated at pivot index `3` and become `[4,5,6,7,0,1,2]`. Given the array `nums` **after** the possible rotation and an integer `target`, return _the index of_ `target` _if it is in_ `nums`_, or_ `-1` _if it is not in_ `nums`. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[4,5,6,7,0,1,2\], target = 0 **Output:** 4 **Example 2:** **Input:** nums = \[4,5,6,7,0,1,2\], target = 3 **Output:** -1 **Example 3:** **Input:** nums = \[1\], target = 0 **Output:** -1 **Constraints:** * `1 <= nums.length <= 5000` * `-104 <= nums[i] <= 104` * All values of `nums` are **unique**. * `nums` is an ascending array that is possibly rotated. * `-104 <= target <= 104`
null
Array,Binary Search
Medium
81,153,2273
437
welcome to august seleco challenge today's problem is path sum three we have a binary tree which contains integer values find the number of paths that sum to a given value now a path uh does not need to start from the root but it needs to go downwards we can consider a 5 to 3 here path 5 2 1 a path negative 3 to 11 a path so on and so forth and we just want to find the total number of paths that equal that sum so the most straightforward approach would be to do at that first search at each node so say that we start at the root and check to see while we're traversing down in a depth first search if any of these paths equal eight if they do we increment our total by one and we can check each one for every single path but the problem is the paths don't need to start from the root right so we'd have to also check for this node going all the way down and so on and so forth so the time complexity starts to become exponential but regardless let's go ahead and try to implement that solution the way that i suppose i could do it is to have two methods one for i'm gonna call helper and this is gonna be the thing that actually counts up the path sum i'm going to initialize as a self variable kind of like a global variable here and we'll make that equal total so for now i'm going to pass on the helper method this is going to be the main part where we just do a normal depth or search right so if you remember all that is if not node return otherwise we go left and we go right and finally that'd be it but here we want to call our helper method and what do we want to pass well basically we want to pass the current node and also the current value and that way what we're going to do here in our helper is going to do a depth first search again and we'll say same thing if not node return but we are going to call the left as well as add to this actually we don't need to do that do we um i suppose we will pass in the current and we'll pass in the current here as well and finally we'll say hey if cur plus the current node's value equals sum then we'll increment our total by one and i'm trying to think if i need to add to its current value i suppose i do um i have to add to this current no doubt value and that should be it all i have to do now is call this the first search with the root and make the oh we're going to do that we just need to pass in method well i suppose we need to pass it in here too then uh well i think we just pass zero here i think that's fine finally we turn the self.total finally we turn the self.total finally we turn the self.total so let's see if this works i may have missed something here looks like that's working let's go and submit that and accepted all right so that's great it works but this isn't very good this is um obviously doing lots of repeats is there a way that we could do this in all of end time like we are passing through every single node can we somehow take some value and kind of keep track of everything that we've been through so far rather than just doing it over again so to do that's a little trickier right we have to pass some sort of object so how about we have a dictionary we'll have a lookup table that's going to store um kind of like twosome where we'll store the amounts that we've gathered so far and counting number paths that we can bring over and if we find that yes at this node we've able to get this sum subtracting everything from before then we will add the total number to our total as well okay so that's much trickier but we could do it we can do that and we'll initialize a uh lookup and we'll make this a default dict with integer values being the default value and we no longer need this helper method we could do this all in one different search but to do that we will have to pass in the node as well as let's call it root sum and we need to pass this along to get this right so first let's go ahead and just delete that we don't need that um still be if not node return and now what are we going to do okay so we take our root sum and we're going to add to it our current node's value now we want to add to our self total if anything we've found inside of our lookup table i believe so we look at our lookup and get our root sum and we'll add to our total assuming that something uh is already there so what else now we have to stop the total look up i suppose we have to update our dictionary and what we're going to do is add root sum as well as sum because we have to keep in mind this is going to be as we add up moving forward if we want to uh figure out if we could subtract it's actually adding right so that is going to be called plus one and we'll backtrack here once we're out of this part we will have to subtract the same thing so the only tricky part here is trying to figure out what i need to pass i believe it's root sum and root sum starts with zero so let's see i don't think i missed anything but let's make sure that works i think it does let's go and submit that dang it okay so i missed something up here uh it's um oh you some wideness because i'll put one hmm it might be because i haven't initialized my lookup at sum to equal one see if that's why so let's take this and just make sure this works okay so i believe that's right yeah so i have to initialize of course my lookup start with one otherwise it's going to start at zero so it's not going to add up the ones whether that do equal that sum so here we go this is the o of n solution very tricky um but it's you know if you have those concepts from like two sum before and lookup and you're able to do this that first search hopefully you can kind of get it and understand what i'm doing here so thank you for watching my channel and remember do not trust me because i know nothing
Path Sum III
path-sum-iii
Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes). **Example 1:** **Input:** root = \[10,5,-3,3,2,null,11,3,-2,null,1\], targetSum = 8 **Output:** 3 **Explanation:** The paths that sum to 8 are shown. **Example 2:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22 **Output:** 3 **Constraints:** * The number of nodes in the tree is in the range `[0, 1000]`. * `-109 <= Node.val <= 109` * `-1000 <= targetSum <= 1000`
null
Tree,Depth-First Search,Binary Tree
Medium
112,113,666,687
1,710
Hello Guys Welcome To Another Interesting Problem The Series Cup Coding Old Man Problem Vishal Maximum Unit Certificate To Understand This Problem With The Help Of Example Atishesh Truck End Subscribe Number of Units of Water Units Box Inside a Cylindrical Shells Units and the Answer is What is the energy waste from above such input from left side 0172 units inside and outside and inside were only two family to the number of units can be taken very simple example with just one very simple to keep in mind it is the number of units subscribe unit me is among all the causes beta yes ok so after 10 over pick one up the Video then subscribe to the two maximum units all like this particular Video give a so typing this box and placid near so if total number of ten plus five The Number of Units Which Is Maximum Possible For Giving That Another Example To The Number Of Units Which Can Understand Subscribe Now To The Number Of Units Which Will Give Example The Parameter Number Units Shot The Second Units Shot The Second Units Shot The Second Parameters Possible In Which Is The most number of units is having the most number of units. Of Units Witch State Unit Swayambhu * Play Services State Unit Swayambhu * Play Services State Unit Swayambhu * Play Services First Next Behave 9X Largest Number 90 Comparing Second Parameter Neck Blouse Assembly Notification Next Among Different 7.the Largest to 0.5 The Largest Single 7.the Largest to 0.5 The Largest Single 7.the Largest to 0.5 The Largest Single Elements of Obscurism Number of Units Very Simple But Very Simple Example of a Specific Subscribe How Many Types of Units Account Number Box This Tree Rehearsal Active Listen That This To Select Box This Period Selecting Five Box Surya Selected For Boxes Where Totally Select Box Software Sector-5 Boxes And What Is Software Sector-5 Boxes And What Is Software Sector-5 Boxes And What Is The Number Of Units Switch Off Taken On Facebook Twitter Units of Intent Effective Court Fee Units Next Select Widgets Look at the Next Element Which Supported Descending Order by the Number of Units You Have Lots of Unity Boxes in University Total Number of Units 507 Next to Drops 2018 Do You Want To Know how do you want to be quality selected boxes we need to selected boxes Chuttan - 8 is equal to is just want to know what do we selected boxes Chuttan - 8 is equal to is just want to know what do we selected boxes Chuttan - 8 is equal to is just want to know what do we get from this and what is the number of units into the total number of units Shyamveer What is so Let's move to coding this point to take back right you first to support you all the animals and me to the elements in order by decreasing order number of units and its first president after number of units and subscribe number to the number of do the one thing but here shot upright you for a 10 second of the perimeter visit number of units and vitamins and different that they the first parameter is switched off it will happen by default so this is how to solve the second phase meter is emperor you will have to Declare and structure type and will not to personal computers instead of doing but why don't be used the priority queue subsequent to off shopping superhit monk iso * sort by shopping superhit monk iso * sort by shopping superhit monk iso * sort by default hydride four-five kilometers how can we default hydride four-five kilometers how can we default hydride four-five kilometers how can we use to make a simple app to all the part Of The Number Of Units And Used It Should First Parameter In Do That 154 Vijay Koi Jo Number Of Units Android Pushya Number Of Box Saugandh Advantage Course Will Not Do Anything For Different You Will Start From According To The Number Of Units Which Water Board Middle Please subscribe and subscribe this Video Maximum Boxes Maximum Units Which State Unit Sowe Intersell This is the Quality and Quantity No Respect for Its First Sub Skin Tha Actually You Are in This Way You Want to Say Left Side Lots and Lots of Minutes per Week Unit Certificate Unit Blood Boil Finally Returned And Will Return To Top A Record Of Will Give The First Vairat National Top Most Valued And Which Is The Value Which Is The Top Means Vitamin Maximum Number Of Units Sudesh Value In This Value What Do You To Select You Have To Select the number of boxes for true this account number avoid services vikram the second parameters show this account plus seat is this point be listen what is this is this point be listen what is this is this point be listen what is this overall score in central excise hussain practice awards and side effects in 100s of Five Sentences About 100 Years Since The First Interim The Number Of Units Simply Dot Hai What Is Doing What Is Number Of Units Boxing Number Of Units Work For Example Which In Turn Will Also Bring To Front Treatment Simple Liquid Soap WhatsApp Number Of Account Number One Will Not Be Removed Boys For Withdrawal Definitely Description Box What Will You Collect You Will Collect Free Boxes Rate Of Baroda Tan Is The Greatest Element Alex Reed This Element Is 9 Inch Per Stick Fibrosis Sainik Collection Boxes 538 No What You Collect Next Negative Collect Which You Can Try To Collect This Point But I Don't Have To Collect All The Back To Back System For Lots Of How To Take Off But What You Want To Know On The Left Side Subscribe Thank You All the way that box is Shivalinga treatment account only by love this point is for not sure that you can feel till now full bottle of beer Number of units will change a guy will multiply quantity box is box * Number of units Number of box * Number of units Number of box * Number of units Number of Units Will Romance with B.Com Number of Units Will Romance with B.Com Number of Units Will Romance with B.Com Hotspot Hair Oil World Cup Final A Solid Spine and Images Samay NCC Officer and King The Switch and Acceptable Solution Matric Thanks for Information and Reasoning
Maximum Units on a Truck
find-servers-that-handled-most-number-of-requests
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`. Return _the **maximum** total number of **units** that can be put on the truck._ **Example 1:** **Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4 **Output:** 8 **Explanation:** There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8. **Example 2:** **Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10 **Output:** 91 **Constraints:** * `1 <= boxTypes.length <= 1000` * `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000` * `1 <= truckSize <= 106`
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
Array,Greedy,Heap (Priority Queue),Ordered Set
Hard
null
1,893
hello everyone so in this video let us talk about a problem from read code the problem name is check if all the integers in a Range are covered so the problem goes like this that you are given a 2d integer array as you can see range okay and also two integers left and right now each range of i as you can see each range of I Has a start and end okay now which represent an interval from start to length so which you just understand that you have different intervals different ranges as you can see in this 2D array now you have to return true if each integer in this inclusive range of left to right is covered by at least one of the intervals now what you understand from here is that you just have a range that is from left to right okay this is from left and right this is a range now there are different intervals also okay you just have to understand just tell me that whether all the numbers in the range from left to right are covered by the intervals from this particular array range okay that's it now what covers means let's take a small example of understanding that let us take that we have let's take this example will be left and right so let's say we have uh all the numbers from left to right okay so left right so it is from left which is like two and right which is let's say 5. so all numbers between two and five so which means two three four and five so you just have to understand that all the numbers between two and five should be covered by the Numbers present in this range the ranges are one two then three to four and five to six three two four and they both are like uh inclusive like every number is inclusive so what you understand is that I have you can just assume that there is this is some sort of a Band-Aid okay this is a Band-Aid of a Band-Aid okay this is a Band-Aid of a Band-Aid okay this is a Band-Aid okay this is some sort of or you can say you can just say that this is some sort of a you are like some sort of a bridge okay and you want to like repair this complete bridge and this is some sort of plaster you want to put on the bridge you just have to ensure that all the parts of the bridge are clustered okay so which means that let's say I want to plaster a bridge from one till two okay I will just do a Plastering from this one to two one two to half okay then I want to plaster from three to four then from five to six so as you can see that the complete bridge is plastered you just have to understand it said these are different Plastering type okay you have to do this Plastering on this bridge in the end the complete bridge should be plastered every point in this bridge should be covered that's it there's nothing much complicated so what you can directly do is that you just have to ensure that you just set it over all these let's say ranges one by one and you just make one more let's say array and just keep on Counting how like what is the number of elements this particular range is covering this is covering one and two okay so let's say this is the index 0 1 2 3 4 5 and 6. okay then this is covering the range one till two so one and two range is covered then this is coming three and four so three and four is covered then five four six five and six is covered so this is the complete covering that we'll do we just have to understand that whether our bridge is also good my bridge is from two and five so two is this and five is this so okay this is this whole Paradise cover so that is so just you just have to build this array and then just hit it over this array from this left to write and ensure that all the blocks in this particular range are all covered if it is then answers 12 else answer is false so the overall thing is this only that we have to first make an array of this particular length so from left to right so I just make from right plus one which means that left is also covered I'll just make because the cancer pretty much small okay you can just make complete area of that just all the ranges all the let's say intervals in this particular ranges I just do a for Loop over whatever interval you have and just increment that particular value like how many blocks you are covering while you are clustering this in a of J plus okay so just you're just counting out how many blocks you have plastered like which means that you are just building out this array now you're again doing a follow from left to right and just ensuring that every block should be covered which means that it should be having some value because it is a slice of zero and you have done the plaster which means that you've incremented the value if any value turns out to be zero in this complete range from L to R which is the bridge which means that if any will transfer with zero which means that partner block is not plastered that is not come about in that you know the answer is sponsored I am not completely plastered the complete Bridge okay I've not covered the whole uh you can say the left to right range okay if that is not covered the answer is false if everything is covered this condition never hit then answer is true that's it that's all the logic and the good part for this particular problem as well nothing much complicated because the countries are pretty much small and that's it I will see you in the next one if you still haven't doubts for this particular video I will see you next month including and bye
Check if All the Integers in a Range Are Covered
maximum-subarray-sum-after-one-operation
You are given a 2D integer array `ranges` and two integers `left` and `right`. Each `ranges[i] = [starti, endi]` represents an **inclusive** interval between `starti` and `endi`. Return `true` _if each integer in the inclusive range_ `[left, right]` _is covered by **at least one** interval in_ `ranges`. Return `false` _otherwise_. An integer `x` is covered by an interval `ranges[i] = [starti, endi]` if `starti <= x <= endi`. **Example 1:** **Input:** ranges = \[\[1,2\],\[3,4\],\[5,6\]\], left = 2, right = 5 **Output:** true **Explanation:** Every integer between 2 and 5 is covered: - 2 is covered by the first range. - 3 and 4 are covered by the second range. - 5 is covered by the third range. **Example 2:** **Input:** ranges = \[\[1,10\],\[10,20\]\], left = 21, right = 21 **Output:** false **Explanation:** 21 is not covered by any range. **Constraints:** * `1 <= ranges.length <= 50` * `1 <= starti <= endi <= 50` * `1 <= left <= right <= 50`
Think about dynamic programming Define an array dp[nums.length][2], where dp[i][0] is the max subarray sum including nums[i] and without squaring any element. dp[i][1] is the max subarray sum including nums[i] and having only one element squared.
Array,Dynamic Programming
Medium
53
1,017
uh this question is converted to base negative two so you are giving the integer answer return the binary string representing is representation uh and it's based negative two so um again I if the base is actually two then we will definitely know um the zero degree is definitely one uh the one degree is what two and then 2 degrees 4 and 8 right so the negative for the negative two uh zero degree is one right uh one degree is negative two degrees four negative a for the next one y just you know negative two zero negative two one negative two is three so only thing is what if you notice like this is not changing so the common of the I mean the common of degree layer now changing is actually the even number so if the degree is actually even number we have a positive number like if a degree is negative it's all it is zero this is one this is two this is three then they are actually different right so how do we shift uh shift a sign when we actually uh go into the next degree and we can actually just add a sign uh add a negative sign on the next one right so when we shift so the entire solution are pretty similar to what um finding the integer uh when you're giving the base two name so I'm gonna just keep typing I start typing and then just follow along so I have a stream Builder so if this is a normal base to conversion now which is a pen and then n and one right just find out the last digit I'm using an in notation and then n equal to what and she's right by one if this is what base two right and if this is base negative two then like just put a negative sign over there and when I want to return the only thing I have to check is like if the length is actually greater than zero then what I need to reverse right I need to reverse then convert to a string else I just return zero and if this is base 2 you still have to reverse I mean this is the simple stuff right so if you know uh if earn is actually equal to a right and the buying machine is actually one zero right and then uh what we want to just using it I mean just uh shift right every single time when we append the last digit we will get zero one right and then we want to return we definitely need to reverse then the binary string of n is definitely correct so this is not matter of negative two base it's also a matter of positive pauses too so just have to reverse and this is straightforward enough submit so let's talk about the time in space this is going to be a time and I'm going to say login why every single time you shift right by one it's actually a base two right and then the time is actually what log base 2 of n right and then if this is what base negative three then you know base three of your friends something like this right and the space you know space is the uh it depends I mean it still depends on when so it's only it's going to be login and then the base is to I you only need the length of the I mean development length right so uh just you know like I'm gonna just run some ball so let me see 17 and using debug mode start debugging so let me run it so look at this bye I'll press one zero one and you can double check right so uh again like this is straightforward enough and just a little bit thinking when you want to convert to a negative all right so um if a question leave a comment below subscribe if you want it alright peace out bye
Convert to Base -2
odd-even-jump
Given an integer `n`, return _a binary string representing its representation in base_ `-2`. **Note** that the returned string should not have leading zeros unless the string is `"0 "`. **Example 1:** **Input:** n = 2 **Output:** "110 " **Explantion:** (-2)2 + (-2)1 = 2 **Example 2:** **Input:** n = 3 **Output:** "111 " **Explantion:** (-2)2 + (-2)1 + (-2)0 = 3 **Example 3:** **Input:** n = 4 **Output:** "100 " **Explantion:** (-2)2 = 4 **Constraints:** * `0 <= n <= 109`
null
Array,Dynamic Programming,Stack,Monotonic Stack,Ordered Set
Hard
null
82
hey what's up guys this is john so today lead code number 82 remove duplicate from sorted list number two so you're given like a sorted linked list and you need to delete all the nodes that have duplicate numbers and leaving only the distinct numbers from the original list return the linked list sorted as well so for example right we have one two three we have this list here linked list and we need to re remove all the out duplicate numbers which means that we have we need to remove those two threes and then those two fours pretty straightforward right so but since the little the only difference for this problem is that we need to remove all the numbers that have the same numbers so which means that you know when we're at like two here right we're from one we go to two and from two uh we should not go to three because we will need to go to four and then maybe from four uh we will also since there is like two fourths here from actually we shouldn't go to four we should go from two to five directly all right okay since we need to remove some of the numbers so for this problem you know oh it's better for us to maintain the current one as this one so this is the current and basically and then we will check the current dot next and the current dot next so basically we're checking if the next two numbers are the same then we know okay so we will we need to remove the at least two numbers otherwise if this the current if the current next that is not the same as the current x dot next then we know okay we can safely move the current cursor to the current dot next right so this is if an else right so which means that you know so if the current if this one is the same if they are the same then we i mean we will not move the current cursor forward because we might have like we will need to remove some of the nodes after the current one and we will only we're only like moving forward when this condition is not met and that's how we escape the uh word or delete those duplicate numbers and when it comes to the coding actually it's pretty pretty short right so as always right so for this kind of delete or changed linked list we always uh create a dummy node right and so for this one the dummy we need to create a link for the dummy nodes right so domino's next equals the hat and like i said the current equals to dummy so keep it notice here the current does not equal to hat the reason being is that you know like for example this two here uh not example two here uh the first one the hat might also be duplicated right so which means that you know from the dummy it could directly jump two to two that's why the current is a dummy and similar like while current right so while current something and then in the end we return dummy dot next okay so like i said so since the current for the current one we check if the current dot next uh we first we check if there are like two nodes right if there are and then we check if the current if the next one dot value is the is equal to the current dot next dot value right so if the next two numbers are the same then we know okay we have to remove at least those two numbers but we might also we might remove more so more nodes so how can we do that so for that i'm going to create a temp attempt node so i'm gonna the time node will start from the current dot next so something like this right so if we have like one and then let's say we have two let's see we have two uh four twos and then we have another three here something like this so we are at one right so this is current and then we check if the current dot next which is this one that this is the next right and this is the next dot next if the next and the next dot next are the same then i'm going to create a temp like node pointing to the to this one right so this one is temp and i'm going to loop uh moving the time forward right from here basically while the temp and the temp does next if this one and the next one are the same dot value equals the temp dot next dot value if they are the same then i move the temp right basically the move temp dot next so and what i know once this while loop is finished the time is what the time is it's right here right because at this moment the temp dot next they're not the same this is the temp dot next right they are not the same or what they're well there's no time dot next node at all so in this case the temp is it's right here so now we can move the current cursor right basically we move the current cursor to what so the current we're not moving the current cursor forward but instead we're redirecting the current one to this one so we're redirecting the current one to pointing to the three here so current.next equals the temp so current.next equals the temp so current.next equals the temp dot next yeah right so because at this moment the current is still pointing at one here you know there could be uh you know let's see if they're like two threes here right so if they're like a another duplicate three here so the next while loop the current dot next it will check this condition again and then it will move uh keep moving the cursors uh forward again so that's that and else right like i said so we only move the current cursor forward when the if is not true so which means that the next one is not duplicate one then we move the cursor to the next so here like the uh if next two notes hard duplicate right move the curse move the temp move the current dot next forward right so here like the uh if next two nodes are not duplicate right move the current to current dot next yeah i think that's it so run the code yeah submit cool i think that's it right i mean the uh so the only difference for this one comparing to the other like a linked list problem is that you know we are we're maintaining like the uh the current one not the and we're looking while maintaining the current cursors we are looking for the next two nodes all right and if the next two nodes are the same then we try to extend uh that temporary template temporary uh point uh cursor so that we can move the current next forward and then if the next two numbers are not duplicates then we know okay so the current.next is the number basically current.next is the number basically current.next is the number basically the current.next will not be removed and the current.next will not be removed and the current.next will not be removed and then we can safely move the current cursor to the next one otherwise we just keep skipping right um yeah i think that's pretty much i want to talk about for this problem and yeah thank you for watching this video guys then stay tuned see you guys soon bye
Remove Duplicates from Sorted List II
remove-duplicates-from-sorted-list-ii
Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,2,3,3,4,4,5\] **Output:** \[1,2,5\] **Example 2:** **Input:** head = \[1,1,1,2,3\] **Output:** \[2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List,Two Pointers
Medium
83,1982
326
foreign with the lonely Dash and today we're going over leap code question number 326 power of three which states given an integer n returned true if it is a power of 3 otherwise return false an integer N is a power of three if there exists an integer X such that n equals 3 to the X so what does this mean well it just means that we need to figure out whether N is a power of three that's not the most complicated thing in the world um and the way we're going to solve this um is well there's a couple of different ways we can solve this in fact though I think maybe for this video we will solve it in two different ways so how are we going to do this well let's take a look down here to an iterative approach um so first and foremost when we're thinking about what n is going to be because 3 is going to be 2A power um n is always going to be positive right so it's always going to be positive so let's say they give us the number 13 we need to figure out if 13 can be a power of 3 which we know it's not right because 3 to the first power is three to the second power is nine three to the third power is 27 so there's no integer that will come along where we will reach 13 right so if we take 13 we divide it by 3 we end up with 4.3 and because this is not a whole 4.3 and because this is not a whole 4.3 and because this is not a whole number then we also know it can't possibly n 13 cannot possibly be a power of three I think even the example they give us on the website it says what if n is 27 well we know 27 divided by 3 is 9 divided by 3 is 3 divided by 3 is 1 and because we got to 1 we know that um that 27 or N is a power of 3 it is in fact 3 to the third kind of looks interesting there so uh in order to solve this iterative approach this is all we're going to do we're going to divide n by 3 and if it comes out as a whole number then we're just going to keep dividing until it gets to 1. if it's one then we're going to return true if it's not a one then we're going to return false so that's the first approach that we're going to do it's pretty simple and straightforward the this is all of the iterative iterations we're going to need in order to solve it but there is an even easier way of doing it and we're going to talk about the mathematical approach now if we get a little bit more into computer systems we know that the largest 32-bit integer know that the largest 32-bit integer know that the largest 32-bit integer that we can process is oh look at this I must have left out some left out a number or something like that it's something I got to look up this number it's 2 million oh yeah it's 2 million 147 483 yes that's right is this big old number which um the closest number without going over that is a what do you call this thing a oh my gosh I can't even remember a power of three thank you the word power just flew out of my head is a power three is three to the 19th right because 3 to the 20th is larger than this number so we give us a bad answer but 3 to the 19th is below this number now all we have to do is take that big old number and determine that if we divide it by n that there is no remainder then it is a power of three so this is the most simple way of doing it but a lot of people don't think about uh 32-bit integers being think about uh 32-bit integers being think about uh 32-bit integers being this way to work so that's why we're going to do this in two ways we're going to do this iteratively first and then we're going to solve it in the mathematical way which is just taking the modulo of the largest value uh that is a power of three and determining if it's zero so let's take a look at any of the constraints and see if there's any other edge cases that we're going to have to consider for either of these approaches and look at that all the constraints say is that it's going to be an integer n that is within the 32-bit stream so uh that is within the 32-bit stream so uh that is within the 32-bit stream so uh nope there is absolutely nothing to consider for our edge cases we can just move on to writing I guess two sets of pseudocode okay so for our pseudocode we're going to do two different ways of solving this problem so the first one is the iterative uh solution of the approach and the second one is the mathematical approach so the first iterative one right so this is going step by step the first thing we need to know is that n always has to be greater than zero so that's we're just going to do this iteration while n is greater than zero what are we doing while n is greater than zero well if n divided by three is a whole number right so basically if we keep dividing over and over again and it's a whole number that means it's possible that it is a power of three so if n divided by 3 is a whole number what do we do um what are we doing we're saying n now equals n divided by three we're reassigning the value of n so I'm going to write that in then re-assign the to write that in then re-assign the to write that in then re-assign the value of n to n equals n divided by three done pretty simple uh otherwise if n divided by 3 is not a whole number what do we do well we're just going to break out of the loop because we know at that point that um that it's not and I guess you could say return false because we know it's not going to be a power of 3 but we're not going to do that in this case just because I want to build this slightly differently then once that Loop is broken we can ask ourselves if n is equal to 1 right and we're going back to where we were talking about once it gets down to one here then we know it's a power of three so if n is now equal to one then return true if n is not equal to 1 then return false and then we're done so that is the entire iterative uh way of solving this problem I don't think it's all that confusing but it's pretty simple the mathematical one is even more simple right the first thing we need to figure out is the same thing if n is less than zero we're going to return false because remember it has to be a positive integer the next one is if 3 to the 19th power divided by n is a whole number then we're going to say yep it is something that is 3 to that whole number will equal n then we can just return true on the converse if 3 to the 19th power divided by n is not a whole number what do we do while we return false so those are the two ways of solving this problem let's copy them let's paste them into our work area and let's get coding here we are in the Python 3 work area of the leap code website and we're going to do our iterative approach first the first thing we have here is while n is greater than zero so while n is greater than zero because remember if it is zero or less we just have to immediately return false but we need to manipulate n first if n divided by three is a whole number or in this case if n divided by 3 has no remainder then what do we do well we're reassigning the value of n to be n divided by 3 and this will continue to go all the way through until uh n is um less than zero or we tell it to break so else we are breaking out right so that's if n modulo 3 is not zero so in this case we're really kind of looking to determine whether the final value of n and is one or not so we can kind of continue on saying if n is equal to 1 then we can return true so if n equals one we are going to return true else if it's not one then we're going to return false and that should be all of the code now some people get a little bit confused on how this will run until you know n is less than zero how in the heck are we ever going to have a one here well n can end up being 1 where n modulo 3 is actually one so n that becomes 1 divided by 3 becomes less than one if that makes sense so I promise you that when n becomes one so if this is 3 divided by 3 n becomes one we ask ourselves is one greater than zero yes if one modulo 3 equals zero well no one modulo three equals one that means we're going to break out and N is going to be able to equal one so let's hit run see how we did and it does work and when we hit submit we're going to see that it's a fairly quick um oh I should say memory is not bad 32 92 should be faster than 30 I would think let's give it another go just for arguments sake oh there we go 70 so it is a pretty fast way this iterative way of solving uh the question but there is a much simpler way what we can shorten so this is way number one highly suggested iteration is good however let's try mathematical so what I'm going to do is I'm going to comment out all of this lovely code and I'm going to delete our initial set of um pseudocode and we're going to do the mathematical approach and we're going to kind of tear it apart slightly so first one is if n is less than zero we're going to return false okay so here we go if n is less than and I think I may made a mistake here because it can't equal zero either so if n is less than or equal to zero then we're going to return false now uh the next line is if 3 to the 19th divided by n is a whole number so if n to the 19th power or sorry 3 to the 19th power I made a mistake 3 to the 19th power divided by n is a whole number so we're going to do kind of the same thing we're using modulo n equals zero so if that's the case then we can return true else meaning that 3 to the 19th power modulo n doesn't equal zero else we're just going to return false and we're going to see if that works and if it does we're going to shorten it even more it does seem to work just fine so how can we make this shorter well we're just going to take all three of those and put them into one return statement we're going to return whether n is greater zero and whether 3 to the 19th power uh modulo n is equal to zero and that should be everything we need to have in order to answer this question and we'll hit run and there it is so if I hit submit we're going to see hopefully that this is not too bad okay at about 50 of each I'll always hit submit twice to see how we do the second time um maybe a bit better there we go 91 in run time because really it's only one well I guess it's two there needs to be two actual calculations is n greater than zero and is this a thing so um those are the two approaches which I would make with python in order to solve uh question number 326 power of three both iteratively and mathematically foreign
Power of Three
power-of-three
Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_. An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`. **Example 1:** **Input:** n = 27 **Output:** true **Explanation:** 27 = 33 **Example 2:** **Input:** n = 0 **Output:** false **Explanation:** There is no x where 3x = 0. **Example 3:** **Input:** n = -1 **Output:** false **Explanation:** There is no x where 3x = (-1). **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Recursion
Easy
231,342,1889
92
Everyone Welcome Statement Reverse Link List You have not given us anything in this question but please have given us a hand note and have given us an index, meaning initially the head will be index 1 and a left index has been given and one on the right position. If the value is given then the left position is mine and the right position is mine in this example, so what I have to do is to reverse my list from tu to 4, okay and I will have the rest in my output list. The list has to be kept in the same order but from left to right it has to be given in reverse order. In this question we have to give our left hand text kitna tu and right index kitna given four. So initially what do I have to do. See even. Like this index of mine is 1 2 3 4 5, so what I have to do is to keep my list before 2, it, etc and my list after 4, I have to keep that also in my output list. So how will I tackle this, I have to reverse some of the list by breaking it from here and reduce it with some margin, so look, for that I will keep my two pointers, one will be my previous which will point to which initial, null is fine and one in What will I keep, I will keep my current pointer, which initial will point to, my limit will point to the note, English: Okay, so limit will point to the note, English: Okay, so limit will point to the note, English: Okay, so what is the value of my left, if you are there, then I will keep moving my current till I reach where I am, till my you. If she doesn't reach then first of all my value position is Van but because of that she is younger than you so I will simply take my previous where will I take the current and where will I move the current next to the current is ok in this position. What is my current position number? What is your position and what is my left? If you have given me, then from here to the next one, what do I have to do? If I want to reverse, what will I do? I will preserve one of my forward nodes so that I can If there is no extra space, what will I do if I have to forward it, so I have made a picture and which is my current note, I will remove the current note from here and create a separate one in which I will reverse mirror it, I will keep my link list, then my How long will you remain and you are one of mine, I tell you, this is my head and the oil, both of the initials are making some point, this is you making some point and here as mine, I have reversed it, I have made it new, but To whom will this previous one still be pointing? You must be pointing to me. It is okay because I have never broken this point, so what will be the current, after it decreases, where will the current reach? It is okay in the forward direction again. What is mine, what is this to me, what does this mean to me, till where is four, the value of the right key is four, so till four, what do I have to do, if I want to reverse, then again what will I do, I will make a forward and remove my current note from here, in which I will attach my reverse one, so how tight will mine be in this, three will be attached, this is mine, this will be attached in the next one, and the one which is my head, now who will the head point to, will it point to this, okay, so from here this is mine. The head will be removed, mine will point to the three and again where will the current mine go, will go to forward and the forward pointer will not be mine, it will point to the next of the current and again I because if it is four then what is the value of right if it is 4 then here What do I have to do with my current, I have to tap the next one of my current and if this is my current one, then the current one should go in my reverse mirror, then I will go for the current one in my reverse, I will add it first and I will make it point C position. This is my fifth position, but to what extent do I have to reverse? If I have to reverse till my fourth position, then what will I do in this case, which is my previous node. So look here, all my pointers are like this, then I have to What do I have to do? Who do I have to attach in the next part of my previous list? The head of my reverse list is fine and the head of my reverse list is fine. Who do I have to attach in the next part of my list? Forward is to be attached, okay, so simply I have to return my who, in this my head over English will be the same, but in this case, who has become my direct head, who has become my current head, but sometimes this can happen. Like if it is 1, 2, 3 and 4 and 5 then what will I say from where to where do I have to reverse my list? What will be my next case that I have to reverse my list from 1 to 2 then in this my How much was the previous tap, will it be ok and what will be my current, then I have to reverse it from the van itself, this is the first position, second position, third position, fourth and fifth position, so there is something in this, what will I do with this type of current of mine. I will take it here and this is my head and my oil will point here and the current will flow here, then I want you too, so then I will remove this oil and attach it to this, then my head will point here, okay. And if the current reaches next to the current, then it will reach here in the current. Now what is the index of this? Three, so my right index is till you, so I just want to tell you that my initial here was the previous one. Neither in the next of the previous, I had put this head which is the head of my reverse list but if ever my previous is null then in that case the head of my link list will be this one of mine which is the head of my reverse. Its link will be the head of the list, okay, and from here, you always have to put your forward in the next part of your oil. Okay, so to understand this size, I will explain this to you and talk about time and space complexity. So what I have done is that I have taken the current pointer of my link list to the end, then I reduced the time complexity of the point to N and the space complexity of my list, I removed the corresponding points of my list. If I reverse it, my space is not taken. Okay, so let me code it and show it. How will we code it? What will happen if my head goes to the right, meaning both left and right are at the same position, there is no date to point to the same index. So simply what will I do in this, I will return my add, I will return the English which was found in the input, I have to return that English in the output, adervise, what am I doing, make my list note 2 pointer because below which I am making it. I am making a current point because it will point to the head note and what do I have to do at the bottom, I have to take my current up to where till the left, so I take one of my bricks, my idea would be that it would be a van, okay. So here I am, it will be smaller than my F, which means how will my left be smaller, what am I doing in this, I am simply pointing it where is it currently and where is my current going, next note of current. Okay, Else, either here or here, what condition can you put in place of it? You can put your A condition, but it will check after being in the air, so you put it in such a situation, what should I do if what is there on me if that? Has reached left. Okay, if he has reached my left position, then what I have to do is to create a forward note. To make forward, whom will he coin, will find the next one and what I have to do is to create a forward point and which Apna current is his next, what do I have to point to and what is the current, what do I have to do with the current, what will happen to me, what will happen to the reverse, that will be the head of this, how much will you be equal to, what can I do to him, because my reverse list. If it is from left to right then what will be its head and what will be its reverse, to whom will both of them point, will they point to their current note, if it is not so, what will be in it, which will be my current will be like this, line number 29 From line number 34 to line number 34, my logic is and first logic, okay, so when I add first, what was I doing after that, where was I moving my current point, I turn my face to forward, okay mine. The position is notification, so I was simply moving my calendar previous forward, if I want, forward here, if I want, I will go to the next, okay, I will come out from here, what will this mean to him, what will be the previous point, how far will he point left? This will point to the previous value and that will be my forward point. Point to the next value of the right key. So see, I have to make one less in this which is the match of my reverse key. Next of that I have to attach it to someone. You have to attach the forward note. Okay, forward whatever you have to say because after that my current is fine and what do I have to do from here, I have to check. If my previous note is not there from = 1 to the name of the van then not there from = 1 to the name of the van then not there from = 1 to the name of the van then I have to go to previous next. I have to touch someone's head, the head of the reverse note is fine and else if my previous note is taped, what will be my previous nail in it, which will be my head, what will become of the English's heading, what will my heading of the reverse note become, okay? And when I return from here, what will I do in the return, I will get my English head not going back because what is the case in which my English head was changing, the value of my life will start from the van, so I told him here. I have handled it, if my previous is null, then in that case, the head of my list will be updated, what will be equal to the head of the reverse, okay, so I run this, second, sorry, I have used equal operator here. Sorry, I have applied assignment operator here, so I have to apply double equal tu operator here too. Can you find the symbol, that is my one for Nokia, current is defined, meaning in our reverse current is defined in our function. What have I done to this, I have turned it, I will submit it and watch it. Accepted and thanks for watching the video.
Reverse Linked List II
reverse-linked-list-ii
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_. **Example 1:** **Input:** head = \[1,2,3,4,5\], left = 2, right = 4 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[5\], left = 1, right = 1 **Output:** \[5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 500` * `-500 <= Node.val <= 500` * `1 <= left <= right <= n` **Follow up:** Could you do it in one pass?
null
Linked List
Medium
206
450
hey there and welcome to another leak code problem it's going to be problem number 450 delete note in a BST so we're given a root node reference and a BST and a key and we need to delete that node and return the root reference possibly updated of the BST so for those of you that don't know a BST is a binary search tree meaning all the nodes to the left of a node are smaller than that node and all nodes to the right of node are greater than that node so you can see like here's a five so everything here is going to be smaller than five everything here is going to be bigger and so on so same thing here so it's giving us an example of where we try to delete node number three and so when we delete node number three it's saying you can place this 4 up here but another valid solution would also be we delete this three then we have a two up here and then we put a 4 over here okay and then also if we don't find the node then we just iterate through this tree and we just return the tree back so let's think of different cases that we can have for deleting a node so case one let's just actually make this yeah so case one our node has zero children so well what do we do like let's say we try to delete this node what do we need to do well we just get rid of it and we update this right pointer to be null right or none or something okay now case two one child which would be like this node right this node has one child so that's pretty straightforward as well right we just take whatever node this is we delete it and then we replace it with the node that it's its child it's left or its right and we just update the whatever this node so this is the right we update this right to be this node okay what if it has two children right the most complicated case so in this case it's a little bit straightforward but let's say instead of that what if our node what if our tree looks something like this let's use or actually let's use this tree right here right so let's say we try to delete the root what would that look like so that's the third case is we have three children zero children pretty straightforward we delete the node two children or one child we just replace it the node with its child now the third case is two children so what would we replace it with a three would we replace it with a six what makes sense and so the way to delete in a BST the algorithm for deleting in a BST is you need to take whatever node is the this node's successor in this whole tree and what a successor means is the first node that is a greater than this node so in this example it would be six so what we need to do is we need to make we need to change this to a six then we need to delete the six and then this can just be a seven and by the way so the way we're going to be doing this problem is instead of deleting a node so instead of just deleting a node we're going to be actually replacing the node and then we're going to be recurring down so for example let's say we try to delete five and we find this node 6th that it's its successor so we're going to say okay we tried delete five we find the six and we're going to say six is a successor so then we're actually replace this value 5 with a six and then we're going to call delete on the right subtree of this tree and then what and then we're going to return that value and make that the right subtree so if we're here we try to delete five we make this a six now we go down here we try to delete six right and so it's going to be recursion so we tried delete six same thing what's its successor it's going to be seven so we replace the six with the seven and then we go down here and we try to delete seven and then finally when the root has no children we can't recurse down anymore so then we just pop off the seven and then we return none here we return 6 here or sorry we returned seven this would be a value seven and so we're gonna update if we TR we're trying to delete a node instead of deleting the actual node we're just going to change its value to the successor and then we're going to delete the successor and we're going to keep recurring down until we can always delete some node that's a leaf node now here we found the six quite easily right because it was just the next node but what about if our tree is like this right so our tree's five just say one now let's say it's like this let's say this is 10. and then we have some other stuff here like eight seven nine twelve let's say okay well what about in this case it's not just going to be the successor node of this five isn't just the nodes to it's right it's not this node so in order to find the successor what you actually need to do is you need to go one to the right so we're going one to the right and then you need to go all the way to the left from where you're at and that's going to give you the successor so we go to this 10 and we say while this node is not empty we just go left and so the successor 5 is actually going to be 7. so then we place the value 7 in here and then we just call delete on this node with seven so it would try to call delete on this node with seven and clearly this is not oh by the way so the other case is let's say we're on a node and we're trying to delete like node seven what we're gonna do is we're gonna say okay well if this node is not the one we're trying to delete then we need to recurse down the correct subtree so if the node is bigger we recurse right and if the node is smaller we occurs left and so in this case if we're at 10 here if this node is 10 then and we're trying to go 7 so we're going to go left is this node 7 no okay we're going to go here okay perfect we found the seven it has no children so we don't need to replace anything we just delete this node straight away and then we just return and so our solution here would be one seven and this should always work out if you go one to the right and then all the way to the left right so 1 7 10 12. and then here we have an 8 and a nine so that would be the solution for that where we did get rid of the five but we kind of hacked it where we replace its value instead of deleting the node directly because if you delete node directly it gets really tricky you have to rearrange the whole tree so instead we're just going to replace and keep deleting further on down and that's going to be our algorithm so let's try to code that up so first of all we're gonna have a helper function or just call delete and that's going to be on a node and we also pass in a key right we might be able to just call delete node directly I think uh but let's write this up and then see if we can get rid of the function so first of all if the node is none then there's nothing to delete but we need to still return so okay now the other cases remember are if the key we're looking for is bigger or smaller than what we're trying to delete right so then in that case if p is smaller then a bell then we just say no dot left and we have to keep reassigning this because for example if we're here and our key is four we are going to try to delete four or actually no there here's a better example so let's say we're like this our node is 5 4 6. and our key is four so we're here we go left we delete this four now this becomes none and we return none so that's why we need to say the left or the right child equals whatever the return of the function is because the left or the right child might get updated to none and so we need to say that so no not left equals none or not none sorry it's going to be delete and we've got left key so that's going to be that case other case is if key is greater than no doubt l same exact thing okay so this is no dot right key and now the other case is it's this right so the last possible case we have is if the node is equal to the value we're trying to delete and remember we have multiple cases for that right so the first case is if the node has no children we can just delete the node straight away so we can just say if not node dot left and not node.right and remember this else case node.right and remember this else case node.right and remember this else case means that the key is equal to the note value so if that's the case we just return none that's how we would delete and then whatever this node got called from would get updated its pointer would get updated on so we're not really deleting we're just saying this node is no longer a child of anything okay so that's one case now another case is if there is a left and there isn't a right or if there is a right and there isn't a left so in that case if and remember what we do in that case is we just replace it with that node right so if node .left uh yeah so if node not left but we don't want to have two so and not node.right then we just return node.left because for example if for node.left because for example if for node.left because for example if for this if we're trying to delete this node and we're saying the left of this is whatever this returns we can just return this node right here and so the left of this five will be two okay so that's that case then the other case if this is the other case so if no dot right and not node.left node.left node.left then we return node.right then we return node.right then we return node.right and so the final case is if there are two children right because this is no children this is the left this is the right so here we need to remember we need to go one to the right and then all the way to the left right so we can just say Cur equals no dot right and then we can say while Cur dot next does not equal none right so while we can go left actually this wouldn't be let next this would be left okay so now we went to the right and all the way to the left now what we need to do is we need to get that value right and then we need to replace that value we need to put whatever value that was so let's say it was a six we need to put that into the node that we're at so node dot val equals curve.val dot val equals curve.val dot val equals curve.val and now remember the successor is always going to be to the right assuming we have two parents so now what we need to do is we need to call delete on this right section and then we need to delete so let's say we in this example let's say we are trying to delete five here so our net now we replace this five with a six and now we need to call delete on this right node with the new value we're trying to delete which would be a six so we're basically taking the value of the next node putting in inner node and then just calling delete to delete the next node instead of actually deleting the node in place because like I said that would be tricky like how would you just if you don't have two children and you just delete those pointers and like it's hard to know what goes there and that's very hard to keep the same tree structure okay so node.valuable Square dot valve okay so node.valuable Square dot valve okay so node.valuable Square dot valve then we can just say node.write equals then we can just say node.write equals then we can just say node.write equals and then we're going to call this delete function node.right and then our new key is going node.right and then our new key is going node.right and then our new key is going to be remember we're deleting the node that we the value that we just updated this value to so if this is a six we're trying to delete six now oh okay and finally so we just returned the node itself now let's think about if we can actually do this like do we even need this delete function or can we just do this in place I think we can just do this in place to be honest and so instead of this being node this would be root though so root just copy all these so root I could do a finder replace but so because we are using the exact same um like we have the same thing we have a node and a key so root okay and then we also need to make sure we bring these back so all right and then incentive returning node we return root okay so let's double check this and then we're gonna let's try submit so if not node we return none if key is less than root dot val this should be fine if key is greater then you're done right else if not root dot left and not root does not return none if we're dot left and not root dot right okay if we've done it right and not read without left return cursory dot right okay read that value square dot val root dot rate okay let's try to run that all right so this should be and all these delete should we delete nodes so uh all right okay so this needs to be solved that deleted oh I guess should be root okay great uh all right um okay so that worked so let's try to think about the time and space complexity for this so time well what are we doing we are deleting but worst case scenario so once again this is not a balanced BST and so if our BST is like this right or it's for example let's say it's like one two and so on just one greater and then the key we're actually trying to delete would be like maybe this Leaf node in that case the complexity would be o of n where n is the number of nodes but on average complexity if the BST is more or less balanced then it's going to be of log n so worst case is O of n averages log n because it'd be a any kind of tree iteration to find something is going to be log in if it's balanced because we're a great integrative half the elements every time get space so it's going to be the same thing the space is going to depend on the recursive call stack and so worst case scenario once again if we have this linear thing then the recursive call stack is going to have n recursions and we're not really returning until we get to the very bottom so that means same thing where worst case is going to be omn and average is going to be the goal of longing all right so that's it for this problem and if you like these kind of videos like And subscribe it'll help grow the channel and see you in the next one
Delete Node in a BST
delete-node-in-a-bst
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return _the **root node reference** (possibly updated) of the BST_. Basically, the deletion can be divided into two stages: 1. Search for a node to remove. 2. If the node is found, delete the node. **Example 1:** **Input:** root = \[5,3,6,2,4,null,7\], key = 3 **Output:** \[5,4,6,2,null,null,7\] **Explanation:** Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is \[5,4,6,2,null,null,7\], shown in the above BST. Please notice that another valid answer is \[5,2,6,null,4,null,7\] and it's also accepted. **Example 2:** **Input:** root = \[5,3,6,2,4,null,7\], key = 0 **Output:** \[5,3,6,2,4,null,7\] **Explanation:** The tree does not contain a node with value = 0. **Example 3:** **Input:** root = \[\], key = 0 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * Each node has a **unique** value. * `root` is a valid binary search tree. * `-105 <= key <= 105` **Follow up:** Could you solve it with time complexity `O(height of tree)`?
null
Tree,Binary Search Tree,Binary Tree
Medium
791
1,930
hello hi guys good morning welcome back to the new video uh I hope that you guys are doing good problem unique length three of three unique and three paric subsequence uh so like initially when I read the problem I thought it's a DP problem but it was not let's see that how we approach it and how we actually see the hidden hints in the problem statement itself so uh if we just usually start reading so it just says that we have a string s the number of unique pal Andres of length three so first thing is unique parres of length three we have to find which are the subsequence of s now subsequence you know I know that is just in the order but you can skip the characters cool now uh a Parr is just what is something which reads forward and backwards same now and it just says that not that if there are multiple ways to obtain the same subsequence it is still counted as a one way so if I have ABA and there are multiple ways to get a Aba still that ABA is just a one subsequence so it should be down just once you'll see that with an example itself but yeah and it just shows what's patter what's the subsequence so uh what so if you just go and look so first thing was it should be of three length it should be a Parr of three length it is for sure that these two characters will for sure be same right this can be different so one thing what we can infer from our point is it's a p of length three so for sure the first and last should be same the middle one it can change so what we can do is okay I know the first character is this I should simply go and check okay I just want a last character right I just want a last character which should be same as that so I can just go and find for the other character which is same as that of me now Aran there can be multiple other characters it can be a here which one are you planning to choose I say that let's take anyone let's take the middle one a for now let's take and let's see what will happen so okay for sure if I take one of the other is now in between I can take any character as in any of these I can take so shall I okay if I know the index is I if I know the index is J so I'll know okay if it is a 0 1 2 3 4 five and six so I know for sure I have the five characters in between so shall I take and say for this particular IG pairer I will have five subsequences can I write that no I should not why I should not because for sure this I know it is a okay the this next a at index one and then this a it's a one subsequence okay that's a great subsequence AA but if I just go and ask again if the first a at the index zero and the a at 1 2 3 4 index 4 and then again a is it a subsequence yeah it's also AA so for sure you counted that thing a twice so whatsoever you are taking in between take it unique so I will go and check in between this I and J what all are the unique characters a b c a they are just three unique characters so for sure the number of subsequence which this IG can contribute are three now are okay it just seems fine that we took the starting and the ending as same and for sure we took one of the A's which are forward to us and then corresponding to that we know okay in between I have these characters so are we planning to choose the j and every J are we planning to choose I'll say no why no because let's say you took this J right or let's say you took this J if you took this J right here still you will choose the number of unique characters in between right now number of uni characters are 0 1 2 and three if you took this J still you will just choose the number of uni characters in between right so ultimately what we are trying to say is if you go and look at this example small example so if I had a here I am planning to choose this right a if why not some other a or why not some other I or J so I it was this J why not some other I or J now if I am planing to choose let's say if I just choose this next I and this J still you will see that it will actually make a subsequence as a any one of these two in between which is a either B or C and then a this is exactly same as what we saw if we have taken the first a itself so ultimately as a are same as a is same so it is very beneficial for me that I'll take the first a and the last a and anything in between will form a subsequence for it now what it happens I take this a so anything in between a I take this a and now anything in between these three I firstly check okay what are the number of unique characters in between and for sure that will be my number of things which can come in between of this a and why it will not affect my answer because ultimately even if I have another a b c another a then still if even if I take this J then still what I will get is this a I can get but this a is also same so for sure unique characters a b c okay let's have it at D or E so what will happen is I can have a b c d and e now what if you were saying okay if I would be having I here then again you saw if I was here then still you would have got a d and a which is same as what if you had a i in the beginning so I is just showing I and J are just showing the location of a to better take the extreme locations of a just on the extreme left and on the extreme right for sure you will can include everything in between you just want number of unique characters so as to form number of unique subsequence starting with that character A and it will not affect us because for sure I have only of length three I don't have to go multiple in between I just want the number of unique characters in between of every character which means I'll just go and find okay what is the first location of every character last location of every character and I'll go and do it for every character which means I'll have it for a b c d and so on so forth up to Z I'll go and find okay what's the first occurrence it's a zero last occurrence 0 1 2 3 4 last occurrence is 4 and I'll go and same make it for everyone if not then by default I'll just keep it minus one now I know this is one it can form one subse one parent R of length three so I'll just go and check okay what are the number of unique characters in the length 1 2 3 I can just take a sub like I can unordered set and put all these elements of in length one 2 three and I can just check okay what's the length what the size of this particular set or sub or like unordered set and that will give me number of unique characters in this length 1 2 3 and with that I can just go on to all the 26 characters and just check so it will be nothing but 26 + n check so it will be nothing but 26 + n check so it will be nothing but 26 + n that would be pretty much it let's see again uh why I thought of initially DP was because I thought okay it's a subsequence so maybe I have to figure out but then the catch was the length three in the length three you just need and again it's a palr so you need only the first and last letter as same in between anything can change now to make the first and last letter as same just keep the first keep the last same take the extrem ends so that everything in between you can take right cool let's jum on the code uh it will be pretty much as what we saw that firstly we need to have an unordered map uh saying okay for every character what is the first and last location for it so I can have a pair just saying that for every character I will have so let's have this character so it will be start from a less than equals to Z and C++ now for less than equals to Z and C++ now for less than equals to Z and C++ now for this character we are just mentioning that it's starting and ending locations are 0 or rather what we can do is we can just keep it in Max and minus one and then update it accordingly it's up to you like how you want to do it so like you can actually have it as int Max and minus one also now uh what I'll do is I'll firstly try to have the initial what is the start index for every character and that should be upd only once because I want the earliest start index of every character so I'll just go on to the entire length now I'll just say okay bro the current character for me right now is s ofi so this character if this characters if like it map is toring for our answer if this characters first is minus one only then update this character so I'll just say MP of C do first it will be actually nothing but this character I and the same I have to go and do for the last character although you can just do this in one line itself but just for the Simplicity and Clarity I'm just showing you that how we can do it in two lines so we will just go and now again do a second again checking just mentioning that uh how to map our last character like location of that last character now I have got the first and the second now I need to find my answer I'll just simply iterate on my enre map which I have found so far so that will be mp uh p is just a pair now that P pair will firstly store that what is the character now I don't need this what is the character right now because I just want to find the number but let's say if you had a chance and if you wanted to find uh the exact pal rooms which means I'm just asking you okay give me the all the Parrs of basically all these subsequences then this would have been used this C would have been used just to print Okay C the new cor question mark and then the C again now I will just have my start which is actually P do second but P do second was actually a pair now and start was being stored in first so I'll just do a first and same goes for end it will be nothing but again p. second but that was again a pair so again uh do a second on this now I know that I have to find all the number of unique characters in this particular set so I'll just say okay it's St now I'll just go on to all of the characters but I + 1 and less of the characters but I + 1 and less of the characters but I + 1 and less than my n so because you know that I start is nothing but that a character but I want i j okay start and end but I want everything in between from the start and end so I'll just go in the start and end minus one range and I'll just push simply push this in my set an set which is O of one operation so with this I'll just push this s of I in my set and then ultimately I can just add in my answer this size of my set and then ultimately return the answer so with this I can easily get for every character what is okay there's something wrong answer is 0 something we missed uh n minus1 i ++ or set A to Z we map for every ++ or set A to Z we map for every ++ or set A to Z we map for every character then we go on to every character great I did not assign anything here cool uh let's quickly submit and see I just did not assign here so that was it cool bye-bye
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
355
hi guys so let's talk about design twitter so you have to design a simplified version of twitter where user can post tweet follow unfollow another users and is able to see the 10 most recent tweets in the username feed so there are some functions you need to write inside the twitter class so there's a constructor and post to it get news feed and follow unfollow method so you have to read through it and when you read through it and you have to brainstorm what you actually need to do for this question and this is pretty standard op problem you need to create a class inside the tutor class so i already wrote two classes one class is called tweet so twit has its id and time and also the next tweet so what it actually meant is id is going to be twit id time it will be when does it tweet right it has to be unique the tweet has to be unique right and also uh tweet next twit next actually how you link to um this user like how many tweets for this user right and you can actually connect the tweet inside the user class so you can see there's a tweet inside the user class and for the twit constructor you have the id and time you just have to initialize and then set the next the tweet next equal to no and i have a function called get id i just return id and let's talk about another helper class which is class user so class user has set a follower set integer follow and id and tweet head tweak head and these are the variables inside the cluster user so what are i mean what is the follow for the set in set integer so for each user you can follow uh you can follow as many as you want right so this i this integer will store the user id and this user will just follow will store the user id inside the set so which means you can actually know how many um how many users you follow or how many people you follow right and based on this follow because you cannot follow twice right so this has to be unique the user id and also the in id is your user id right so this is also unique how about tweethead so since twit is the uh it is technically a linked list right and you can use the tweet head and you can um you uh you can also use the next inside the tweet so you can actually know which one is your head of the tweet which one is the reason the most recent one in your uh i mean in the tweet for this user so in the user constructor i have in id i'm initial at least id to the id i'm going to initialize the hash set will be the headset it's not going to be trista it's going to speak it's going to be hashtag and today i initially to know and since you cannot follow yourself right i'm going to add yourself into the follow so this will void like if you want to follow a person which is yourself so i'm just technically i'm just i'm going to add a follow uh i'm going to add a user id into the follow and the next function the next method is get to head i just returned return to twitter and get follow i just return follow and for the follower for the follow i can actually just add the id inside the set integer right and for unfollow right uh i said the condition which mean is for this user id cannot be the id you follow i for id you give right this should not be a lot right and if the id is not equal to the user id right you can remove it this is how the follower works and for the post right you want to post a tweet inside this user and i have a tool here right so technically it's a creator to it i give the post time and the time stamp so post id and time step so how do i get the timestamp i have the variable inside the twitter class and twitter class i have timestamp i'm going to be i'm going to set the timestamp you unique so for each tweet it's unique and i have a user map is another variable inside a twitter class i'm not going to talk about this first so uh when i add a tweet right i can increment a timestamp so the next tweet will be unique right the next tweet time will be unique and i'm going to reset the uh the head the tweet head to the new to it so new2.next equal to two head and then so new2.next equal to two head and then so new2.next equal to two head and then two uh to take equal to neutral so this is how you in re initial re initially your two head so they will jump uh let's jump to the twitter class so i have two class one uh two variables sorry two variable timestamp and you in a user map and for the user map key is the user id value is user and i will have i'll have to initially declare that user map is equal to new hash map and timestamp is equal to zero and i'm going to write the first function for the post tweet so what do you actually need to do for the post tree if you are given a user and then to id tweet id right if the user id is not found in the user map you should add right like for example twitter and then you post to it already so there's a user you didn't add into the user map so i'm going to say uh if user map dot contains key user id so i have to make it opposites negative one so i'm going to say if i didn't find a user id inside a user map i need to create a user new user i'm going to give user id for user so user id only take one variable which is id and i need to put into my user map so user map is integer and a user right integer and user so that would be user id user so this is not uh because you need to uh post a tweet and we have a post method inside the user class so you need to get the user get user id that post and what do you actually need to post the post id right which is twitter id and that will be the solution for the post so i'm not going to do this for the next one this is the hardest one i'm going to do the unfollow first so how do you do unfollow if you can find a user inside a user map you can unfollow if you cannot find a user inside a user mac you don't need to worry about it right so this is the trick so if user map that contains key follow id if you can find it inside the user map you can unfollow so how do you upload how do you unfollow you can actually find the method inside the user class it's called unfollow so let's just work on it user map i get unfollow id dot unfollow which one you want to unfollow this guy right so this will be the solution for unfollow method and for the follow that would be exactly the same but that would be a little bit tricky because what happens if you follow a person which is not inside or you inside the inside your user map you need to add right so if you cannot find the um user inside your user map put the folder id and follow eid right that would be the base case i think i spot it correct right so if i want to follow right which means there are two layer two uh two user inside my uh database for sure but my user map did not update right if i didn't find it now i need to create a user for this follow id then i need to add into my uh user map right so put and then that would be the follow id and the user and also the following id probably id is user it will be exactly the same stuff and user map that put follow id comma user all right so if you want to follow someone right and there's a method called follow inside the user class so i can use this method so here is it user map get follower id the follow eid that will be the solution for the follow method i hope i didn't make the type of mistake but whatever let's just keep going and let's move on the next one get news feed so you have to know you have to retreat the 10 most frequent of the 10 most recent sorry uh inside the inside user feed so what you actually need to do is um you need to create a list of integer right i'm going to call it this i'm going to give it to you linked list okay so if i cannot find this user in my user map i can just return this right user map content key if i didn't find this user you just return empty this okay so what if you can find it right you can find it uh for this user uh this user could follow many users right which is set integer follow and i do have the git follow method right so i'm going to copy and i'm going to paste it right here but this is the method inside the user class right so i need to do that is set integer and i'm going to call user the user you follow right it's equal to user map dot get dot user id where's my model user id dot get follow right all right let me explain again i need to get my user class and then this is my method inside my user class and that would be the user to follow and i need to have a priority queue so why do i have the priority queue is actually going to give you the 10 most reason right so why do i have to use a priority queue because the timestamp times then whenever you post the timestamp increase and i can actually just uh reorder like i can actually reorder the priority queue from biggest to smallest so priority queue and this will be a tweet i'm going to call pq and then priority queue and that would be like this right and i need to initialize initiate my order inside the priority queue right so the size of the priority key will be user.size and also priority key will be user.size and also priority key will be user.size and also the lambda is lambda expression that would be better time minus a that time so why do we have to use time because time is the ash time sorry time that would uh that would be the times timestamp and timestamp for each timestamp you will assign the timestamp for these tweets and for each three when you post it right you need to increment so the biggest one will uh will technically mean the most recent one right and that would be the priority queue method so i need to try verse right so user ins sorry in users so for each user you could have it could have tweets right so i'm gonna get i'm gonna say tweet t equal to do user map dot get and then user there will be a user id right but in the user class we have the method called get to head right so that will i'm gonna copy get tweaked head so i would be i would actually know my head of the tweet so if t equal to no i'm just continue i'm not worried about but if t is not equal to no i'm going to add into my i'm going to enter my priority queue so you don't have to worry about how many tweets inside your inside this user you just add the head of the toy in the priority queue and we will check about um uh the pq that is empty it will talk about the priority queue is prior to empty or not if not empty then we will uh sorry so i have if statement i'm going to talk about it later but i'm going to pop i'm going to say t equal to p q dot po so i'm going to pull the tweet from my priority queue i'm going to add i'm add other tweet that get id why because this integer this introduces this integer right and each tweet is not an integer i need to get id which is my get id method and what happens if you have next to it or this tweethead i adding every tweetpad inside the party queue but you could have the next tweet inside the tweet right then you could have people you could say t if t dot next is not no then p q dot and then just say t next so that will be the solution but i'm not done because i need to say retrieve the 10 most recent to the id right so what if list of sizes is equal to 10 i can just break right if you say the retrieve the 20 then you just say 20. but it could be uh i mean you can actually create a verbal max tweet inside your cost but i don't care because this is one way of doing it then at the end i just returned this for this function and i just run a code and see what happens okay uh i spell it wrong right i spell you wrong okay that will be the solution and i'm going to talk about the timing space complexity so follows for the total time total well the total times time space time and space complexity um it actually depends why because for each method it does handle it differently so i'm going to talk about the total space complexity so the total space complexity will be all of n so it doesn't matter like which one uh which method the all of the function that then this is all open space and for each tweet uh twitter class i'm going to talk about this so for this method pause 3 right the time complexity for this one is over one why because your content there will be all of one right you put all of one right you get out of one right you post again it's all of one right so that would be the uh times complexity for the post3 so next let's move on the next one uh get new to again new feed so the time complexity is think about it should be unlocked right why you because you re initialize the priority queue even though you didn't renew shy it's still enough because you use priority queue they do have to compare and the last one for the follow is one because content put get follow all of one right so this would be exactly the same thing for unfollow content get unfold this is all of one for the entire method so this is different it's unlocked and orders are all the point right and for the total space complexity is all of n and that will be the solution and if you feel is helpful then you can leave a comment you can press a like you can subscribe if you want it and this question is really standard for rop and i will talk about the next one later if i can find a similar question so peace out
Design Twitter
design-twitter
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the `10` most recent tweets in the user's news feed. Implement the `Twitter` class: * `Twitter()` Initializes your twitter object. * `void postTweet(int userId, int tweetId)` Composes a new tweet with ID `tweetId` by the user `userId`. Each call to this function will be made with a unique `tweetId`. * `List getNewsFeed(int userId)` Retrieves the `10` most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be **ordered from most recent to least recent**. * `void follow(int followerId, int followeeId)` The user with ID `followerId` started following the user with ID `followeeId`. * `void unfollow(int followerId, int followeeId)` The user with ID `followerId` started unfollowing the user with ID `followeeId`. **Example 1:** **Input** \[ "Twitter ", "postTweet ", "getNewsFeed ", "follow ", "postTweet ", "getNewsFeed ", "unfollow ", "getNewsFeed "\] \[\[\], \[1, 5\], \[1\], \[1, 2\], \[2, 6\], \[1\], \[1, 2\], \[1\]\] **Output** \[null, null, \[5\], null, null, \[6, 5\], null, \[5\]\] **Explanation** Twitter twitter = new Twitter(); twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5). twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> \[5\]. return \[5\] twitter.follow(1, 2); // User 1 follows user 2. twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6). twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> \[6, 5\]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. twitter.unfollow(1, 2); // User 1 unfollows user 2. twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> \[5\], since user 1 is no longer following user 2. **Constraints:** * `1 <= userId, followerId, followeeId <= 500` * `0 <= tweetId <= 104` * All the tweets have **unique** IDs. * At most `3 * 104` calls will be made to `postTweet`, `getNewsFeed`, `follow`, and `unfollow`.
null
Hash Table,Linked List,Design,Heap (Priority Queue)
Medium
1640
611
hello everyone welcome to quartus camp we are at 15th day of july lead code challenge and the problem we are going to cover in this video is valid triangle number so the input given here is an integer array nums and we have to return the valid triplets of triangles we can form from this set so let's understand this with an example so here's the given example so we have to pick three numbers or triplets from the given integer array to form a triangle so now if you ch check we have a 2 3 4 so each side can be having a unique length or both sides can be equal another size can be different or all three sides can be different so first set is going to be two three and four and the second set is picking the second two from the index one so again that is going to be two three four or picking first two twos and then three these are the three uh triplets that we can pick for the output there can be one more chance of combination that is two comma 2 comma 4 but this cannot be forming a triangle because there is a property says that a plus b is greater than c which is nothing but any two sides of the given triangle or the length of the triangle must be addition of this both the sides must be greater than the third side it can be any side but adding any two sides must be greater than the third side so in this case if you add 2 plus 2 it is 4 which is equal to the third side but is not greater than third side so this cannot be coordinates of a triangle so by using this property we have to approach this problem and get our solution so if you are trying to approach via brute force then we can have three for loops where i j and k form three pointers and we iterate every possible triplets in the given integer array and check whether any two sides some is greater than the other side if that satisfies then we can have a counter so it iterates every time it finds a new triplet and that is going to be our output but this is going to take big o of n cube time complexity so how are we going to approach this in an optimal way so now we are going to approach this problem which is very similar to three sum problem where we have to find the triplets whose sum is equal to some value but here we are going to iterate three triplets and find whether summation of two is greater than the third side so to do that we are going to first sort the given array so let us take this example for this problem i am going to have my pointer ice at the very starting position and my pointer k at the ending position and my pointer j is going to be one pointer before k so what we are going to do is we are going to check whether if i plus j is greater than k so in this case 2 plus 5 is obviously greater than 6 so we could consider this as one triplet but here we are going to have our counter us the difference between j and i that is how many numbers are there between j and i which is one two three four five so we can possibly form five combination of triplets between by keeping uh j as 5 and ks 6 why because we are going to check the condition whether the value of i plus value of j is greater than k so in this case if i is at very least position as the array is already sorted and five it has some fixed position in that case if we can add the value at i and value at j and that is greater than k which means if we iterate i to the next positions whatever i moves towards j it is going to increase the sum and definitely not going to decrease the sum so in that case whenever you add the value at i and j it is gonna be greater than k for sure so you can actually form by keeping two comma five comma six three comma five comma six and four comma five comma six as triplets as you increase i the value is also going to increase to the sum so that is the basic logic we are going to approach once we count all the possible triplets between i and j we are going to increment i if suppose it did not form a greater value then we are going to increment j or decrement j and k accordingly to fix our window size and calculate the possible triplets between the range so this is the overall logic of the problem you are going to get it when we are going to code it and this is going to work in big go of yen square complexity which is better than the brute force approach so yes let's go to the code now so as i said let us declare a variable count which is what we are going to return as our output and i'm first gonna sort my given array so once it is sorted i'm gonna assign my three pointers i j and k so as i said my k is gonna be the highest number so we are going to put our k to the last number in the array so here we are fixing the size must be greater than 2 because we are looking for triplets so there must be two elements before pointer k and my i is gonna start with the very first number and my j is gonna start one pointer before k so i'm gonna iterate till my i is meeting with my j pointer and i am going to check if my value at pointer i and value at pointer j is greater than value at pointer k if that matches then we are going to find our count and once we find the count by fixing j at that point we are going to decrement j if not if this condition is not satisfied which means the value is less than n of k so in that case we have to pull our pointer towards the higher value so since i is at the lower value we are going to move our i next to the higher value so once this loop completes our count will be updated with all possible triplets that forms a triangle so yes this is it let's run and try so yes let's submit so yes the solution is accepted and runs in 32 milliseconds so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
Valid Triangle Number
valid-triangle-number
Given an integer array `nums`, return _the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle_. **Example 1:** **Input:** nums = \[2,2,3,4\] **Output:** 3 **Explanation:** Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 **Example 2:** **Input:** nums = \[4,2,3,4\] **Output:** 4 **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] <= 1000`
null
Array,Two Pointers,Binary Search,Greedy,Sorting
Medium
259
1,465
hello everyone welcome to quartus camp we are at third day of june lead code challenge and the problem we are going to cover in this video is maximum area of a piece of cake after horizontal and vertical cuts so the input given here is the height and width of a piece of cake and the horizontal cuts and vertical cuts integer array which represent where we are cutting the cake horizontally and vertically and we have to return the maximum area of a piece of cake in after the cuts so let's understand this problem with an example so here is a given input and height and width is given as 5 and 4 so let us consider we are having a rectangular cake of height five and width four so we are going to cut the cake at position one two and four horizontally so let's cut them at one two and four same way vertically we are going to cut at positions one and three so we cut one and three so we know area of rectangle is height into width so if we want to calculate area of each of this rectangles then we have to know the individual height and width of each pieces so to find individual height consider this as rows in columns for the first row the height is going to be 1 because the difference between 0 to 1 is going to be 1 and the next row is going to be also 1 because the difference between 2 and 1 is 1 and the next is going to be 2 because the difference between 4 and 2 is going to be 2 and the last one is going to be 1. same way if we calculate the width at each column then it is going to be 1 2 and 1 so now we know the width and height of each row and column so it is very easy for us to calculate the area of each rectangle inside it because we know it is the product of width and height so here the maximum or the highest area is going to be 2 cross 2 and that is going to be our output so how are we going to approach this problem so if we are approaching it in the same way i have explained we have to find the difference between each values in the horizontal cuts and vertical cuts and we have to find the area of each rectangle and fix with the maximum one but that is actually going to take big o of n cross m times where n and m are the differences or the height differences between the horizontal and vertical cuts but how do we approach this in an optimal way is the question here so consider this example again this is a rectangular cake of width 30 and height 20. so if we are making a cut at position 20 vertically then we know our maximum area is gonna be there in the first column that is the difference here is 20 and the difference here is 10 so if the area is has to be largest then in that case the values also should be largest so if we check where our height is going to fall whether in the 20 section or in the 10 second it is definitely going to be in the 20th section because that is the higher value so higher width gives us the higher area same way if we are making a cut at 5 horizontally then the height of the first row is going to be 5 and the height of the second row is going to be 15. so in this case we again know our highest area is going to fall where our highest height is so it is easy for us to find the largest area where our highest height and highest width meet so now the task shortened up to finding the largest width and the largest height among the given horizontal and vertical cuts so once we find the largest or maximum height and width we are going to return the product of it so that is the maximum area we could get so yes this is the overall approach and this is going to work in yen login time complexity because we are going to sort both of the horizontal and vertical cuts array that is going to take log in time and we are going to iterate and find the maximum height and width that is going to take n time so overall it is going to take n block and time complexity and why we are sorting the arrays if suppose the height is going to be 20 and 10 then if we are finding the differences then it is gonna written as minus 10 in order to avoid the negative values we are going to first sort the array and then find the differences between each values so hope you are understanding the solution let's go to the code now as i said we are sorting the arrays horizontal cuts and vertical cuts and i'm declaring two variables m and n that denotes the length of these arrays for easier access so now we are going to find the maximum height and maximum width by considering or right writing the arrays horizontal cuts and vertical cuts but the first index 0 and the highest index h will not be included in horizontal cuts that is if we want to calculate the difference between uh zero to the first height or the first cut also the difference between the highest height given and the last index value which will not be included if we iterate and find the differences between each adjacent values in both the arrays so we have to handle these two conditions first and then move on to calculating the further differences so i'm declaring two variables max height and max width where i'm handling these two conditions while declaring them itself so i'm gonna copy the same for max width as well so now i'm gonna have two for loops and the first one is gonna iterate the values of my horizontal cuts and calculate or update the maximum height with the maximum height after calculating each differences between the adjacent values same way i am copying this for vertical cuts as well and calculating the maximum width so once that is done finally we are going to return the product of max height and the max width but here they have asked us to return in modulo of 10 power 9 plus 7 so i am declaring a modulo value and trying to do a modulo and converting it to a long variable in order to avoid integer overflow so let's run and try so let's submit let me try updating more below value let us submit now yes our solution is accepted and runs in 26 milliseconds so thanks for watching the video hope this video helped you and if you like the video hit like subscribe and let me know in comments thank you
Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
maximum-product-of-splitted-binary-tree
You are given a rectangular cake of size `h x w` and two arrays of integers `horizontalCuts` and `verticalCuts` where: * `horizontalCuts[i]` is the distance from the top of the rectangular cake to the `ith` horizontal cut and similarly, and * `verticalCuts[j]` is the distance from the left of the rectangular cake to the `jth` vertical cut. Return _the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays_ `horizontalCuts` _and_ `verticalCuts`. Since the answer can be a large number, return this **modulo** `109 + 7`. **Example 1:** **Input:** h = 5, w = 4, horizontalCuts = \[1,2,4\], verticalCuts = \[1,3\] **Output:** 4 **Explanation:** The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area. **Example 2:** **Input:** h = 5, w = 4, horizontalCuts = \[3,1\], verticalCuts = \[1\] **Output:** 6 **Explanation:** The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area. **Example 3:** **Input:** h = 5, w = 4, horizontalCuts = \[3\], verticalCuts = \[3\] **Output:** 9 **Constraints:** * `2 <= h, w <= 109` * `1 <= horizontalCuts.length <= min(h - 1, 105)` * `1 <= verticalCuts.length <= min(w - 1, 105)` * `1 <= horizontalCuts[i] < h` * `1 <= verticalCuts[i] < w` * All the elements in `horizontalCuts` are distinct. * All the elements in `verticalCuts` are distinct.
If we know the sum of a subtree, the answer is max( (total_sum - subtree_sum) * subtree_sum) in each node.
Tree,Depth-First Search,Binary Tree
Medium
2175
1,837
e Hello everyone love nation control and we are together again today's last name is art digit indiska A number of en is given to you. Friends, here is the number of en in base ten. By the way, the number K is given as a parameter and it asks you for the sum of the digits of this number in blood base and its representation. that crane asked. If you look at it. Friends, it is given as 34 k6. He asked for 69. Friends, how does it become 69? The number in base 34/10 is shown as 54 in base six. The number in base 34/10 is shown as 54 in base six. The number in base 34/10 is shown as 54 in base six. The reason is 4, friends. Because 650 0 times four, this plus 621 times 5 653 0530 607 0 times one is also 4. Since 36/4 is one is also 4. Since 36/4 is one is also 4. Since 36/4 is in base six of 34, its representation is 54. Here, Friends, they asked us to actually add the sum of the digits in this representation, and when the number is given as ten, coffee is in base ten in Istanbul. Friends, since it is already in base ten, the sum of its digits is returned as one. I wanted to be asked to return to the union of the intestine, it was stated that it would be between two and one hundred on the paper, friends, we have already shown it here in the bead questions, a whiteboard like this, let me move on, we were doing the classical division process on the machine, find out how the number can be written to any base, until when In fact, that number is from zero, that is, division. As long as it was chapter 10, we were actually continuing this process. For example, let 's do the number 34 as it was given to us. Then tell 's do the number 34 as it was given to us. Then tell 's do the number 34 as it was given to us. Then tell me 34/6. Find out what we are doing, friends, me 34/6. Find out what we are doing, friends, me 34/6. Find out what we are doing, friends, we divide 34 directly by six, right? Divide by 6, DB is like this: 5 and 6 30 13 There are Divide by 6, DB is like this: 5 and 6 30 13 There are Divide by 6, DB is like this: 5 and 6 30 13 There are four left on my card, and then 52 is greater than zero. The section that is divided by 6 is 06 times 60. Then, when we subtract it here again, 5 remains. When we reach zero, friends, the original number is actually 0. Starting from the end and the last remaining, but I'm more Dost starting from here, not like this, Selim, starting from here, the last remaining ones, starting from the beginning and actually going towards the beginning. If we calculate the representation of all the remaining ones, it's yours. Actually, we find the equivalent of the base six or the equivalent of any ceiling, there we have the number 54, which is 34, let me write it like that, son. It took me to see that it was shown as 54. We always know that, friends, we go from the end to the beginning. When we write down all the rest, we find the representation of that number on the highway. Secure the heart. Let's go to Google Chrome and actually start looking after it. First, Friends, this is already easy to ask. In fact, as long as it is greater than zero, it will be enough for us to add this birsam variable to itself. In fact, as long as the number of valen is greater than zero, it will be enough to add them to this birsam variable. I put it in the mode according to Kaya so that it gives me the remainder when divided by the number of mu dukas and as I just showed, I want to find 5 and four. In this process, Friends, the en is equal to kadipaşa every time Kaya divides and never throws the number of en, de Vay Porto loses the number of en as I showed. In fact, it enables the transaction to be made through When the number of the en was equal to Zero, I stood there and came back brightly, and then I came back with understanding kinlee here. You idiot, we have worked faster than seventy-seven percent of your salary, faster than seventy-seven percent of your salary, friends, this is the method. Actually, this is the method used in this month. You can find the equivalent of a number in any plate and related to it. In fact, you return the String form or die the representation, however you want, A directly like this. With an easy method, with the simplest method. In fact, we can find the equivalent of any base 10 number in another floor area very easily in this way. Yes, friends, that's all what I will tell you about this later. Goodbye, see you in the next video. Is there any ?
Sum of Digits in Base K
daily-leads-and-partners
Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`. **Example 1:** **Input:** n = 34, k = 6 **Output:** 9 **Explanation:** 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9. **Example 2:** **Input:** n = 10, k = 10 **Output:** 1 **Explanation:** n is already in base 10. 1 + 0 = 1. **Constraints:** * `1 <= n <= 100` * `2 <= k <= 10`
null
Database
Easy
null
302
all right so let's talk about the smallest rectangle enclosing black Crystal so you are giving the metric 2D imagery zero represent a white pixel one represent that pixel so you want to find out the area of the smallest rectangle and here is the idea so you in the example one you return what the area of six because this is two high is three all right so this is the idea right so how do we uh start our algorithm uh we the first solution is going to be prefer search I'm going to talk about your solution the second one is using a functional pointer a functional programming sorry about this and yeah and here we go so breakfast search starting black pistol coordinate right we can Traverse four different direction and if a current self is visit then we have to mark as you know visit something like this right and then if I Traverse the neighbor you know if the neighbor cell is actually equal to one I need to add into the Q and then later on once you find out everything right you'll get you will get two chord in it what are this so you will get a top left and bottom right so top leg is going to be X1 y1 authorized gonna be X2 Y2 so this is Imagine This is X1 this is S2 so if X2 minus X1 right and we will get the height and y1 minus by two is something like this right you all right so we need to find out the correct uh position right so let's start coding so I'm going to create a cube I'm passing the code and it was just going to be x y and then kill that offer by passing X Y into there right and I need I will have the top left starting Works here's come on y right id4 right and important y equal to x y and what else I need a four different direction all right so uh you can use 2D array or use 1D array to Traverse doesn't matter up to you but here's 1D Direction array I will teach you how to Traverse and I'm currently this is my current self so I'm going to just mod x y equal to just something else not one not zero right so I'm gonna just you know Traverse my Q and then I will have a and then I will have like a you know the current position for the Q dot pop right I'm going to say position go to Q double so in I equal to what position zero J equal to position one right all right so once I have it then I can Traverse the direction so uh so again this is the 1D right so I'm going to just I equals 0 and listen uh actually is from zero to four because zero one two three there are four different direction and index you're not including the last one so this is doing by purpose right all right so let's start the story what start with the row equal to the I represent X right plus direction is zero which is going to be high okay and there's zero percent J Plus Direction I plus one so imagine I'm gonna draw I equal to zero right and then your first point will be your X will be what uh zero comma and then I plus y equal to 1 so 0 1. so you have to just set I and J are zero by default right so this is ing default value and then I just made sure my I equal to zero iteration equal to this and I shouldn't use I because I already initial I over here I will change to K alright so when k equal to so this is k equal to zero and then k equal to one this will represent Direction one it's going to be one comma one plus one two one zero right and then you do the zero negative one and then negative one zero since that is right uh just to just do math all right so I make sure update list k and then I forgot the direction should be multiple I mean the plural value so if R and C are all open right if our less than zero or equal to the length I mean the last row and then you access for C Lesson Zero c equal to image star length basically you have to ignore all right and also if your current self Ai and C does not equal to one then this is not the it's all right we only visit a black pistol so I will continue so uh it doesn't matter like how do we find the top left every single black pistol represent you know something right so this is only zero two one and then one two and two one so if you want to find out the top left then you will have to what top layer is only one x one y one right so find out the minimum 4X so this will exponent represent zero right y1 this is going to be minimum for column so this will be what uh 0 2 0 1 so there will be one right well by one equal to one so you would so this position is equal to zero one right all right so bottom right this one you want to find out the maximum value for x so it should be two maximum value for the column should be two and this is two so this is top left bottom right so uh top left and the to able to mess on me and I'm gonna say top left zero comma the r right and then top left A1 equal to the left thumbnail top left Point comma C and then bottom right equal to exactly the same thing and you're able to master Max and this was zero and this will be R right bottom right one method next one comma C and then once we finish the current cell we need to Mark as visit ORS or image or CO2 right one switch finish the entire value also we forgot to add into the key right so it's going to be queue.offer new inch RC queue.offer new inch RC queue.offer new inch RC so the current cell which is going to be the black pistol will add into the Q and then I will keep traversing the four different direction based on the Excel right but for the current black pixel um I'm going to mark it as visit so this is neighbor and the queue to find out the neighbor and yeah pretty much it right so and necessary okay this should be care what I'm doing should be careful or equal to j i plus Direction k based on the for Loop right and yeah so once we have it then we'll find out the width and height so if width is actually equal to what button this is zombie X2 X1 and then our index starting from zero so we increment by one I you know a reason then you do exactly the same thing but there will be X2 minus you know uh sorry Y2 minus y1 and then you want to plus one area your return width times height so I think this is a solution let me run it yep submit all right so this is the idea of prefer search so the timing space for breakfast is well this is space so the worst case for this won't be M times n so the um you know M represent the length of the image and the N represent the length of image at zero so uh here we go yeah so time will be this basically I mean space will be less this is time so time uh worst case one is going to be all of the cell inside the you know inside a queue right so that would be the worst case all right next one functional programming so what we actually need is what we need to what find First one so the first one should be this we need to have allocated the row and column to find the first one so this will be a rule this will be the column and you want to find all zero so find all zero this will be fine or zero this will be fine oh zero so now we know the width and height based on these two right this two idea find the first one for the row is this one find all of 0 for the row is this one so it's going to be three minus what zero represent height and then this is going to be zero one two three minus one for the colon represent base so let's start calling so I will have the chart image to set equal to image then I will have X1 equal to what find anyone right and passing oh sorry I'll pass in the zero the range between 0 to X because you're starting from zero you know and then you given the coordinate for the black cells right recording it and then you want to find out this first one is from the row zero to the coordinate it doesn't matter the coordinate starting from you know the first row but and then you are using the rule zero X to represent 5 or 0 and starting for S Plus 1 to 1. length of the image using all zero all you know rule audio right then we're using the idea to find out the colon find anyone from zero to Y and then this time we need to use column o0 and Y2 there will be 5 oh 0 y plus one and then there will be the land of the first and then you'll be calling all and then you'll be calling all and then you'll be calling all zero all right so again we need to have these two function first so it's going to be in taking two arguments is going to be represent I and J that would be the range so if you see this you probably know this is a binary search for the functional programming and we need to have the rule of zero this is going to be well the functional and then the input is going to be integer and then the output is going to be Boolean and this will be all zero and if you have another one which is going to be the same PSI o0 and then I and J and o0 all right this find this so let me call I mean let me call the I mean identified my row audio and column o0 so we're taking the functional and this is input and then you output is Boolean right and then my name is row of zero so that would be equal to the new functional sorry function and then we need to overwrite the idea right the overrider the default function so it's only probably put in and then Boolean P has to be capital and then we're using apply so we're passing we're actually passing the index into here so I'm going to say index all right so how do we do it so for the rule zero we can just you know convert all of the chart into the string or string to chart and then to match every single one is actually the curvature zero right so this will be returned new string and now I'm going to just paste on my index next dot charts convert to charge that all match P pixel representing equal to zero so this will be function of Boolean for rule audio then you talk about another one zombie function integer we put as integer output is Boolean and this will be colon or zero and new function and then you want to override the apply so you're taking an index so you want to find out all column zero right so it's you have to store the info on the colon you know sorry uh the row 0 to I'm a image.length I'm a image.length I'm a image.length and your column index is right over here right so let's start doing this so it's not before in I equals to zero I underst and if there is a one right if image index does not equal to zero which means equal to one Euro return pause because you want to find out the column of zero right and then this will return so just based on my index I know uh does my current so you're giving a call in this and then you Traverse R1 or two or three for this value to c l a o same you know only all zero if not equal to one you return first right all right so uh here we go so how do we do this find anyone then we will have what uh let me do this return X2 and minus 1 times Y2 minus y1 all right so using the binary uh binary search I'm going to say when I listen J right and then if uh oh zero dot five which is going to be a number which I'm going to say k because if K represents the middle value based on the inj right so all zero dot apply k so if my current rule is all zero right but we need to find out the find anyone like we need to find out one inside this rule right so if all zero apply the K we need to increment our high to take plus one right we need to find one first one right and then J will become k because you want to reason why right and this will be super short for almost the same but the condition is a little bit different so I less than J same idea k equal to I plus J minus i d y by 2 and using all 0 power 5 K pi so we want to find out find o zero right we need to find out all zero so we need to you know get this or get this you know the rule number three right we need to get this one even though our base is starting from zero right we need to get this one right so you end up equal to J equal to K there will be the vice versa if you're doing a find anyone and find all zero right and else are equal to K plus one this is because you want to return all right so you have to you know follow the idea and using the rule of zero as a functional you know pointer you know and then to pass into the function as an argument so this audio represent rule of zero and if you use a column or zero right this audio represents column of zero then we're using the apply audio dot apply if the current rule is all zero you return true if a current uh digital retention right if this one return true let me you didn't find one inside your metric the current Index right we pass based on the index right passing the index so we need to just uh either adjust I or either adjust uh adjust J right hopefully I don't make a mistake oh I do so this will be right over here and every single at the end of the function preparation you need to enter comma charts oh and then you know you have to return true inside the apply submit all right so this one is really difficult and timing space are straightforward so just imagine this find any one we go over here right this is the Wilder condition as a binary search idea so it's going to be log you know uh log this is you know from zero to X right so it's going to be log n right and then every single iteration you Traverse all zero dot apply and you're using row and column right so sometimes you're in our around here right so this is this will be all of uh all of n right the rule all of them this is actually taking the all of colon value coming to the string so they will be all of n so uh these two will you know be one of the time in space complexity oh sorry time compost time complexity so if you notice we don't have the space is this one but we can actually copy this the image we're passing the image variable into our function but we are not doing this we actually allocate one image to the array right so this will be another time complexity so uh again the time in space is over here so uh if you are confused you know leave a comment below subscribe if you want it all right so this will be the solution I'm not you know running the debug because if you if I'm running a debug like the metric are going to be hard to see visualize you know so if you still have questions leave a comment below subscribe if you want it see you next time bye
Smallest Rectangle Enclosing Black Pixels
smallest-rectangle-enclosing-black-pixels
You are given an `m x n` binary matrix `image` where `0` represents a white pixel and `1` represents a black pixel. The black pixels are connected (i.e., there is only one black region). Pixels are connected horizontally and vertically. Given two integers `x` and `y` that represents the location of one of the black pixels, return _the area of the smallest (axis-aligned) rectangle that encloses all black pixels_. You must write an algorithm with less than `O(mn)` runtime complexity **Example 1:** **Input:** image = \[\[ "0 ", "0 ", "1 ", "0 "\],\[ "0 ", "1 ", "1 ", "0 "\],\[ "0 ", "1 ", "0 ", "0 "\]\], x = 0, y = 2 **Output:** 6 **Example 2:** **Input:** image = \[\[ "1 "\]\], x = 0, y = 0 **Output:** 1 **Constraints:** * `m == image.length` * `n == image[i].length` * `1 <= m, n <= 100` * `image[i][j]` is either `'0'` or `'1'`. * `0 <= x < m` * `0 <= y < n` * `image[x][y] == '1'.` * The black pixels in the `image` only form **one component**.
null
Array,Binary Search,Depth-First Search,Breadth-First Search,Matrix
Hard
null
16
um hello so today we are going to do this problem three sum closest which is part of political daily challenge so the problem says uh we get an array of numbers of Link n and we get a Target and we want to find the three integers um such that their sum is the closest as possible to Target and what we want to return is the sum of these three integers the sum that is closest to this value Target um and you can assume that we can have only one solution we have exactly one solution so let's take a look at this example with Target equal to one the closest one to this value is the sum two of two numbers which is this here so minus one plus two that's one plus one is equal to two so that's the closest one if you try let's say two um two one minus four that would be minus one so um same difference right two difference um and no matter how you do it right this is the closest if we take a look at this example here um the sum that is closed there is only one possible sum of three numbers which is all three zeros so we return We written that sum right um so that's the idea um now let's see how we can solve it okay so let's see how we can solve this solve it here um so this is what we can do is the first thing to notice is that um there is no constraint on like the three numbers having to be contiguous right we can choose any two numbers so for example in this case we can choose this one and this one um or we can decide to choose this 2 minus four and maybe minus one right so the numbers don't have to be contiguous so with that um maybe we can sort and then use that in our advantage so we can sort the number and see how we can take advantage of that so if we start then the solution actually becomes easier because we can just use two pointer technique and depending on the how close that sum is to the Target we can decide whether to advance the left side or the right side let's see how that pans out um so let's say for example this array here if we sort it what do we get -1 sorry actually minus four minus one -1 sorry actually minus four minus one -1 sorry actually minus four minus one two okay so what we can do first we just take the first smallest um numbers so and assign our best value to that so that would be minus four minus one that's minus five plus one that's minus four right um and what do we want to keep we want to start um I from some Index right the I is the first number of the three but I needs to go only up until n minus 2 right so up until here right because you can't go past this to have three numbers if you go here you can't have three numbers anymore right but actually I'm realizing this is too small of an array so let's pick a larger one uh maybe and I'll say something like -4 something like -4 something like -4 um minus one after it's sorted two three seven nine something like this and let's say maybe K is equal to um something reasonable so the closed one to five would be or maybe let's say nine right so the closed one to nine would be minus one plus one that's zero let's make this one five here so that solution is valid okay and let's say this one here is five okay um so once we sort so the best is equal to minus four right so our I initially is here um we can do two pointers technique because we can place the left side at I plus 1 place the right side at the end of the array and just do the sum so the sum here would be minus four minus one plus nine so this would be minus five plus nine which is four okay and so we compare that we get the difference between that and the target so um what's 4 minus Target which is 5 that's minus one so what can this tells us about moving which pointers to move so if diff is equal to zero well that's the best answer we have so we can just return because that means it's equal the sum is actually equal to Target and we can't do better so if it's equal then we can just return the sum let's call it s but if it's if the sum is smaller than zero what should we do in that case so if the sum is smaller than zero that means s is so s minus Target the difference sorry is smaller than zero that means s is smaller than Target that means if we want to get a number that is closer to Target we need to increase s right so that it gets closer to Target so that means we need to advance our left pointer so here we advance our left pointer if it's in this case diff is bigger than zero what does that tell us so that tells us that s minus Target is bigger than zero okay which tells us that s is bigger than Target so to have a chance to have a better number or closer number we need to reduce s so that it gets closer to Target how do we reduce s we get a number smaller than the right one to do that we go right and so we decrement our error value here to be able to do that so you can see this makes it quite easier but in each step because we have taken the absolute value we actually don't know if we decrease that would be the best solution so each time we need to keep track of the best so far so we say the best should be equal to S if the absolute difference between the best minus Target is bigger right then the best using this s then the difference using this as value okay but otherwise if it's not bigger if it's smaller then means best is still the best answer so we instead we just keep best here right um so that's pretty much the idea we saw the array first we get the three first numbers um and then we use two pointers technique and depending on the difference between s and Target the sum of the current three numbers in Target we decide whether to move the left or right pointer because with these it tells us that what should we do with us should we increase it or decrease it and depending on that we move L or R pointers and we can we should do this while of course while left is smaller than R because once the immediate let's say maybe they meet here we are done there are no more numbers to look at we already explored our numbers so we should stop and just return the best we have so far yeah so that's pretty much it now in terms of time complexity for this solution um we'll be doing going through every eye right we'll be moving I for every time right so once we are done with LR we want to keep moving because when we get an answer for I here that's the answer for I fix it at this position but maybe the answer like in this case is when I is fixed at this position because minus one plus five so we need to do a loop for I so that because we fixed the first number and then we do this two pointer technique to find the two remaining numbers so what this tells us is we have a first Loop for I which is oven and then we have another loop for the two pointer which is also at most oven so overall this is uh solution is oven Square time now in terms of space we are not really using any extra space we are using two pointers and then a loop so it's oven space um so that's kind of the outline of the solution now let's implement it and see if it passes out test cases foreign we just saw in the overview so first we said that we want to sort then we want to keep the best numbers to be the sum of the first three numbers right and then we want to fix I each time but it has to be at least be up to n minus 2 because otherwise there are no more three numbers to look at right one optimization I'm going to do here is if there are duplicate numbers we want to skip them right so if this is equal to I minus 1 right then we want to skip um yeah this is just a small optimization but the core of the thing is we want the left and the right side to be I plus 1 and right side to be the length of -1 -1 -1 so this is just skipping duplicate numbers um and here so we do um we go we fix the left and the right side to I plus one and N minus one right and then we start moving them while they are different so while the L is smaller than r what do we want to say the current sum right is equal to the sum of the three numbers so we fix it I and then we have the two other numbers are L and r and the difference is going to be S minus Target right so if this is equal to zero that means we should be able to just return s because they are equal but if diff is smaller than zero um so that means basically s minus Target is smaller than zero which means s is smaller than Target which means we will do Best by increasing s and to increase s the only way we do that is by increasing l so that we explore bigger numbers right we add a bigger number here if we decrease R we will add a smaller number so that won't be beneficial so we increase l but if diff is bigger than zero which means s is bigger than Target so in this case what we want is to decrease L to decrease s sorry and to decrease L we need to add a smaller number for R here so we need to decrease r and here we can just do else instead and this would be basically very difficult to zero so we have our answer and for each solution we want to update our best value which is um is going to be S if this is better actually than the previous f as the previous best we have so if this is bigger than the absolute value for S minus Target which is just diff so if this is bigger that means this is a better solution because it's closer that means s is closer otherwise we just return best okay and then at the end here we want to return is the best we have so far right um and note here we fix every eye and then we move L and R um so I'll just want this um some value syntax here because we don't need this semicolon uh okay I'll submit one thing to note is that lead code has been having some problems with Python 3 recently so some solutions are used to bet to pass no longer pass um so hopefully this one will pass um okay yeah this is a reasonable solution because if you take a look at the constraint here this is of 10 to the power of 3 so oven squared is going to be 10 to the power of 6 so it should pass and you can see here in the second run it passes so this yeah list code has been having troubles with this lately but um yeah this is um this is a good solution here um yeah so that's pretty much it for today's problem uh please like And subscribe and see you on the next one bye
3Sum Closest
3sum-closest
Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`. Return _the sum of the three integers_. You may assume that each input would have exactly one solution. **Example 1:** **Input:** nums = \[-1,2,1,-4\], target = 1 **Output:** 2 **Explanation:** The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). **Example 2:** **Input:** nums = \[0,0,0\], target = 1 **Output:** 0 **Explanation:** The sum that is closest to the target is 0. (0 + 0 + 0 = 0). **Constraints:** * `3 <= nums.length <= 500` * `-1000 <= nums[i] <= 1000` * `-104 <= target <= 104`
null
Array,Two Pointers,Sorting
Medium
15,259
837
hi everyone in today Channel we have this problem new 21 game and the problem number is 837 all right guys so first of all what we are gonna do we are going to clearly understand what this is going to say after that we're going to move to the logic part we're gonna see how we can solve this problem what is the logic and after that we are going to move to the implementation part we are going to implement our logic in C plus Java and Python programming language fine guys now let's see what this pronouncing right so problems is allies plays the following game Loosely based on the card game 21 all right so there is a guy with the name of allies and Alice plays a game which is a based on card game 21 right fine now allies starts with a zero point okay Enter the number while she has less than K points so allies start with the number zero points remember this point and she will draw until unless she has less than key point so it's okay so there is a condition between uh drawing and K well let's there is some condition right during each draw she gained an integer number of Point randomly from the range one to Max point where Max point is in integer so whenever let's say she draw a number 10 right if Max point is 50 right so if even if drive one or two any number so she will gonna gain a number between 1 to 50 it may get 20 25 anything number but every draw she gonna get a number between 1 to 50 all right and that is going to be also randomly right and you can see here they have written each draw is independent and the outcome have equal because of probability so it's not like that if uh she gonna drag to Adam then he gonna get a number let's say 15 or 16. no even she draw 12 or 15 or 16 the probability is going to be same it does not depend on this particular draw so it's uh something related to mathematics we can call uh concept like probability statistic right so this two concepts are based uh we can say this problem is based on these two concept as well so you must have a little understanding what is probability what is the statistic not statistic but yeah probability should be known to you right all right so now we can say allies stops drawing numbers when she get K or more point now this is important Point guys as you know that it started uh drawing a number from zero now when she will stop when we get she get number less than we can say number K or more than K right one two three four but when she's gonna draw four if you gave us um let's say five so if she gonna draw five number uh then she's gonna stop because we have a condition then whenever she gonna draw a number K or more than this point if uh gonna draw six or gonna draw seven then we can say she has to stop it right so she will stop the game now return the probability that lies had n or fewer points okay and answer within the 10 list of minus 5 of the actual answer are considered accepted now what we have to return guys see uh we are having this range right one two Max Point all this scheme is going to be used on this Max point right all right so what we're going to see we're gonna say that guys uh we have this range right now there are some point we are given the some n right there you can see now in uh we can say input also we are given n so we have to find the probability of these numbers written the probability that allies has n or fewer points so what we can uh say that if we understood this particular problem with the sample one then you will see we are getting hit the probability is one that means upper fat right he always gonna get these numbers so how this we are going to get this one probability see guys the probability one is nothing but we can see we have n ten right so means we have to find the probability of 10 of fuel points right so we can say 0 1 2 3 4 5 6 7 8 9 and 10 right now the key is one and initially she is going to start from 0 right you can see L I start with zero point right and so probability of zero point she start with the German super abilities only we can see one to get a zero point it is one light so because she want to start with zero right have it makes sense she's gonna start with the zero right and after that uh we can say uh she will go less than K right that means she has a less than keyboard so is she gonna go with the less than K I hope it makes sense so less than K first of all let me write the probability of zero which is nothing but we can see one right now guys less than K means less than one right so we have don't have anything right we next time we are gonna get one and which is breaking this condition she has less than K parents that means she gonna stop it here I hope it makes sense right and draw the number where she has less than K point I hope you are getting right so she gonna get uh we can say the total we can say the actual probability is going to be nothing but one will be right and we can make one condition here if you notice that K is nothing but this right so we can make a one condition K is nothing but this one and this is one ten right so we can see one base condition is going to be nothing but if K is equal to zero if this is at zero then we can directly return one as well right now if it is one here if you assume so we are going to calculate the zero this is one now we are going to calculate the one probability which is nothing but based on this only this right and we can see it is also going to be nothing but 0.1 how it is 0.1 you can nothing but 0.1 how it is 0.1 you can nothing but 0.1 how it is 0.1 you can see the total probability was one and we have total numbers right total we can say uh points is 10 right so 1 divided by 10 is nothing but 0.1 so from 0 to by 10 is nothing but 0.1 so from 0 to by 10 is nothing but 0.1 so from 0 to getting a points one is nothing but the probability is nothing but one zero point one right let's break into the simple part if history you are not getting and believe me guys I know you may face some difficulty in this part but until unless this loads partner over keep try to understand right so after that we are going to the implementation bar and implementation part you will have a better idea right but the logic part is just to make you clear that what we are going to do actually in the code part right we can't have this particular point in our head so for getting a second one is based on zero only and for 0 again we have one probability and one divided by 10 Again 0.1 so this will keep going 10 Again 0.1 so this will keep going 10 Again 0.1 so this will keep going zero point one and so on up to 0.1 one zero point one and so on up to 0.1 one zero point one and so on up to 0.1 till 10. now if you will add all this probability then you're gonna get 0.1 is coming ten then you're gonna get 0.1 is coming ten then you're gonna get 0.1 is coming ten times so we are going to add this into ten times which are we can say total probability that's one right because 0.1 into 10 is nothing but 1 only so we 0.1 into 10 is nothing but 1 only so we 0.1 into 10 is nothing but 1 only so we are going to return one I hope it makes sense right still if you're not getting let's understand second example so second example we have n6 right so let me draw the sixth line uh six points one two three four five and six and what we can say we can see the probability of zero is nothing but one we have start we are starting from zero now what we have to do we can say case one right again we can't move to uh this one as well right case one that means we have to stop you for this if we are getting K or anything right so we will first time we will draw let's see what we are getting nothing but one assuming right it's probability thing so we need to assume it if we are getting a one we have to stop it first of all that's make sense right so we are getting one but the Pro actually probability of getting one is based on what based on is this zero only right so 0 has a probability one so if even you can say p of 0 into the total we are having nothing but one by ten right because the node one by six I hope it makes sense here also right so one by ten right so this is going to be the actual probability for one so P of 0 is nothing but one and one into one by ten is nothing but one by 10 which is nothing but 0.1 right now for two the but 0.1 right now for two the but 0.1 right now for two the probability is going to be based on zero only why it's not based on one because you can see we are going to stop at the one we are not moving at if we are at one we are not gonna draw any coin we are going to stop it so you can see she gonna draw until and unless she has less than K point so for two P of uh for two R so it we can come to two from zero only right we can't come from one if that makes sense I hope right so once we are gonna say we are going to say again the same P of zero to convert n it's going to be 0.1 0.1 0.1 convert n it's going to be 0.1 0.1 0.1 convert n it's going to be 0.1 0.1 0.1 0.1 and 0.1 right and even if we have 0.1 and 0.1 right and even if we have 0.1 and 0.1 right and even if we have done this we are going to add all these things which is nothing but probability of getting a number uh and a few points which is nothing but we can say uh what we can see here 0.10.16 0.1 into six and that is nothing 0.10.16 0.1 into six and that is nothing 0.10.16 0.1 into six and that is nothing but 0.6 and you can see in the output as but 0.6 and you can see in the output as but 0.6 and you can see in the output as well we have 0.6 triple zero right and well we have 0.6 triple zero right and well we have 0.6 triple zero right and there will be some condition also comes so let's move to the logic part I hope you understood the problem now right or we are getting output so that is nothing but this is fine right if K is 0 when simply return one right if K 0 we can simply return one right now one more condition is there that is nothing but if k plus Max point is or less than n means if n is greater than or equal to K plus Max y then also we have to return one and why is it so uh that thing you will understood in the code part as well but in here as well so let's take an example of this one so you will understood how we can say so here every time we were getting K 1 right if we have K is nothing but 3 now so how is this going to look like so let's move to this 0 1 Let's draw first of all n is 3 not any six right so we can say 0 1 2 3 5 0 so now this is our Point set and the probability of 0 is nothing but we can say zero point node zero point it is actually one now for one the probability is nothing but what we can see it is based on 0 we can come to one from zero right so for one we can say probability is going to be nothing pure into total Max point which is nothing what we can say 10. right so the probability one is zero is nothing but one so we can say one divided by one ten is nothing but 0.1 right 0.1 right 0.1 right so we can come to 2 from 1 as well if we have one coin then we have we draw because we can draw out the one coin right so K is uh still a three right it is not we can say one is smaller than K right so we can draw a coin as well right it will not she will not stop right so we can say probability of two is based on 0 plus page two one does that make sense we have one divided by 1 by 10 so 0 is nothing but uh 1 divided by 10 is 0.1 and P of 1 is 0.1 0.1 by 10 is 0.1 and P of 1 is 0.1 0.1 by 10 is 0.1 and P of 1 is 0.1 0.1 divided by 10 is nothing but zero point a zero one right I hope it makes sense right so now the probability is going to look like how you can see Zero Point we are going to add it right so if we're going to add it so it's going to look like 0.11 like 0.11 like 0.11 if that makes sense I hope it's making a sense right so if I have done a calculation here just uh you can uh check it yourself but yeah logic will be gonna same right it depends on these two right for two hours so for reaching a three also we can say depend on there does that make sense right guys if you're getting a sense then uh let me know if you uh for three also we can come to two we can come to one we can come to zero because we're gonna add this probability and we are going to add here but for four you can see for 4 we can't come from zero no for four we can't come from this right we can come from zero one two then we can't come from three right I hope this makes sense because three uh where if we are at three so we are going to stop it we are not going to write but we can say we are gonna come from these three coins from zero we can come to four we can one we can come to from two we can come to four but from three we can't come because if we added three we can stop it right so we're gonna add this possibility again here so we are going to add this possibility again here so these three value will gonna be remain same I have same I hope you're getting it and just be happy to return the possibility of these only right uh so this was the music I hope guys you are getting it and for that we can use a DP as well uh for why because we want to store all these data right so just not we can see the depth to DP but yeah for storing this value we can use a one array which is called a DP right so this was the logic guys I hope you understood this and one condition which I want to point out was that if we haven't explained nothing but four right if am expect nothing at 4 and here if you will see 3 minus 4 if we do three uh we can say three plus four right it is still uh we can say it is a greater node greater right and a six here so if let's say uh if I say what point can I give to point out that particular condition for you okay uh let's say here uh Note 3 here it will be two then K will never become right so let's say a k is one and a Max point is four right so now if you will notice that n is this condition is satisfied n is greater than or equal to K plus map right so n is greater than or equal to that means five right so it should be uh we can say 6 is greater than or equal to 5 right so what I want to say here that if you are reaching at this four right so if you are at this fourth index now here now uh you will see that we can get only the point between uh zero not zero one two three four right we can get only these points right so when you are at this fourth so you will gonna reduce this I would say uh you will gonna reduce uh we can see the uh probability of this particular zero index you are going to calculate only for this one and two right because we are having a limit of one two three four even if you are not getting this particular Point don't worry we are going to see this in code part but uh till this you must have understanding why we are getting the same uh probability and why we are stopping from uh we can say three and what is the how we are calculating the probability of one and two right so if uh now if you are clear with this one so let's move to the implementation part and see how we can implement this one uh so I am at here Java so let's take a first of all pythonite so let it be done right so now first of all what we are going to do we are going to say uh if K is 0 right if K is 0 or we can say uh if K 0 like let me write help it is a python light so we can use more keyword if K 0 or uh we can say n is greater than or equal to K plus Max points so we can see written directly 1.0 and Y 1.0 because written directly 1.0 and Y 1.0 because written directly 1.0 and Y 1.0 because we have to return a float value and we have to write here India right fine but if it is not the case now our logic comes right so what are we going to do we are going to first of all uh create DP okay DPR is going to be nothing but having initial value 0 so we're going to multiply with n plus 1 and if you have 0 means getting a 0 program get the zero point the probability of getting a zero point is going to be nothing but always one way because we are going to start from there only right after that what we can do we can say uh use a loop or I in range of n plus 1 and we have to start from one right because we have already zero point right now what we can say DP of 0. first of all let me create our total sum right here 1.0 why uh what is this total sum so if 1.0 why uh what is this total sum so if 1.0 why uh what is this total sum so if you will see here so initially we have having a 1.0 right here right now I having a 1.0 right here right now I having a 1.0 right here right now I don't want to go again and again to get a more time complexity so I will just keep this particular variable as for my total sum right so for my DP of this I is going to be nothing but V what we can say deeper Y is Max point is nothing but 10 right here if your U is consider the first example so total sum 1 divided by ten zero point one four we can say first point right and same goes for second as well so here we are going to check it if I is less than K that means our condition satisfied right so we can say uh what we can do we can say uh total sum is going to add the last recessive probability rate so DP of I is gonna add into total sum but if it is not the case then what we can say our result now we have to consider all those probability right so we can see result is going to be plus equal to TPU Phi now this line you will understood uh just give me a second result is equal to nothing but initially 0. so this is nothing but v z plus equal dpfi is nothing but this one we want to add all this possibility right three four five six which we have to return there so if this condition not satisfied then we are at this condition we are going to add this value in the next addition we are going to add this value then this value right come out this uh if else now we are going to have one more condition that is the main condition which I was uh wanted to point out that in the logic part as well so that your condition is if I not I if we can say uh I minus uh Max point right I minus Max point is greater than or equal to 0 right now we have to leave the we can say probability of the earlier point we can't reach from there to this particular point and for that what we can see we can say uh DP or TS minus equal to DP of I minus Max y right so this is done now once this is another result and we have to run this code and see whether it's working fine or not so let's see it's taking a time because uh we can say here invalid a syntax okay we haven't used a colon here so let's run this code now okay now it's taking still more time right you can see all the three cases are passed so let's try to submit this group and you can see guys it got submitted right I think my internet is working slow that's why I'm taking a time right so fine now let's move to the next programming language that is nothing but uh we can say Java and here first of all quickly we are going to say if K is equal to zero or we can say n is greater than or equal to K plus node K we can say yeah K also but we can say Max point plus k then you can simply return 1.0 right once this is can simply return 1.0 right once this is can simply return 1.0 right once this is done we are going to make a DP so we can make a double array double and the name of TP and here uh we can also do like this as well so both them same thing so new double and here we can see n plus one line and double uh DP of 0 is going to receive 1.0 to receive 1.0 to receive 1.0 and after that we can say make a two variable double result is zero and double and one more thing which is uh we can set order sum is zero right not zero dot assemble USB 1.0 right we know the dot assemble USB 1.0 right we know the dot assemble USB 1.0 right we know the probability of the zero point right we are having in our hand that so we can see now start from uh one from beta is equal to one I less than t uh n plus one or you can say I less than equal to n and I plus and here we can see DP of I what are some divided by Max point and uh if I is less than k then we can say simply total simple is equal to dot SM plus equal to DP of I right and if it is not the case then we have to add in our result wizard plus equal to DPO I right now this is done now we are going to check the one more condition which is nothing but I minus if I minus uh let me hit like this if I minus Max point is greater than equal to zero that means we have to leave the previous we can say probability which is going to be nothing but we can see PS minus equal to DPO uh I minus Max point once this is done we are going to return number simple is that let's try to run this code and see whether it's working fine or not and you can see all the desk is power selected to submit this code and I hope it will also get submitted right so let's see yeah you can see it also got submitted so let's move to the now our next program language that is nothing but we can see C plus so let me let us see let's fine now guys you're taking I don't know why it is much time so but we have selected our C plus language so yeah here it is code right so now what we are going to do we're going to say if uh if K is equal to 0 right if K is equal or we can see if n is greater than or equal to uh K plus Max points so we can say simply return 1.0 we can say simply return 1.0 we can say simply return 1.0 and if it is not the case then first of all make a DP array so we can say Vector node in we can say double of DP the size will be n plus 1 and the default value will be 0 and here we can say TP of one and one because it's 0 is nothing but equal to 1.0 and we can Define two equal to 1.0 and we can Define two equal to 1.0 and we can Define two variable more that is nothing but number of reason we are going to move to 1 till the end all the points right and we are going to get the probability of all the points now we can see if I is equal to no we can say first of all we have to calculate the probability of that particular point so that will be nothing but DP of I is going to be total sum divided by Max point right and after that we can check if I is less than k then we have to add this total supplies equal to DP of I and we have already seen why we are adding the logic part right else we can say uh adding the result right because now we need this uh to return right so DP of I we have to add another result once this is done we are going to check one more condition if I minus Max point is greater than equal to 0. so what we can do we can say uh remove this probability from our total sum and because we don't want to consider this now we can't reach to this particular point from that particular point so from t s minus equal to DP of uh we can say I node I minus Max by now once this is done we are going to say return our result let's try to run this code and see whether it's working fine or not and I hope it all right so let's see this and you can see all the desk is part selected to submit this code as well and if it gets submitted then definitely we have solved with all the programming language right so you can see guys it also got submitted right so now we have successfully solved this C plus Java in Python and we have understood the logic part if still you have any kind of doubt if I miss something then don't forget to write in the comment section right and if you learn something in this video if you learn something new in this video don't forget to hit the like button and subscribe my channel meet you in the next video
New 21 Game
most-common-word
Alice plays the following game, loosely based on the card game **"21 "**. Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outcomes have equal probabilities. Alice stops drawing numbers when she gets `k` **or more points**. Return the probability that Alice has `n` or fewer points. Answers within `10-5` of the actual answer are considered accepted. **Example 1:** **Input:** n = 10, k = 1, maxPts = 10 **Output:** 1.00000 **Explanation:** Alice gets a single card, then stops. **Example 2:** **Input:** n = 6, k = 1, maxPts = 10 **Output:** 0.60000 **Explanation:** Alice gets a single card, then stops. In 6 out of 10 possibilities, she is at or below 6 points. **Example 3:** **Input:** n = 21, k = 17, maxPts = 10 **Output:** 0.73278 **Constraints:** * `0 <= k <= n <= 104` * `1 <= maxPts <= 104`
null
Hash Table,String,Counting
Easy
null
27
hyponyms so we got a problem in liquid that is remove an element okay so our problem statement is that there will be a list three two to three and we have to take off one of the words that is the target word that is three all the occurrence of these three from this list in the best efficient way so there are certain ways to do it but what if I tell you this can be achieved by predefined functions such as collections or something like that of java itself so this is a class called Harris and it has a function called Stream So if you look at this one so this one has the address dot stream just to pass this particular array and it has a function called filter which will look to each element of the particular array and checks that value with the starting value if this is not matched then only let's save that number into the particular new array and we'll get the new array in the form of result okay now what again you have to do is just copy this particular result in the same array okay we can do like that you pass that we will that you pass that we will that you pass that we will get the particular value but I prefer to show you that you can do this one as the copy command as well to get to know that how we can directly copy those things you will get the expected value like this if you save it and run it you will get all that better results thanks for watching
Remove Element
remove-element
Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return _the number of elements in_ `nums` _which are not equal to_ `val`. Consider the number of elements in `nums` which are not equal to `val` be `k`, to get accepted, you need to do the following things: * Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. The remaining elements of `nums` are not important as well as the size of `nums`. * Return `k`. **Custom Judge:** The judge will test your solution with the following code: int\[\] nums = \[...\]; // Input array int val = ...; // Value to remove int\[\] expectedNums = \[...\]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums\[i\] == expectedNums\[i\]; } If all assertions pass, then your solution will be **accepted**. **Example 1:** **Input:** nums = \[3,2,2,3\], val = 3 **Output:** 2, nums = \[2,2,\_,\_\] **Explanation:** Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). **Example 2:** **Input:** nums = \[0,1,2,2,3,0,4,2\], val = 2 **Output:** 5, nums = \[0,1,4,0,3,\_,\_,\_\] **Explanation:** Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). **Constraints:** * `0 <= nums.length <= 100` * `0 <= nums[i] <= 50` * `0 <= val <= 100`
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
Array,Two Pointers
Easy
26,203,283
1,254
hello guys welcome to deep codes and in today's video we will discuss little question 1254 that says number of close Islands so guys this question is somewhat similar to the question number of islands so if you have uh some understanding of this question then I uh insist you to solve this equation by yourself uh and if you face any difficulty then yeah watch this video will clear all your doubts and will give you a pathway of to solve this type of equations so now let's begin with the question understanding so here you are given a 2d integer array and that is consists of only zeros and ones so here zero means Len and one means bottom and you need to return number of close Island so uh what is an uh close Island so Island uh that is a group of zeros that is closed by water in all direction that is left top right and down so water means one so our group of zeros that is surrounded by a once so that is known as close Island and you need to return number of such close Island okay we will see in this figure for better understanding so guys here as you can see this one RR word this one are nothing but there this is what everything here is water okay all ones means water in zeros mean line so this all is water so guys this portion okay this portion this of zero this complete thing is what is just an island okay this is nothing but an island so let me market this all thing this is nothing but Island okay because it is surrounded by water it is uh one now another thing this is also Island this is also surrounded by water on all the sides so this is Island see you can't consider this is not an island this is also not an Island an island has to be surrounded on four side it is top left bottom and right on four Direction via bottom here this is nothing there is nothing so this cannot be counted as a island okay this is also not an eyelid got it clearly so any zeros or land you can say at boundary that is not an island or this is not considered to be an island okay clear so that's why we return two as our answer one is this island and another is this one okay now if you look at this example here you can see only this middle one is connect is surrounded by once that is water on four detection so this is the only Island present now guys if you look at this third example see here these zeros this complete set of zeros this means between this whole thing this all thing is nothing but the island because they are surrounded by water and here this thing this is also surrounded by water on foreign and this between species is also Island so there are two islands here okay so guys till now I hope that you got some understanding of what this creation is trying to tell the question is trying to tell simple things that you need to find a group of zeros and that group of zeros has to be connected by once if it is not connected it's surrounded by once and if this condition is satisfied then simply increment a count of number of closed eyelet okay so at the end we need we get the count of number of close islands in the given grid so yeah guys if I take one more example I'll discuss these so guys this is the given grid okay assume that this is the grid and uh I asked you how many different how many count of islands close Islands see close Island present here how many close Islands present here okay so guys see this is one thing so let me use highlighter so this is one thing right this is one close Island okay this is at the zero mean Island and these are surrounded on top uh right bottom left on four Direction these are surrounded by uh water so this is one close Island and guys this is another closed Island okay see diagonally there is a land okay but that is not true we have to consider we have to only considerate four reduction that is top left bottom and right only in four Direction whether the water is present or not for a island to be considered closed one so yeah this is one thing and this is another okay so these are the two close Island present in the given grid this cannot be considered because here there is nothing if nothing then also cannot be considered a close Island okay so the few things has to be kept in mind is if land on Boundary don't consider it okay so uh in order to solve this question where we have to where you have to check that how many closed islands are possible and for that what you have to do you have to say First Traverse the island right you have to do traversal then only we you can tell that yeah this is an island so for that you have to do some type of trouser right either you can do a BFS traversal or DFS traversal right but for means this is basic thing you have to do some type of traversal okay got it so yeah uh let's uh process this question by if you are doing DFS Travers means the logic for the BFS will also remain the same but here in this video we will be talking about DFS travels it is easier to understand okay so what we would do in DFS traversal we will keep one uh visited area so now guys I am talking about approach here I am starting approach part so in this DFS what we will keep when visited 2D array uh this would be of a type Boolean okay and what we will do so in from this main function we would uh check if uh if a grade of I J equals to 0 and not visited of IGN if this is the condition then we will call our DFS function okay got it so yeah for all the land weather possible and if that land is not visited then we will call for DFS function and we will do a DFS okay let me quickly show you the code and do a driver right that will be a better understanding for you guys so guys see here I've initially created the Boolean Vector visited initialize the answer variable then I ran a 2d follow means for Loop inside a follow forward to Traverse this 2D grid see the one thing to note here is I started my for loop from I equal to 1 up till R minus 1 similarly J equal to 1 up till c minus 1 means this is less than C minus 1 so that means I discarded the boundary what I did I discarded boundary okay that means if a land is also present in the boundary then we don't care about it okay we won't start our DFS if there is a boundary we will never check for boundary here then if this is the case that if any Inner Cell is a land that is grid of I is equals to 0 and it is not visited then we will start making DFS con now this DFS would be of a type Boolean because we have to check only one thing right if the if it is a line then if then is the length covered by water on the force I don't know that is only where to check yes or no so yeah we took a Boolean if yes then we were written one and our answer will be incremented by one right if it is closed by water and force I then what we will do we would simply add plus one to our also so yeah that's why we took Boolean DFS fall pass the grid pass the visited an ing now guys let me take this so guys uh whatever code will be do so our code will start initially from this index 0 sorry 1 so this is the first index one comma one and our uh and after starting from this we will check whether this is the land and visit it or not so this is a line and this is not visited initially so guys what we will do is we're going to start visiting we would start visiting we will visit this okay we have visited this got it now we will check in all the detection up down left and right in the up this is what in the up Direction this is nothing but a water so if the up direction if it is a water then what we are doing we are returning one so here for this up will be written one for this left we will return one for this bottom we will a we will see what that is another water present so we will again so this DFS call will continue see it won't end if it is a length then we are Ending by and returning one but if it is a water then what we are do we will simply commits nothing return statement is there we are simply checking that for four reduction so here currently we are at this bottom right here at this point so from this we will check in for reduction so in the up detection it is already water so if it is already visited then also return one correct in the left it is a water return one bottom return one right we return one so for this land from all direction will be written one okay then so that's this um so here so this will return one this will also return and this line will also written one to this node okay because for this everything is uh every direction this has got one so yeah we will return one see at the end we are doing B2 is n that means water at up is true this is true and this is true in all four Direction it is true then only we will return true if any is false then return false okay so at till now we have reached here that we have Travers it's in three Direction up left bottom now for this now we are at here okay for this we will check on the up Direction water so return true water return true and this is its left is already visited so for this land also what we will do if we simply return one so what we have started from this right this line and for this line we have written uh one from all the detection it is true from all the detection so yeah we will return true so I hope you guys understood that we will start from one of the lane we will check in for o4 detection if you found another link then for that line check in full detection and sign the answer recursively right you got the recurs will be solving this as a for each of the length we are getting correct got till here so yeah this so yeah afterwards of this complete land group of Island we will return one because all these are true so we will return true thickness our answer will get incremented by one got this so if you want to do a dry run for say afterwards let's say if you encounter this zero now for this zero what is our condition so for this zero we will check for uh we will check for up we will return what we will return one check for left we will return one for bottom so now but bottom there is also one line so for we will start making a DFS call for this burner right so for this bottom up is already visited left is water right is water sorry bottom is water now right case this right side of thing so this right side of thing is what there is nothing so if you have nothing on the right side then that means you encountered a boundary that is out of the bound so here on the right it is out of bound and if you encounter these so if you encounter this that means there is no water boundary correct so if you encounter out of a bound condition that means there is no water boundary and in that case guys we would return zero because this is invalid right this is not valid so that's why we return 0 if it is out of the bound that means this means that there is no water boundary and that is an invalid Island so yeah we return zero and at the end what we are simply doing a bit wise of all this up down left and right and if anywhere we would get false that means true and false if you return false at any resistance overall our answer will be false and we will return zero nothing will be added to your answer so yeah guys this is how this DFS function will work the time complexity for this approach would be big of M into M so total number of rows into total number of columns and similarly space complexity would be M into n because we are using this busy trading okay got it and also one another thing the space complexity the this recursive stack will also add something to our space compensating plus recursive State okay this will be also added towards the our space complex setting so yeah guys this so this is for the time and space complexity part and yeah that's all for this video if you guys have any doubts then do let me in the comment section make sure you like this video And subscribe to our Channel thank you
Number of Closed Islands
deepest-leaves-sum
Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.` Return the number of _closed islands_. **Example 1:** **Input:** grid = \[\[1,1,1,1,1,1,1,0\],\[1,0,0,0,0,1,1,0\],\[1,0,1,0,1,1,1,0\],\[1,0,0,0,0,1,0,1\],\[1,1,1,1,1,1,1,0\]\] **Output:** 2 **Explanation:** Islands in gray are closed because they are completely surrounded by water (group of 1s). **Example 2:** **Input:** grid = \[\[0,0,1,0,0\],\[0,1,0,1,0\],\[0,1,1,1,0\]\] **Output:** 1 **Example 3:** **Input:** grid = \[\[1,1,1,1,1,1,1\], \[1,0,0,0,0,0,1\], \[1,0,1,1,1,0,1\], \[1,0,1,0,1,0,1\], \[1,0,1,1,1,0,1\], \[1,0,0,0,0,0,1\], \[1,1,1,1,1,1,1\]\] **Output:** 2 **Constraints:** * `1 <= grid.length, grid[0].length <= 100` * `0 <= grid[i][j] <=1`
Traverse the tree to find the max depth. Traverse the tree again to compute the sum required.
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
283
welcome back to algojs today's question is leak code 283 move zeros so given an integer array nums move all zeros to the end of it while maintaining the relative order of non-zero elements order of non-zero elements order of non-zero elements note that you must do this in place without making a copy of this array so we have to do that in place so space complexity is going to be one but the idea around this question is very simple so it's just moving the zeros from the nums array wherever they're positioned to the end of the array so brute force approach would be to have multiple loops and compare the two and then just shift back so it's almost like a sort in our room so we're just going to put the zeros to the end but what we could do instead to make it more optimized so time will be o n is to use a two pointer technique so let's say we start the left and right pointer at index zero we move the right pointer along and we find a value where the right pointer does not equal zero if that's the case then we flip these values and then we move both the left and right pointer the right pointer is currently at zero so we move it along again we want to find a position where it's not equal to zero so here we have three we flip the left pointer with the right pointer and we move both left and right pointer is pointing at a value that's not equal to zero so we flip it again then we move left and right pointer and now our right pointer is out of bounds so we have the sorted array with zeros towards the end of it so this is the most optimized approach as you can see with the follow-up it as you can see with the follow-up it as you can see with the follow-up it says could you minimize the total number of operations done so in this algorithm we are just using one operation so obviously time complexity is on the space complexity is one so this is the most optimized it can be so left will be set at zero right will be set at zero while right is less than nums.length if the number at the right pointer does not equal zero and we can flip numbers at the left with thumbs up right increment the left pointer and then increment the right pointer and then we can run this okay and there you have it
Move Zeroes
move-zeroes
Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. **Note** that you must do this in-place without making a copy of the array. **Example 1:** **Input:** nums = \[0,1,0,3,12\] **Output:** \[1,3,12,0,0\] **Example 2:** **Input:** nums = \[0\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Could you minimize the total number of operations done?
In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.
Array,Two Pointers
Easy
27
455
hello everyone so in this video let us talk about an easy problem from lead code the problem name is assigned cookie so let's start the problem statement goes like this that assume you are an awesome parent and you want to give your children some cookies but you should give each children at most one cookie only now you can only give one cookie you can understand that each child i has a great factor of g of i which is the minimum size of the cookie the child will be getting if it like if they get that much of cookie that like that child will be content satisfied and every cookie has a size that is s of j that is also good so you are given two let's say arrays one is for every child what is the agreed factor or let's say how much size of cookie they require and the next is the cookie sizes like different cookies you have to assign these cookies to your children just that after assigning you just your goal is to maximize the number of children that will be given these cookies and that are contented that are satisfied i can do this now when i think of these problems i just think of that i have the cookies i have the children i have to somehow maximize it like i have to maximize the children who are contented who are satisfied so i start assigning the cookie that is of the maximum size so can you tell me what like if i have the maximum size okay i should assign it to which children i should start assigning it to the very like the children who has the maximum grade and i will not assign directly to that child because let's say that the child has a grade of and i want a size of cookie 10 like the size of the cookie should be 10. and the maximum cookie i have is eight now if i assign that cookie to that child also that will not cause any good to that child i hope you get the point why because if i provide that cookie that child will be obviously not satisfied he will only satisfy when the cookies are at least of size 10. so if i provide him a very large cookie of size 8 then also he will not be satisfied but there will be a child let's say there is another child who will be satisfied by a cookie of size 8. so why not give this cookie to a child who will be satisfied by a cookie of size 8 instead of wasting this cookie to a child who will not be satisfied and thus it is some sort of a greedy problem in which i will be going like i will both max like sort out both the arrays and try to take every cookie and just see that can i assign it to the maximum child if i am not trying to assign this i will give it to the second child who has the maximum grade like the second maximum grade third maximum greed if i if any one of them is able to take this cookie i will give to this cookie to that child that cookie is gone because i can go give at least one cookie at most one cookie sorry and then i will take the next greatest cookie and try to assign it to the next child and that is how you can do this let's take one example so the example is one two three and one so i have three children so three children and the grid of them is of the let's say i have like sorted them out you have to sort them out so let's the grid is uh five three two one and the cookies i have is let's say four three one i have only three cookies let's say so uh what's my main strategy is let's say like sort them both the cookies and the grid array i like after sorting them out from let's say in the descending or the maximum at the first and the like this order now what i'll do is i will start from the very first cookie that is this for cookie can i assign it to this child no why because like i cannot assign this to this because this child has a grid factor of five even assigning this cookie of size four will not be satisfied with this cookie so let's not give this child any cookie at all for this instant let us move on to this child can i assign this cookie to this child yes because this child has a greed factor of 3 and if i give him a cookie of size 4 then he will be obviously satisfied so why not give him the maximum size cookie so that i will now move forward so this cookie is assigned to this side now let us move on to the next cookie and this child is completed now can i give this cookie to this child yes i can so i will give this child this cookie and let's say that the last wedding again has a cook like the grade of two now can i give this child this cookie no so both of these child will be on satisfied whatever cookie is left i will give them so both only two child will be satisfied and that's all the logic here i will use only so let's move on to the code part so that it will become more clear to you now so i will sort both the like the size array and the grid array of the childs and the cookies and then this one current variable and the total number of child that will be satisfied these are the sizes of these arrays iterate over all the children one by one and this pointer that is this current variable is pointing towards the maximum cookie okay now what i'll do is i will just check that can i assign the cookie i am on this current index cookie that is the maximum cookie whatever cookie i am on to this particular child okay and i will only assign this cookie to this particular child if the greed factor is smaller than the cookie size because then only this child will be satisfied so it is only better to give this cookie to a child who will be satisfied not the child who will not be satisfied by wasting this cooking so i will be just checking out that weather i have some cookies left so this current is iterating over the cookie area so there will be some cookies only now so let's say that the cookies are only one and the child 100 so i can only give one cookie so i will only iterate over the number of cookies in the array if i have some cookie left so current is less than m okay that is the size as well as the greed of the ih children is less than equal to the size of the cookie i have then only i will give the child that cookie so the total number of contented children will increase by one that is totally incremented by one and because that cookie is now given to that child i will move to the next largest cookie that is current plus also that i have sorted them in the reverse order like decreasing order from the maximum smallest that desire we use are vegan our end and that is how in the end you just have to run it you turn this off so that's a very greedy problem and that's over our logic and the good part for assigning cookies problem from lead code if you're streaming out you can mention in the comment box thank you for watching this video till the end i will see you next until they keep coding and bye
Assign Cookies
assign-cookies
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number. **Example 1:** **Input:** g = \[1,2,3\], s = \[1,1\] **Output:** 1 **Explanation:** You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. **Example 2:** **Input:** g = \[1,2\], s = \[1,2,3\] **Output:** 2 **Explanation:** You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. **Constraints:** * `1 <= g.length <= 3 * 104` * `0 <= s.length <= 3 * 104` * `1 <= g[i], s[j] <= 231 - 1`
null
Array,Greedy,Sorting
Easy
null
1,171
hey everyone today we are going to solve the daily EOD challenge of 12th March 2024 and the problem statement is remove Zer some consecutive notes from Ling list so let us first understand the problem statement so according to the problem statement we have been given a ling list and what we have to do is we have to delete consecutive nodes that has a zero sum now what do I mean by this so let's take an example say for example we have a ling list as 1 2 Min - example we have a ling list as 1 2 Min - example we have a ling list as 1 2 Min - 2 and 4 so cons if we get a part of Ling list that results in Zero Sum then we have to delete it so here in this Ling list you can see that this part of the Ling list that is 2 minus 2 they are giving us a zero sums because 2 + - 2 is giving us a zero sums because 2 + - 2 is giving us a zero sums because 2 + - 2 is what it's zero so what we have to do is we have to delete this part of the Ling list correct so our answer would be 1 14 so we have to return this ring list so what we have to do is we have to first identify the part of lingl that is giving us a zero sum and once we have identified the part which is giving us a zero sum what we have to do we have to delete that part okay now we are having two questions that is how to identify the part of the Ling list that is identify part of Ling list that has a zero sum okay firstly let's see how are we going to identify the part of Ling list that has a zero sum so for that we will be making use of prefix sum let's see how so we took the example as 1 2 minus 2 4 correct so initially our prefix sum is zero uh so let me write here prefix sum so initially it would be zero and we would present at this note one so now what would be our prefix sum it would be 1 + 0 which is what which is it would be 1 + 0 which is what which is it would be 1 + 0 which is what which is one so our prefix sum will get updated to one now our prefix sum would be one + to one now our prefix sum would be one + to one now our prefix sum would be one + 2 so 1 + 2 is what it's three so we will 2 so 1 + 2 is what it's three so we will 2 so 1 + 2 is what it's three so we will get a prefix sum of three now we are present at this node so what would be our prefix sum it would be 3 + min-2 be our prefix sum it would be 3 + min-2 be our prefix sum it would be 3 + min-2 right which would be one and then we'll move to this node and what would be the prefix sum it would be 1 + 4 which would prefix sum it would be 1 + 4 which would prefix sum it would be 1 + 4 which would be five correct so here you can see that this prefix sum one is repeating itself okay so whenever a prefix sum repeat itself it means that all the elements that we are encountering in between this and this prefix sum they has a sum of zero because then only it's possible that a sum is repeating itself if we will have a sum in between them which is not zero then in that case this prefix sum would not have been one right it would have been either greater than one or it would have been either lesser than one okay it wouldn't have been one so whenever prefix some repeat itself it means that the numbers in between them are contributing to a zero sum so let's verify that whether it's true so you can see that where we got this prefix some one we got this from here and this prefix some one we got it over here so you can see that the elements after this one that is this two and this minus two are having a sum of what these two are having a sum of zero so here what we had one and we got a one over here and since these two are having a sum of zero so one plus this zero is giving us a prefix sum of one right so it's clear that here we are getting a part of a ling list that is having a zero sum then only this one is repeating itself correct so how are we going to identify the part of the lingl that has a zero sum we are going to identify this using prefix sum right using prefix sum so how by using the prefix sum so whenever a prefix sum will repeat itself it means that we have got a zero sum right uh let me write it over here whenever a prefix sum let me write it as PS whenever prefix Su repeat itself it means that we have got a part of Ling list that has a zero sum correct so we are done with the first part which is identifying the part of Ling list that has a sum of zero now the second part that we are yet left is how are we going to remove it right so you can see that this part is the one which is having a zero sum so how we can remove it by setting the next of one as four correct now you may notice that how are we going to know that the prefix sum one this prefix sum which is repeating itself where we have found it earlier right we found this one earlier then only we are saying that we are having a zero sum correct so how are we going to know that we have got this prefix sum earlier so for that we have to keep track of this prefix sum so we will be storing this prefix sum additionally we have to know one more thing that for which note that at which point in this ring list we are getting this prefix up so for that what we will be doing is we will be using a hashmap and in that hashmap what we will be storing is we will be storing the prefix sum and corresponding to prefix sum we will be storing the node so say for example if we store the prefix sum as one then this prefix sum one is corresponding to which node it's corresponding to the node one correct and similarly we will store this prefix sum three and corresponding to it we will store the node two and the moment we will get this prefix some one so what we will do we will check that whether this prefix one is already present in our hashmap so we can see that this prefix of one is already present in our hash map so what does it means that in between this whatever the numbers are present they are giving us a sum of zero so we have to delete those notes so how are we going to delete those notes we are going to set the next of this note that is whatever the prefix sum which is repeating itself we will find out its corresponding node which is one and we will set it next to the next of this minus two so what will set we will set the next of this one as the next of minus two which is nothing but four okay so and we will be getting the result as 14 correct so now we have identified the part of linguage that has a sum of zero and we have also removed it okay so we are done with both the steps now before moving to solving this example I want to discuss one more test case which with you so uh let me write it over here if we have 1 minus one so what should be its result should be null right why because you can see that this one plus minus one what is thee what is the sum it sum is zero correct so this entire Ling list is having a sum of zero so it means that we have to delete the entire Ling list and if we will delete the entire L list what would be our result it would be nothing but none so let's see that whether the approach which we discussed over here is going to work on this or not okay so initially we are present at this node and let's say this is our hashmap which is initially empty so what we will do we will store the prefix sum as one and the corresponding node as one correct now we will come over here what would be our prefix sum would be 1 + minus one which is what would be 1 + minus one which is what would be 1 + minus one which is what which is zero so we will check that is this zero present in our hash map so zero is not present in our hash map so what does it means that we have not got any Zero Sum so what we will do will simply store this prefix up and its corresponding node as minus one and we will move forward and you can see that we have completely exhausted the Ling list so according to this approach what would be our result would be this Ling list only but is this correct the answer is no it's not correct so for handling these kind of test cases in which we have to delete the head or in which we have to delete the entire Ling list what we will be doing is we will be using a domino let's say the D node value is zero and what we will do we will set the next of this D node as the Ling list which is given to us and what we will do is in the hashmap initially we will store this dumy node so our dumy node is zero and initially what was our prefix sum it was zero so we will store the prefix sum zero and corresponding to it we will store this Domino okay now again let's do the same dry run so what would be the prefix sum over here it would be 0 + one prefix sum over here it would be 0 + one prefix sum over here it would be 0 + one so what would be it would be one so we will check is this one present in our hash map so this one is not present in our hash map so we will store the prefix some one and corresponding to it we will store the node one now we will move forward so we have got a minus one so what would be the prefix sum would be 1 + minus one which is zero sum would be 1 + minus one which is zero sum would be 1 + minus one which is zero now we will check that is this prefix Su zero present in our hash map so you can see that this prefix sum zero is already present in our hashmap so we so what does it means that we have got consecutive nodes that has a z sum so what we have to do we have to now delete it so how are we going to delete it we are going to set the next of this zero right we are going to set the next of this node that is the next of this zero as what as the next of this minus one so what would be its next would be null correct so what we have got zero and corresponding to it is what it's null so we have got this till now what we will be returning as the answer we will be returning the next of this zero as the answer why because this zero was not initially part of the Ling list right this was not the part of the Ling list we made this dummy node on our own so as to handle these kind of test cases so what we will be returning is we'll be returning the next of this particular D node so what is the next of this dominoe the next of this dumy node is what it's null so what would be our answer it would be null so is it working now so yeah it's working so we have to keep in mind that just after creating the hash map we have to store the prefix sum zero and corresponding to it the dumy note okay so now that it's clear now let's do a quick dry run for the this test case so let us create a hashmap over here and what we will be storing in the hashmap we will be storing the prefix sum and corresponding to it would be the node okay so after that what we have to do we have to create a dummy node let's say this is our dummy node let's say this is dummy and we have to set the next of the Domino as the head of the Ling list okay now let's create a pointer current which would be at the head of the Ling list and initially what our prefix sum would be zero fine now what we have to store in our hash map initially we will be storing the prefix sum zero and coresponding to it we will store the Domin node what is the Domin node it's zero okay so now our current pointer is at one so until our current is not null what we will do we will find out the prefix sum so what will be the prefix sum it would be zero + one which is one sum it would be zero + one which is one sum it would be zero + one which is one so now what we will do we'll check is this one present in our hash map so this prefix of one is not present in the hash M so what we will do we will store this prefix some one and corresponding to it we will store the node so what is the node it's one and now what we will do we will move forward so let me represent this current with C okay so we are here so this is current okay so let me write this as well as C okay so now we are here now what would be the prefix sum would be 1 + 2 which the prefix sum would be 1 + 2 which the prefix sum would be 1 + 2 which is three now we will check is this three present in our hash map so three is not present in our hash map so what we will do we will store this prefix sum that is we will store this three and its corresponding node what is its corresponding node it's two so we will store this two now we will move forward so what would be the prefix sum now it would be 3 + 3 it would be six now we would be 3 + 3 it would be six now we would be 3 + 3 it would be six now we will check is this six present in our hashmap so six is not present in our hashmap so what we will do we will store this prefix some six and its corresponding node so what is its corresponding node is three now again we will move forward so what would be the prefix sum now it would be 6 + minus 3 that is now it would be 6 + minus 3 that is now it would be 6 + minus 3 that is three now we will check is this three present in our hash map so we can see that three is already present in our hash map so what does it means that this particular prefix sum is repeating itself which means that the numbers in between this prefix sum to this prefix F sum has a sum of zero correct then only it's repeating itself so we have identified the part of linguish that has a sum of zero now what we have to do we have to remove it so how we will remove it we will set the next of this two where is this two it's here right we will set the next of this two as the next of the node where we are getting this three so where are we getting this prefix sum three we are getting this prefix sum three at here so we will set the next of this two as the next of current which is this minus two right and let's verify whether we are getting a part that has a zero sum or not so here you can see that what we are having three and minus three and what would be its sum would be zero right so since we have got a part of the Ling list that has a sum of zero so we have to delete it but one more thing we have to notice over here is that before deleting this part what we have to do is we have to also remove the prefix sum which we have found out for these notes that is this one so how we were getting the six by adding the prefix sum which we got till here plus this three right and since we will be deleting this three we also have to delete this entry right so what we will do we will delete this entry so we will delete this entry okay and after deleting this entry what we will do we will set the next of this two as the next of this current so what would what will happen we will set the next of this two to the next of current so what is the next of current it's minus two and we have successfully deleted this part so what would be our resultant Ling list it would be like this okay and now our current will point over here fine so what would be our prefix sum now it would be 3 + - 2 which prefix sum now it would be 3 + - 2 which prefix sum now it would be 3 + - 2 which is one now what we will do we'll check whether this prefix of one is already present in our hashmap or not so is one present in our hash map so we can see that this prefix sum one is already present in our hash map so what does it means that the elements in between them has a sum of zero so what we have to do we have to remove them so let's check whether this true or not so you can see over here that we have a two and here we have a minus two so what would be its sum it sum is zero so we have got consecutive nodes with some zero so now let's remove it so how are we going to remove it we are going to set the next of this one so where is this one it's over here so we are going to set the next of this one as the next of current what is the next of current it's null so we will set the next of this one as the next of current which is null so what would be our result in Ling list it would be like this right so let me write this clearly so it would be like uh this the next of this would be null now again we will move our current so our current will reach null and we will stop so this is what we have got now what we have to return the next of this dumin node so what is the next of the Dum node the next of this Dum node is this that is it's only one so our answer would be one so I hope it's understood to you all so now let's quickly code this let us first create the Dum node Dy node so let's take the value of the Dy node as zero now what we have to do we have to set the next of the Domin node as the head and we have to create a point that we will use to iterate over the given ring list so let's take that pointer as current and it would be initially pointing at a okay now what we have to do we have to create an unordered map and what we will be storing in it is the prefixer and the corresponding node to it right so let's name this as memo and what we will store the prefix sum and node correct so initially our prefix sum would be what initially our prefix sum would be zero and what we have to store in our hashmap initially we have to store this prefix sum of zero and corresponding to it we have to store the dumy not right so as to handle test cases like this if we have a test case like one comma minus one in which we have to delete the entire Ling list so for this we for handling this test case we have to store this one right now what we'll be doing is until our current is not null what we will do we will find out the prefix sum so what would be the prefix sum would be prefix sum plus the current nodes value the current noes value correct after finding out the prefix sum what we have to check is we have to check whether this prefix sum is present in our hatch map or not correct so we will check that if memo of prefix sum correct prefix sum if this prefix sum is already present in our hashmap then we will do something and otherwise we'll do something right so let us first handle this else so if our prefix sum was not present then what we were doing we were simply adding the prefix sum and its corresponding note correct so in the else part what we were doing we were adding the prefix sum we adding the prefix sum and it's corresponding notes what is the corresponding notes it's current correct now let's handle this if case so if a prefix sum is present then what does it means that we have found out the Zero Sum found out a part that has zero sum so what we have to do we have to remove it correct so how are we going to do it so let's say list node start from so let's take this from as memo of prefix sub now what is this from so let's see over here so if we had an English like this so here you can see that whenever this prefix sum was getting repeated so what we were doing we were deleting this part that is we were setting the next of this two as this minus two right so what would be this problem this from would be nothing but this two right this from would be nothing but this two so from this note what we have to do is let's take another node two which would be the next of fromom and let's say that sum is equal to it would be the current prefix sum plus the value of this node right now what are we doing over here is we are deleting this entries we were deleting this entry right we were deleting the prefix sum for the part which we are deleting if we will delete this part so what we have to do we have to also delete the prefix sum which have which we have found out for this part right so now what we are doing we are deleting this so we will say that while this sub is not equals to the prefix sub so until that time until that what we have to do until that we have to erase this sum so we will erase this sum and after erasing this sum we will set the we will set two as the next of two and we will update our sum as sum plus equals to the value of two okay now what we will do now once we have deleted this sum from the hashmark what we have to do we have to delete this part of the Ling list and how we will be deleting this part we will be setting the next of this from to the next of this current right that is we will set the next of from proms next as currents next fine now once we have handled this if case and this else case what we have to do we have to Simply increment our current pointer so current is what current is current next and after doing this what we have to do we have to finally return the next of this Dy note right we have to return the next of the D node now let's quickly run this so it's giving us the correct answer let's submit it so it got accepted talking about the time complexity and space complexity so if we will have a total of n nodes in the Ling list then the time complexity is order of n why so here you can see that what we are doing here we are completely iterating over the entire Ling list right so what does it means that we are processing all the nend nodes so the time complexity here would be order of n correct and the space complexity is order of n as well why because here what we are doing is in the hashmap we are storing the prefix sum responding to all the N nodes right so the space complexity would also be order of n so that's all about today's daily read challenge thank you
Remove Zero Sum Consecutive Nodes from Linked List
shortest-path-in-binary-matrix
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of `ListNode` objects.) **Example 1:** **Input:** head = \[1,2,-3,3,1\] **Output:** \[3,1\] **Note:** The answer \[1,2,1\] would also be accepted. **Example 2:** **Input:** head = \[1,2,3,-3,4\] **Output:** \[1,2,4\] **Example 3:** **Input:** head = \[1,2,3,-3,-2\] **Output:** \[1\] **Constraints:** * The given linked list will contain between `1` and `1000` nodes. * Each node in the linked list has `-1000 <= node.val <= 1000`.
Do a breadth first search to find the shortest path.
Array,Breadth-First Search,Matrix
Medium
null
1,819
hello everyone let's take a look at this legal problem this is a last problem in the weekly context and it's um pretty hard okay let's take a look okay the problem is uh we are given a renounce that consists of positive integers and the juicing of subsequence of number is identified and defined as the greatest integer that divides all the numbers in sequence evenly for example the transitive sequence for 6 16 is 2. okay so we need to return the number of different gcds among our non-empty subsequence of nums let's our non-empty subsequence of nums let's our non-empty subsequence of nums let's take a look at this example in this example the num is 6 10 3 and the answer is 5. let's take a look the 2 city of 6 is 66 statistics of 10 is 10 the ducati of 3 is 3. the two city of 6 10 is 2. two situation of six three is two situation of ten three is one juicity of ten and six ten three is one so there are five different two cities there one two three six ten okay so we need to find how many unique to see these okay so um idea is pretty naive we just test every number from one to maximum number and to say if every number is a nucity of some numbers in the input okay so the framework looks like this first when you and we just uh follow the input once to find the maximum number then we will use a boolean vector to indicate if a num in yet or not okay here we can also use a hash set but the overhead of hash set is uh like much greater than array or vector so if we are using set we will get to so which we better use array of vector here we shall use like some simple data structures okay and we initialize answer to zero finally we just written this answer in this for loop we just follow from one to the maximum number and in this block we just check each eye is a valid electricity of some numbers in my input okay so the coding the block is the most tricky part the simply the most important role here okay let's take a simple example if nums is 12 15 like how can we check uh for example one is three how can we trap if three is sound gcd like electricity of some numbers in my numbers f3 is a trucid of some subsequence then so subsequence must be like multiple of three right so we just check three six nine so we initialize three to three first every time we just increment like three to three okay at first we have three bus three is not in my vector so we ignore it six nine they are not in my input okay next one js is 12 is in my vector okay so we update to say the two cd is uh on the scroll on the skeleton and this is the internal function in compiler okay 012 which is 12 okay now gcd the 12. uh just imagine that we don't have 15 we only have 12. then the 2cd of 12 is 12. so 3 is not just to cd in 6 case but now we have 15 so 1 3 becomes 15 we find vector 15 is also in in my nums so i will update gcd becomes gcd 12 15 which is three okay so muscle goes three uh yeah three is gcd of twelve and fifteen and finally we find this two cd is three and i is three so i is three which is electricity of some numbers in my inputs we just increment answer by one assuming the numbers is 12 18 when is 3 101 2 bit 1 2 becomes 18 to say the and 12 18 is six the two city of 12 and 18 is six which is not three so we want to include three here so 2cd is 6 is 3 so we don't include 3 in this case one tree is three will like our one is six in this case gcd is six we will include six in this case but we will not include three okay that's it see you next time
Number of Different Subsequences GCDs
construct-the-lexicographically-largest-valid-sequence
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array. * For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`. Return _the **number** of **different** GCDs among all **non-empty** subsequences of_ `nums`. **Example 1:** **Input:** nums = \[6,10,3\] **Output:** 5 **Explanation:** The figure shows all the non-empty subsequences and their GCDs. The different GCDs are 6, 10, 3, 2, and 1. **Example 2:** **Input:** nums = \[5,15,40,5,6\] **Output:** 7 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 105`
Heuristic algorithm may work.
Array,Backtracking
Medium
null
452
hi everyone so today I've installed bleed code problem number or daily challenge problem number 452 minimum number of arrows to post balloons so in this problem basically we have been given the x coordinate of uh balloon which is taped to a ball and we have to find out the minimum number of arrows which we need to burst these balloons okay so this is the question and they have given that uh you know arrows can be should up directly vertically from different points and it can go up to No Limits like to infinite Lanes so this is the base the Crux of the whole problem statement and what we have to do is we have to basically figure out any of these coordinates are overlapping with each other or not okay so to do that what I'll be doing is I will be uh sorting this array out from there uh using the end point of each balloon for example if we sort this out what we're gonna get we are going to get 1 6 2 8 7 12 and 10 16. okay now uh it gets easier for me to check if let's say uh the first element was 1 6 and then two weight right now what you have to check is like this will be the uh you know the balloon which I'll drag it first okay now we have to see if the starting uh start point or the static coordinate of the next balloon somehow overlaps or comes under the end point of the previous one right if it does then this balloon can also be short or using a single Arrow right but if not for example in this case it is 7 and 12. right so we cannot uh get this right with a single Arrow so what we'll be doing is we'll be uh we'll be using another arrow to shoot these two volumes so this is the basic Crux of the approach which I'll be using so let's move toward the solution okay first point is to sort the array using the end coordinates okay Lambda 8 and the force index which is the n coordinates right now I want to initialize my result with one okay and I would need a current start and end coordinates right so for the initialization this will be the coordinates of my first element after sorting it out okay so it is very simple now we just have to iterate a loop and points and if current and is less than the start point basically if current uh n like the maximum in which we are at is less than the start point of the next element of the current element sorry then we can say we want to instrument one error okay and we have to update the values of current and current start and current end points as well okay so yes this is it at the end I'll just simply return the number of arrows which we are storing in result okay let's submit for the test cases okay so there was some type of there is fine I think local variable Arrow okay so I just literally you know uh wrote what I spoke so I was using Arrow again so okay so the test series got passed let's Summit for further evaluation awesome so the solution got accepted and we performed decent like we outperformed 57.9 of the solutions 57.9 of the solutions 57.9 of the solutions so thanks again guys for watching the video and stay tuned for the upcoming event thank you
Minimum Number of Arrows to Burst Balloons
minimum-number-of-arrows-to-burst-balloons
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches between `xstart` and `xend`. You do not know the exact y-coordinates of the balloons. Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with `xstart` and `xend` is **burst** by an arrow shot at `x` if `xstart <= x <= xend`. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_. **Example 1:** **Input:** points = \[\[10,16\],\[2,8\],\[1,6\],\[7,12\]\] **Output:** 2 **Explanation:** The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons \[2,8\] and \[1,6\]. - Shoot an arrow at x = 11, bursting the balloons \[10,16\] and \[7,12\]. **Example 2:** **Input:** points = \[\[1,2\],\[3,4\],\[5,6\],\[7,8\]\] **Output:** 4 **Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows. **Example 3:** **Input:** points = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\]\] **Output:** 2 **Explanation:** The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons \[1,2\] and \[2,3\]. - Shoot an arrow at x = 4, bursting the balloons \[3,4\] and \[4,5\]. **Constraints:** * `1 <= points.length <= 105` * `points[i].length == 2` * `-231 <= xstart < xend <= 231 - 1`
null
Array,Greedy,Sorting
Medium
253,435
312
Hello Hi Everyone Welcome To My Channel It's All The Problem And Civil Servants And Values ​​In 1000 In This Value 19 Values ​​In 1000 In This Value 19 Values ​​In 1000 In This Value 19 Printed Vidhi Number On Represented Exams Your Host Year All The Value In This New Wave United States Of You Will Get Na Pintu Were Left Right Left and Right 512 125 subscribe The Channel Please subscribe free 1513 Definition and Other is Refined Maximum Point Collect Live Wisely and Similarly When Will Solve This Problem Solving All Possible Combinations in the Worst Passwords and You Will Defiantly subscribe and subscribe the Channel 34 For Will Try All Possible Combination And Take Maximum Whatever Given Maximum To Has Twelve Will Have To Appear Only Three Values ​​In Next One To Three But Again From Fear When Was Values ​​In Next One To Three But Again From Fear When Was Values ​​In Next One To Three But Again From Fear When Was Drawn In Electronics 12345 123 Likes Subscribe Building This Point To The Best in the world will divide switch on website and one is on the right side with values ​​125 will be held in update values ​​125 will be held in update values ​​125 will be held in update Amazing Divya 1315 se zara subscribe Video give Avoid getting lots of condition will start from subscribe Subscribe now to find the maximum first Between Delhi And Subscribe Will Be Valid For Face One To Will Give To The Self I Will Ajay Output Will Get Some Will Get Coins First Live Well Wishes That And Say The Cost Of Value In Two Verses And Left For This Page Will Be Shravan His Left Hand Into Right 154 Switch Board The Cost West Indies Plus What Will Happen In This Will Have To Go Out From Her Death Benefit To Calculator Maximum In The Left Side And Right Side Of This Gallant Supermax Left Side Exactly This Method Game Same Method Solar System Acid Looks Like To Get Maximum Guide Nine Get Coins From Left To Right Some Will Destroy Them From Abroad Nine To That From Being Developed As Left To High In One's Life From I To That Point That I To Right Till Time Call This Is The Basically state translation and definition of water from bikut live score a great scholar here reduce it over and decide which have tried for all possible way between the range of maximum over all which will be possible for what we do we need to one so lets Se Request To No 2 F 2 Mode Of But You Haven't Really Amazed To Know What Will Ooo Will 10 - 151 Will 10 - 151 Will 10 - 151 First And Will Copy Rest Of The Elements From Individuals 208 I Request To Wave Cancer Se Z2 90 Members We Need To Dead Over ICC World T20 IPL 2019 Start Length I Plus End Updates Is Five Plus One Day Subscribe Button Left And Right India Originally Written In This Will Return 25 White Sesame One Person Another Person End Definition Of The Service Will Return Will Guide You Are Included Toys Will Get The maximum point is ab mexico in from mithila 10 will try all possible how is show all possible how is from life can tell in tizi call to z plus one day they will go cut it xa1 plus listen fauj will get coin hai us supermax soft From flat to these two initials will get and Singh also came they in which will be norms of all star name cleanliness systems of earth in the form of coin Vikram even today Mathur Fas ko plus prohibition match dots the marks of Previous Max Points Of and Score Plus Ghee Add Nine From That Alto I Plus That Point That From Idea This World Were Trying All Possible Combinations And Will Take Maximum Word And Will Return Next Point So Let's Try To Compile Country Developed Solution First NCOS Walking And Nurses Judge Problem Is Pay Are Changed Into This Mistake He Tried To Pass This Are Not Equal To And Listen Exclusive Compiled A&amp;M Compiling MB Marketing Answers But A&amp;M Compiling MB Marketing Answers But Say Hello How Is The Country Will Looks Like Soane Finnish Lab Started From The Are 6 Live Video 3158 to activists from first absolutely I will solve and subscribe 2025 work from here absolutely zero two one a plus money 125 service dhawan way three layer channel subscribe to and plus 2 5 is so let's go and drop inches let's go for mode app independence two Branches Which Can Be Drawn From One To Two Subscribe Calculated And What Will Be The Solution Problem Test Ride Point Tours In The First To Enter Dhoni Like This Get Over With It Will Take Action On That Upcoming Nation Of The Left And Right Person Key Service Will Come As A String Of Keys Reason Behind Taking A String Cost To Different In The Valley Of No Effigy Time Multiplayer Can Give The Use This Cream And See What Will You Will Contest All Computer Monitor Computers A Key And After Completing Return given value from thm episode will return and don't forget to subscribe the channel subscribe this and don't forget to subscribe the channel subscribe this and don't forget to subscribe the channel subscribe this multiple time ko select se effective work in the tower quotes which mince can sit and court cases competition subscribe to and hear e can see British accent This Top Dynamic Programming Approach Sallu Subscribe And You Have Any Questions And Still You Can Ask In The Comment Section And Fertilizers Solution That Deliberate And Subscribe To My Channel Thanks For Watching
Burst Balloons
burst-balloons
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, then treat it as if there is a balloon with a `1` painted on it. Return _the maximum coins you can collect by bursting the balloons wisely_. **Example 1:** **Input:** nums = \[3,1,5,8\] **Output:** 167 **Explanation:** nums = \[3,1,5,8\] --> \[3,5,8\] --> \[3,8\] --> \[8\] --> \[\] coins = 3\*1\*5 + 3\*5\*8 + 1\*3\*8 + 1\*8\*1 = 167 **Example 2:** **Input:** nums = \[1,5\] **Output:** 10 **Constraints:** * `n == nums.length` * `1 <= n <= 300` * `0 <= nums[i] <= 100`
null
Array,Dynamic Programming
Hard
1042
643
I'll discussions maximum average Subaru one so you are given the integer array nums and an integer K right and you have to find out a continuously sub array Whose Line is actually equal to K so that has a maximum average value and return its value and this question is supposed to be straightforward enough so uh you want to find out if this is the maximum sub array or if this another color this one is the maximum sub array or uh this one maximum sub array right so it has to be a continuous right and this is pretty much the logic and what you have to do is right you want to find out uh the summation right Beyond submission so you need to create another array and then in this array you need to find out like this is one this is 12 this is negative 5. uh oh sorry this is negative five and okay right okay will represent what negative six right but when you add everything up right uh this is not negative it's going to be what uh negative six one two so this is represent two right and then in this one 50 right 50 plus uh 12 62 minus uh it's going to be what fifty one so that is and then this is three right so it's gonna be what uh 50 so it's going to be 39 42 something at least right so the maximum is going to be what the either these three value right because 1 12 and negative 5 are not the continuous separate uh for length of K right so I will leave the same value so I would still try Bruce I was still charged from k position to the end of the array right and then I want to find out the maximum value and it has to be the average right so I'm not going to divide it by K at this time because um at the end you just you can basically return the index value right divided by K so if you divide it by K as over here it will just like you know two ways of time and then the code is not clean right so let me stop holding and then you'll be able to follow along so I'm going to say if the nouns so the basically is going to be equal to what if it's equal to 1 okay equal to one right you just return the first value right all right so I need a the I mean I need another uh in Array so I'm going to say sum and this is going to be like clone the numbers array right and then I'm going to Traverse for four sorry four in I equal to one I less than numbers and I plus so I'm going to leave the index 0 because index 0 doesn't need to do anything right so I still form one two and right so I'm going to say sum this I plus equal to submit I minus 1. all right so I keep adding the previous one right but what if I'm out of Bound for k uh K position so imagine I'm right here right I don't actually need to add this value but what I did is what sum I plus equal sum I minus some I minus 1 right so in this condition I add everything up so it's only one certain and this is negative five so it's going to be what eight and negative 6 will be two and this is going to be what 52 and 55 right so if I just compile this line the array will be like this right but the problem is what the problem is I don't need the value I mean just for example if I'm a listing this I don't need a value for this one right so I need to add the value back um when I add a bond of Windows Okay window right so this is the window 4K this is Windows okay and this is a window 4K right so I need to know my windows K are correct so I need to add a value by so I have a condition say if a curve I is actually good very good greater equal uh 2K right I need to add a value by right so how do you add a value back I need to what subtract so I need to subtract the value right so since I add one uh at this position right I need to subtract one so it's only from 52 so it will be 52 minus one so it's going to be 51 right and then the value is correct and here's a problem I mean uh here's the if statement so I agree okay and I'm going to say something I minus equal nums okay I minus k so you have to notice I need to I need the original value which is a number sorry inside the num sorry I am when I add I'm going to add to summary so if I subtract I need to know my uh original array so uh now I need to know my double it's going to be my return resource so it is I need to set my integer dot member because I need to find out the maximum so uh again I need to Traverse from what okay right okay and I listen announcer lens and I plus all right so K doesn't start for in this zero right so we need to subtract by one right and then result will be equal to what Max sub Max result or what let's summary I minus uh Summit I sorry and uh if you just kind of like wondering why I use non-stop lens not uh wondering why I use non-stop lens not uh wondering why I use non-stop lens not uh instead of some dot lens and you can change it you can definitely change it right but the problem is well there are the same length right and at the end you just have to say result divided by K right because this is supposed to be the average right and this is a double and I didn't like I didn't divide it by K Y over here right and then uh if you do like just say return result but if you don't right you just have to do like this and this is much more clean be honest and I'm going to say running and yeah and that's all the time in space are pretty straightforward uh this is a space so the space is going to be all of them and representing of the norms and this is all of n right from one to earn and this is all of from K2 and right so they are the same all of n so I'm gonna just uh put some breakpoint I'm gonna just put right over here and then probably right over here and then some something right over here and then started above and let me see if I have any better example I just I mean I can just uh use the current one so just look at the left window I'm going to just skip whatever right so uh it's pretty easy right and then what else uh yeah so this will definitely right so result minus I mean resulted by K and this will be your solution so uh if you have any question leave a comment below subscribe if you want it all right peace out bye
Maximum Average Subarray I
maximum-average-subarray-i
You are given an integer array `nums` consisting of `n` elements, and an integer `k`. Find a contiguous subarray whose **length is equal to** `k` that has the maximum average value and return _this value_. Any answer with a calculation error less than `10-5` will be accepted. **Example 1:** **Input:** nums = \[1,12,-5,-6,50,3\], k = 4 **Output:** 12.75000 **Explanation:** Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 **Example 2:** **Input:** nums = \[5\], k = 1 **Output:** 5.00000 **Constraints:** * `n == nums.length` * `1 <= k <= n <= 105` * `-104 <= nums[i] <= 104`
null
Array,Sliding Window
Easy
644,2211
161
hey folks welcome back to another video today we're looking at question 161 uh one edit distance the way we'll be approaching this problem is by looking at the characters in each of the strings as soon as there's one character that's different we try to look at the substrings that follows um after the character that differs and try to see if that matches so let's jump right in uh before we actually get to the meat of solution let's uh do the setup let's get the length of both the strings and n2 will be t dot length and then if we have n1 to be greater than n2 we would just return the same method but we will switch the strings and the reason why we are doing this is because we want to reduce the number of lines of code that we have and we will see that in a second how that will help us all right so by this point we have um s is length to be uh less than t's length and after that we jump right in so for end i equals zero i less than n one increment i and the first thing we do is we check if the character at i in s is not equal to that of t if both of the lengths are the same you just need to return uh the substring that follows the um the character that differs so if n1 is equal to n2 then you would just say return if s dot substring i plus one dot equals since it's a string you need to use equals instead of two equal signs is equals to t dot substring i plus one so you just return that else if they're not similar we know that the string uh s is smaller than that of string t so and it so the thing to make them equal you would have to delete one character from t so you would compare t with the subsequent character but with s you would keep it the same so what you're trying to do here is that hey we know that the lens are different and if they differ uh by one we are comparing we're deleting the character that doesn't seem to be the same and then we're looking at the other substrings to see if they actually match if they match well and good if not you would just return false and then once this for loop is done we know that we haven't um haven't hit any of the cases yet and then in the end you just want to check that the difference in length is actually equal to one for example there's the character that we have to delete is at the end of the string so you just want to make sure that they differ only by one character and that is what you will be returning since we know that n1 is smaller than n2 so let's uh compile to see if it's okay let me quickly fix that all right the first test case passes the other test case pass as well so let's quickly talk about the time and space complexity the time complexity of the entire solution is off and because we are trading through all the characters in s and t and the space complexity is of one since we're not really using any additional uh space to store data so if you have any uh questions about the solution uh that we just looked at please let me know in the comments below if there are any questions about lead code that you wanted to solve also let me know in the comments below also please don't forget to like share and subscribe i would really appreciate that i'll see you all in the next video peace
One Edit Distance
one-edit-distance
Given two strings `s` and `t`, return `true` if they are both one edit distance apart, otherwise return `false`. A string `s` is said to be one distance apart from a string `t` if you can: * Insert **exactly one** character into `s` to get `t`. * Delete **exactly one** character from `s` to get `t`. * Replace **exactly one** character of `s` with **a different character** to get `t`. **Example 1:** **Input:** s = "ab ", t = "acb " **Output:** true **Explanation:** We can insert 'c' into s to get t. **Example 2:** **Input:** s = " ", t = " " **Output:** false **Explanation:** We cannot get t from s by only one step. **Constraints:** * `0 <= s.length, t.length <= 104` * `s` and `t` consist of lowercase letters, uppercase letters, and digits.
null
Two Pointers,String
Medium
72
32
Everyone, my name is Shashwat Tiwari and I am talking about Longest Pilot Paranthesis in today's video, so if you have not seen the old video of Stock then go and check it out. We are dealing with a very similar problem and this will be the last problem of the series of Stock, after this we will You will move to the quiz and if you are new to this channel, then many series are already out in which we have done all the interview questions like what is the pattern of binary search, what is the pattern of stock, what is the pattern of Richardson, back tracking. What happens to and now more videos are coming daily, so just like this video, subscribe to the channel and let's start today's lecture, the name of the question is the longest velvet parenthesis, this is what life is. String containing just the characters return d length of d longest valid formed parents substring ok what do you mean I understand you look valid parents we already know and if you watch the old video then I have already taught you that but I would have been valid Yes, nested is valid in this way, so you can find out the valid wallet. Here the question is whether you want to find out on the longest wallet or you have to find out the valid parenthesis, what does it mean, like look at this, it is closing, it has no opening as well. No, that is, this is a valid pay, okay, this is an opening, this is a closing, date main, this is a valid pay, similarly, this is an opening, this is a closing, this is a valid pay, now because both of them are written consecutively, that means if there is any in between them. If invalid fare is not there then I can do this, you bill make a valid fare, it has become valid and its length has become four, it has become correct. Similarly, this one of yours is on invalid because it does not have a corresponding opening, it is also invalid, okay. But what is this one opening, what is this one closing, that is, this one is on a valid, this is opening, this is closing, okay, so this is also valid, correct, similarly, look ahead, this is opening, this is One closing is valid, this opening is valid, this is an empty opening, it has no closing i.e. is this opening, it has no closing i.e. is this opening, it has no closing i.e. is this invalid correct, so I can, its length is four, this is again, you are this, again you add them up. Get 10 direct parents longest four and what is the big value in 10 is the answer so 10 is my answer ok I understood the question now let's think how to solve it so first clean it a little ok so first of all brute Let's start with the force. Look, what is the concept in your mind? Let me tell you what is coming in my mind. One is invalid, one is invalid. If I know the location of these taxes, then two are invalid. What is there in between? If it can be valid, then I can say that the length between these two is fine, that is, what will be the length between zero and five? How am I extracting this in the lens: Apar limit minus How am I extracting this in the lens: Apar limit minus How am I extracting this in the lens: Apar limit minus lower limit plus? One mines that I will get the length between zero and five both five and six What will you get the length between zero and six and 17 10 So if I take this as max then my answer is 10 Absolute brute approach is fine So what will I do, what do I have to do blankly, I have to find their index, so how will I find their index, there are two steps, this will be done in two steps, the first step is what to remove N which is valid parenthesis, okay and this is what you know, which is most common. Nice [ __ ], this kiss happens, we have seen it in many videos, [ __ ], this kiss happens, we have seen it in many videos, [ __ ], this kiss happens, we have seen it in many videos, let's do it by the way. If you are thinking, you can go and check out the already video. It is in this playlist and there are many videos in quite length. Now, what is my stack finally? Look, here we will go to index A. Okay, basically, I want length, right, so I want index, not pancreas. 17 So this is opening and closing once. Okay, so this is my stack created. I want distance between them, so look, this is a little. Hotspot is going upside down, stag is formed, what do I do, I am converting it into a list, okay, for the sake of readability, if I can solve this, then I convert it, so how will my list be made, 12 Wickham, something like this, okay Here you will get 056 17 Okay, now I have to reduce it very simple, put one point here, what will be the distance between these two, then 5 - 0 -1 This will be your A then 5 - 0 -1 This will be your A then 5 - 0 -1 This will be your A 10 Now you What has to be done? If I want to keep finding the max among these three, then I will initially make a max and make it zero. Now among zero and four, first four will be bigger. Okay, let us make zero and four bigger again by four. Let 10 and 4 be 10. It will become bigger and finally when I go out of this loop then what will be my answer 10 ok maths I am also pointing this out debt bill b answer first how ok one more thing if your stock is empty ok that is There was no invalid in it, otherwise the length of your string will be your answer because you want the longest valid. There was valid in the stock. Brother, Twin is not valid, it means that the validity of the entire string has been taken out. Let's look at this one more time. I told you that these are invalid ones, if you reduce the border then you suggest that I do n't have these valid ones, that is, they are not invalid in the starting, but at other places, that time is like this situation, there is a power like this, open close. Open Close Okay, this is a situation like power, so how will you keep water in it, one, you got this, what will you compare with this, so obviously I have to push minus one here, okay, so now I can find the length between these and So how can I do that if I do n't have a closing and there is an invalid lying here then what I have to do here is to put a border which bill b is the length of the string N Okay so what I do is I additionally add my era Here I will put -1 in the beginning, it is okay and I will put -1 in the beginning, it is okay and I will put -1 in the beginning, it is okay and I will put the length of the string in the last. Now you see, if they read invalid on my border, then it will not make any difference whether they are there or not, how zero minus one, it is okay. If you solve it then the answer will be zero. Similarly 18 - 17 then the answer will be zero. Similarly 18 - 17 then the answer will be zero. Similarly 18 - 17 -1 Even if you solve this the answer will be zero -1 Even if you solve this the answer will be zero -1 Even if you solve this the answer will be zero so there will be no difference in your overall answer but if this zero was not present then you see how helpful it would have been in correcting it. Let me show you its code and I am not coding it, I have already coded it, actually we have ported it to many places, so I just grabbed it and put it in one place and am showing you because on this It will take a lot of time. We will code the complete butter approach which we will discuss. Okay, so first of all we have reduced the remove valid paranthesis. Now you know that there is a stack, don't know. Watch the old video, so I wrote a function here is the remove valid paranthesis. It is very simple, if it is open then push it, if it is closed then there will be only two conditions, if the stock is empty and you get close then it is valid. If it is already closed on the top of your step and you get close again then also that If it is invalid then that is what I said brother, if it is valid then push. Adverwise, if you had read an open and you have got a close, then open close, make a leg, then pop it. It is very simple logic, will not go into details, there is no invalid. What I did here, you see, the first thing I interested you in is the length It's It's It's going upside down, right? I'm like, let me show you if I want to create my arill from the stack, the first value here is what's going to pop 17. I kept 17 on status, the next value which was popular was six, so what did I do, I again kept zero on index, so whenever you insert on this index, the other elements get shifted. Aerialist's video is not good, so watch it. Okay, the structure is there, so how will it be created and 17 will go on the first index, okay, so this is the concept, so what I did was, first of all I entered the length of the string, then I entered whatever values ​​were in the stock. entered the length of the string, then I entered whatever values ​​were in the stock. entered the length of the string, then I entered whatever values ​​were in the stock. And in the last I gave mines one pulse, ok so two waters were added and all the invalid pulses in between the stock, let's think last, this is just calculating also the maximum difference, so this is very simple, I have created a maths variable, its value is zero because I know. I never have any negative values inside the stock which I have purposely inserted empty one. Okay, to calculate the length, first the value of ears is okay, this is basically zero thinnies and this is this. If we talk about this, then this is first. If the index is fine then give it zero, so take out the difference of whatever value the first index is. If it is maximum then store it. Okay, first and second indexes will go ahead. Second and third and next indexes will go ahead. Okay, so I have started it from one. And I - 1 and I am running it like this, And I - 1 and I am running it like this, And I - 1 and I am running it like this, okay then all my elements will be compared in pairs of two and I will get the maximum answer if you run this so this bill will be very slow okay, let's see something. What percentage is I don't remember no 5.93 ok almost negligible very useless ok but 5.93 ok almost negligible very useless ok but 5.93 ok almost negligible very useless ok but why because but why should we do brit force because this gives us the idea of ​​optical now gives us the idea of ​​optical now gives us the idea of ​​optical now how can we optimize it is there one thing that I am doing wrong I am doing it as late as I am checking out. Okay, let's go back to our question. Here we found zero on the index, this is the first valid leg, okay, you will see its length from this, you will see this zero, you will see, correct, when this fourth leg will also become a valid leg. With this, 4 and 3 become valid, so all these become your valid stacks. Okay, so I can take 420. I can also take out 420. And obviously, if zero is not the index, then we give minus one. Now we have done this. See, what is the point of eating butt? The actual point of my eating is that we have to keep replacing it on these valid ones like it is on the first invalid one. Now when you see this tree of seven and eight, then with what will you compare its length. You will not do it with five, you will not do it with zero, you will do it with six because this is the most recent and valid. Okay, now similarly if you look here, then 9 and 10 and 11 are being made on perfect, okay and till now I have done 12. So at this point of time your recent in valid is not six this recent in valid is your nine ok so you will see from nine to 11 but at the moment you got 12 when you will see yes man 9 more 12 rates, you have already removed your taxes, Sir, valid foot, so child, is six okay, that is, are you looking at the car, where is it being attacked, what do we have to find it, that is, what should be in my stock, always on the top of my stock. What should be if b is ending in a valid then what should be always on the top of my state most recent in valid parent valid bracket if b is always ending in a most recent in valid parent valid bracket then that will give me the distance That brother, it is ending here from here till here, it is fine and because as I said, it is ending at 12 and 12 is inclusive, that is, 12 is ending someone but the six ones are not inclusive, so am I in this? I will apply the formula on you Limit Minus Lower Limit Ok -1 +1 Nothing Why Lower Limit Ok -1 +1 Nothing Why Lower Limit Ok -1 +1 Nothing Why Ok Because Here One Is Inclusive One Is Exclusive This Is Already Explain Please Watch Previous Lecture Ok So You Got An Idea Right We Got An Idea Now how do I have to handle this N thing that when I have to put more in the last, no right because I am checking at every point that nothing else is happening here, now you look at 17, you know. 17 is valid, nothing else is going to happen here, so why would you calculate the distance between you and dal 18, you 17 wo n't you do it right, so I don't need it at all and if there is a closing here and it is a valid closing. This means what will happen on the topic of my state will the previous in be valid okay so I can go from current to previous so let me try run it let it bill be match more clear but we are getting the idea what we want most Let's go from the top of our state from recent in valid, now what do I do, create here, okay, so the stock is not made very well, but we will make a good solution, now I don't have a strike vote, so I did something, already I have to handle the time, when we have Next we have to mark it as there should not be any invalid in the beginning so this is the most recent invalid. Okay sir, I have to pop it, why I have three situations, if one is valid then this one will be popped because there is one invalid. Okay, if it's mine one or already closing then I have to update it that brother, this is the current element, it has become my most recent and in this process what I have to do is to keep calculating the maximum, okay max let's calculate this. Hindi process ok so I serialized my max ok now for the first time I got the close ok @do so what I did was I @do so what I did was I @do so what I did was I popped it and because the stack got empty then I inserted the index of this close This is denoting this close now I have to calculate the max so what is the current value which is the index that is zero ok zero is the topic your zero is lying so I can say zero minus zero then the value is a match between zero and zero Zero this is not updated ok let's move ahead got one open so whenever you get open this bill b n blind area ok again same concept here pe value one is also on the top of the stack so one mysore bill b zero Now let's go next, I have found you, okay, I will pop the view on the top of the state like this, now I am not left empty, my stack is not empty, what does it mean after the sin, there is an old invalid already lying there, so now I What to do is current index witch it is tu main ka sakta hoon tu mines hoti hai to 2 - 0 bill b tu to aapka hoti hai to 2 - 0 bill b tu to aapka hoti hai to 2 - 0 bill b tu to aapka maximum update ho ke tu ho gaya understand the concept let's go ahead index 3 opening got ok so let's go to current value now you Found one closing, pop it, ok, if the stock is not empty, then nothing will be done. Make the current index 4 - 0, nothing will be done. Make the current index 4 - 0, nothing will be done. Make the current index 4 - 0, that is, 4 - the topic of the tank is zero, this that is, 4 - the topic of the tank is zero, this that is, 4 - the topic of the tank is zero, this value will become 4, so your maximum has been updated to four, ok, next value. Five okay this is closing so as soon as it's closing I popped the top of the tag and because the stock is empty I inserted this so five and this value this is closing okay and here's what we do 5 - 5 Why current value is also 5, what we do 5 - 5 Why current value is also 5, what we do 5 - 5 Why current value is also 5, top is also five, so this bill will be zero, nothing will be updated, let's move ahead, like closing is found, pop it, okay, and give what you have to do 6 - 6, this okay, and give what you have to do 6 - 6, this okay, and give what you have to do 6 - 6, this bill will be zero, okay, further. Let's go I reduce it I rub it I also have a six in my step okay I'm raping it Next let's go got an opening okay 797 bill b zero okay so nothing will be updated Next let's go a closing Found like closing, we will pop it. Stack is not empty, it means there is no need to insert it. Current index is placed on top of tax. It is 8-6 bill b tu maximum 8-6 bill b tu maximum 8-6 bill b tu maximum update is ok. If nine is found then index is 9. Inserted this is an opening ok so 9 - 9 wheels television ok so 9 - 9 wheels television ok so 9 - 9 wheels television ok so we don't have to do anything there will be no update here let's go to the next value so I got 10 ok what is 10 again this is an opening so insert 10 then From 10 - opening so insert 10 then From 10 - opening so insert 10 then From 10 - 10 will become zero 11 Milan like closing is here closing came pop will do value what is current 11 stock topic what is 9 so 119 is 9 bill b tu 11 mines nine bill b tu again update nothing happened Let's go ahead, got 12, okay, it is a very interesting concept to see here, like you got closing, you eliminated the top of the stock, now see from the current index, you can also see 12 -6 12 - 6, it is okay from here till here, so you I saw how well you got the length. I was talking about what is the benefit of doing every point, which D. All these must be singing to you, we are doing unnecessary, okay but this is this same this but if we move ahead then I will open. Got again I have emptied my stock and lay down now see I am lying empty sex in this type Next thing index 13 Now you got an opening so index 13 Aa this bill b blind in session 13 - 13 bill b zero Next thing will go a 13 - 13 bill b zero Next thing will go a 13 - 13 bill b zero Next thing will go a closing If you get it then pop the top of the stock. Now your stack is not empty so what do you have to do. 14 - 6x 14 - 6 This bill will be what do you have to do. 14 - 6x 14 - 6 This bill will be what do you have to do. 14 - 6x 14 - 6 This bill will be again. Your maths has been updated to 8. Ok let's go ahead. Got an open index 16 value bill. B open again 15 - 15 there is no point to zero let's go ahead - 15 there is no point to zero let's go ahead 16 - 6 this bill B 10 16 - 6 = 10 which is actually your answer so let's do 16 - 6 this bill B 10 16 - 6 = 10 which is actually your answer so let's do 16 - 6 this bill B 10 16 - 6 = 10 which is actually your answer so let's do your maths after updating it will become 10 let's go next index found 17 Which is n opening is ok so if there is opening then blind answer will be ok 17 - 72 because top of your stock is also 17 - 72 because top of your stock is also 17 - 72 because top of your stock is also 17 and current value is also 17 also zero no need to change now you move ahead your stock is finished ok means your When the string ends, what is your answer? 10 is okay, so how well have we solved this question of such a fragment. What is its time complexity? Bigo open single light reaction. We are not doing anything. Let's then. Let's code this quickly, basically I have commented the rest for you sir, you can just read it later, so first of all I have to create a tag, stock interior is ok, equal, you are done, let's push this in the next value tag. This starting condition now hydrate so on and i = 0 i a li give your so on and i = 0 i a li give your so on and i = 0 i a li give your saline gf ok spring and give i convert to plus character so s dot ok so i know which bracket is this now check Brother, if this is an opening, now your closing comes, then what to do in the process of closing, first of all hit the pop, okay, you don't know what is going on, if your stack becomes empty, it means the current closing will become your new value. So how did all three go, let's submit, okay and if you want, how can you correct what I was calculating again and again that it is zero, then it is obvious that if your state has become empty, then it is okay. To understand this thing, you have done some stock and from both the values ​​of I-Tag and P, the some stock and from both the values ​​of I-Tag and P, the some stock and from both the values ​​of I-Tag and P, the time is right, so I can simply write here that at this time I know that when it is going to be zero, then I What should I calculate in this empty help? I do n't always calculate it. Okay, so you can do something like this. Okay, if we submit now, then I don't think it will be much faster. Let's make a method. Start video out. How to create custom tag etc. New tent is ok and let's take its size alien gt ha plus one let's take it because I have to do one mines and what do I need index so and index it is equal to you mines one correct now how do technicians do it so stock in custom First increment the index, okay and then insert the value, that's why I am not returning, how do we check this, so this comment date and paste and I have copied it okay how will you do, I do n't need anything here. Okay I don't need you and okay so I think is there any improvement in this okay if you also make your collection film do n't talk much nonsense in today's video if you liked the video then first of all like this video. Share with all your friends, subscribe to the channel and see you in the next video, till then bye take care and obviously this is the last video of June's challenge so if you have completed the challenge then Congratulations and if you have come to this video of Bole Butt and you have come before 10th June, the challenge is going on from 10th June 2023 to 2nd June, go and participate in it, who knows, you may get a chance to win a mechanical keyboard which is definitely very Good, I will not give you this one, I will give you my new one, ok, so this is just a test video, see you in the next video, till then bye and tech.
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters `'('` and `')'`, return _the length of the longest valid (well-formed) parentheses_ _substring_. **Example 1:** **Input:** s = "(() " **Output:** 2 **Explanation:** The longest valid parentheses substring is "() ". **Example 2:** **Input:** s = ")()()) " **Output:** 4 **Explanation:** The longest valid parentheses substring is "()() ". **Example 3:** **Input:** s = " " **Output:** 0 **Constraints:** * `0 <= s.length <= 3 * 104` * `s[i]` is `'('`, or `')'`.
null
String,Dynamic Programming,Stack
Hard
20
120
hello friends to the rest of the triangle problem you a triangle find the minimum part some from top to bottom you step you may move to Agency numbers on the row below for example given the following triangle the minimum has some front of to bottom is two three five one so as we needed to find the minimum has some we may think about using greedy algorithm or dynamic programming let's see whether we can use a greedy algorithm the answer is not why because you see if we change this fight to seven and the changes is seven to two at this row we will pick us three but in this row we just can't pick either six or seven but you know there is a 2 here so the path to hold 2 will be the minimum pass so we cannot everywhere pick the minimum it will known to get a global minimum person so we needed to use dynamic programming but there is also another constraint that we can only move two agents term numbers that means here we are at Rosia : 0 so in the next row we are at Rosia : 0 so in the next row we are at Rosia : 0 so in the next row we can either choose the : 0 or : 1 and we can either choose the : 0 or : 1 and we can either choose the : 0 or : 1 and if we pick it up : 0 here in the next if we pick it up : 0 here in the next if we pick it up : 0 here in the next row we can either choose : 0 and the row we can either choose : 0 and the row we can either choose : 0 and the column 1 we cannot pick the Colin - if column 1 we cannot pick the Colin - if column 1 we cannot pick the Colin - if we start from the row 0 we may need to record the minimum person at each column and also the row so in my opinion we need a 2d array to record the minimum person but actually we do not need to record as a row if we start from the last row atom here we know like we add a colon zero we know the in the next row we can either choose the column zero and all the column one if we already have their minimum path some now we just pick their minimum and add that occur in the value let's see what I mean if we start from the last row we first get their minimum path some of with each value so we get a DP 0 equal to 4 DP 1 code you want TP 2 you go to 8 tip his really go to 3 and when we go to the this row like we are at the colon 0 we may pick the minimum from the DP 0 + DP may pick the minimum from the DP 0 + DP may pick the minimum from the DP 0 + DP 1 and the ad is a current value which is 6 so we know in this time the DP 0 will be 6 plus 1 will be 7 right here DP 0 will be updated at shooter 7 the same idea dpi will be updated to 5 plus 1 will be 6 Tippett who will be updated at you 7 plus 3 which is 10 and there we go to the previous row we use the 3 plus the DP 6 our DP 1 which is 6 so we get 3 here DP 0 Y will equal to 3 and the DP 1 will equal to10 4 plus their minimum over 6 and 10 so we add 6 we get 10 and for the first row we master pick this very because we only have one value so the p 0 will be the minimum of 0 values and plus is 2 so we get 11 so at the end of just needed to return the DP 0 because we have to pick this one so what does this DPI me which means the minimum has some in the : I we started minimum has some in the : I we started minimum has some in the : I we started from the lateral so do not need to record a row because for every column we already have the it's a minimum pass that's the column I add : i plus 1 that's the column I add : i plus 1 that's the column I add : i plus 1 actually use J so J and J plus 1 we can use the previous calculated value so now let's write the code for your information you see the rows each ego tooth fall but actually the row index just a 0 to 3 but what about the size of the DP array which they initialize to fight why because when we calculated the first DP for values this DP 3 we will use a DP 3 + DP 4 so in order to do not use a DP 3 + DP 4 so in order to do not use a DP 3 + DP 4 so in order to do not need to check there if the index is valid we just used letter D P array 1 larger than the size of the rows so let's write the code first a simple educator it's their triangle Darlins you go to 0 or just return 0 otherwise gather rows you go to the try and go those thighs we get to the DP the size will be rows plus 1 you will see why we needed to plus 1 and then we start on the last rows which is rose minus 1 all right great origin 0 I - - and then all right great origin 0 I - - and then all right great origin 0 I - - and then J start from 0 j r s equals n IJ plus you see back here the is 3 ok you see here the i is 2 and J will the very the jail will be 0 1 2 so trees the largest G will be equal to the I then DP j will coach you minimum DP j plus 1 which means the last if we had this row we will use the DP j DB j plus 1 which means the following row value plus the current triangle get current row get the current column value so if you see we add to the last row we will use the previous actually the following row so we will use the 3 for this d piece we will use deep history TV for tip is ready before that's the reason we make is one larger than the rows final gesture written to be 0 okay thank you for watching see you next time
Triangle
triangle
Given a `triangle` array, return _the minimum path sum from top to bottom_. For each step, you may move to an adjacent number of the row below. More formally, if you are on index `i` on the current row, you may move to either index `i` or index `i + 1` on the next row. **Example 1:** **Input:** triangle = \[\[2\],\[3,4\],\[6,5,7\],\[4,1,8,3\]\] **Output:** 11 **Explanation:** The triangle looks like: 2 3 4 6 5 7 4 1 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). **Example 2:** **Input:** triangle = \[\[-10\]\] **Output:** -10 **Constraints:** * `1 <= triangle.length <= 200` * `triangle[0].length == 1` * `triangle[i].length == triangle[i - 1].length + 1` * `-104 <= triangle[i][j] <= 104` **Follow up:** Could you do this using only `O(n)` extra space, where `n` is the total number of rows in the triangle?
null
Array,Dynamic Programming
Medium
null
336
hello everyone so today we will be solving talent from pairs and it is day 13 of june read code challenge and the question goes like this given a list of unique words return all the pairs of distant indices i and j in the given list so that the concatenation of the two words i and words j is a palindrome so question is pretty simple i hope you must have understood it so if we take an example we need to find two words from this words array and concatenate them and check whether these words form a palindrome or not if they form a palindrome and if their indices are not equal we need to return them in our result area so uh for this uh array we have zero one as a pair so a b c d c makes up a palindrome and similarly we have these also so the first intuition for this problem would be a brute force solution where for all the words you will run loop and try to find out that concatenation with every other word will give me a palindrome or not but it would be uh not accepted as it will give you a tle because it will be more time consuming so what we will be doing here is that we will looking at some optimal approach to go with this problem so let's give some time to yourself and try to find out whether you can come up with such a solution or not and so here what we will do is that so we will understand some basic uh approach how we can solve this problem so let's say i have two strings let's say i have a string a which is something i'm not specifying what it is and string b which is something let's say stars so i need to find out when a plus b will be a palindrome the question i need to answer is this so let's say for a i put a gap here or i put a space here so i have divided my a into two parts this is the left part and this one is the right part now what i'm saying is that let's consider this left part was a b c and this b string was uh c b a just to understand let's assume this so what i can see is that if i reverse this abc prefix of this a string which is cba and if i append this here cba so if this internal part was a palindrome and appending this to the end will give me a plus b as a culling room what we just discussed is that plus what i'll say is that um if this words of i itself is this empty string then continue and if otherwise if this is palindrome so this word is palindrome if parent room this words of i then i need to add it in my answer so let's start push back uh it will be so hm of uh empty string and i so for every empty we need to uh have all the palindromes that are there in our words array so let's now try to run this now this is working fine so let's try to submit it okay it got accepted so thank you everyone this was for today if you have any doubts please leave it in a comment i will try to solve that out also thank you so let's take an example uh let's say we have a def as a string and a b c as a string or let's say we have a f e as a string so and what i've learned we want to check for every word whether it is possible or not to make a palindrome with other word so let's say we check first for let me make a map instead first because i want only the reverse of b not with the b so for every element i want its reverse so i will store it in a map so let's say a def will become fed uh abc will become c b a and f e become e f now so for the ef let's partition it from the zeroth index so left of this is the empty string so do we have any empty string here so we need we are checking the reverse of b or reverse of any other string in the array so there is no reverse string which is equals to empty and is there any reverse string which is equals to d ef so this is the left part and this is the right part now so no def is also not present so what i will do is that i will shift my uh break point to the first position now left is d do we have a d in our map no we don't have a d e now map do we have ef in our map now ef yes we have ef which is basically a reverse of a string fe so now we have ef in our map i know that we can have ef so i will check the other portion whether this is a palindrome or not so d left part is d itself it is a parent room because it is a single character and all single characters are palindrome so i know that this is a solution so what i will do is that i will append ef here and it will sorry ef so i will append f here because the original string was fe you can see here it was just the reverse we have checked for so f e d e f is a palindrome now we got one answer here so we will store it as a zero and what was the last one so it was d e n 0th and second position so this was one result let me write this result in yeah here now we are done with this so we will move our break point to next position so d e is present let's check for in the map no d is not present and whether single f is present no it is not and if you similarly check for the other elements they will not be present so what this case our answer will only be 0 2 now i have and i think you must have understood the way we are going to code it so let me tell you one thing that we will also be storing index in the map just to check whether the index is not the same index for the element which we are checking for so let's say we are checking for def so we don't want to check for the same index here okay so now let's try to code it out so let's take an order map of string and integer and let's name it hm so first of all let's store all the words in the map so for int i equals to 0 i less than words dot size and i plus so what i will do is that i will take in the some other string uh let's see temporary string which is equals to words of i and let's reverse it reverse of time dot begin to temp dot and just put it into a hash map so hash map of temp will be equals to i uh so we have created our map now we want to check for uh all the words in i equals to 0 i less than words dot size and i plus for every word so for in j equals to 0 j less than words of i dot size so for every word size what i will do is that i will say left is equal to so it will be a string sub string from so left will be my words so one thing we are missing here is that our code might not work for this test case because uh it will yield as 0 1 because it will take a and empty string but for empty string it will not take a as answer so i don't think 1 0 will be a solution let's run for the basic case and let's try this so it is working for a base case let's see this so let's learn this yeah it is not giving us one comma zero so uh what we need to do is we need to handle this uh separately so for uh let's say if uh hm dot uh fine this empty string is not equals to hm dot n which means there is an empty string in our map so what we will do is that uh for all the words and i equals to 0 and i less than words dot size i plus what i will say is that um if this words of i itself is a this empty string then continue and if otherwise if this is palindrome so this word is palindrome if parent palindrome this words of i then i need to add it in my answer so let's start push back uh it will be so hm of uh empty string and i so for every empty we need to uh have all the palindromes that are there in our words array so let's now try to run this now this is working fine so let's try to submit it okay it got accepted so thank you everyone this was for today if you have any doubts please leave it in a comment i will try to solve that out also thank you
Palindrome Pairs
palindrome-pairs
You are given a **0-indexed** array of **unique** strings `words`. A **palindrome pair** is a pair of integers `(i, j)` such that: * `0 <= i, j < words.length`, * `i != j`, and * `words[i] + words[j]` (the concatenation of the two strings) is a palindrome. Return _an array of all the **palindrome pairs** of_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "dcba ", "lls ", "s ", "sssll "\] **Output:** \[\[0,1\],\[1,0\],\[3,2\],\[2,4\]\] **Explanation:** The palindromes are \[ "abcddcba ", "dcbaabcd ", "slls ", "llssssll "\] **Example 2:** **Input:** words = \[ "bat ", "tab ", "cat "\] **Output:** \[\[0,1\],\[1,0\]\] **Explanation:** The palindromes are \[ "battab ", "tabbat "\] **Example 3:** **Input:** words = \[ "a ", " "\] **Output:** \[\[0,1\],\[1,0\]\] **Explanation:** The palindromes are \[ "a ", "a "\] **Constraints:** * `1 <= words.length <= 5000` * `0 <= words[i].length <= 300` * `words[i]` consists of lowercase English letters.
null
Array,Hash Table,String,Trie
Hard
5,214,2237
84
Hello Hi Guys Welcome To Our Hazy Sea Today India Largest Is That Police Particular Example The Largest Area And This Tennyson Explosions At This Time Plot In The Same Example In This Particular Diagram With Sacrifice Will You Help Me To The Dad-Khaj Height Baje List To Suite Fiction Dad-Khaj Height Baje List To Suite Fiction Dad-Khaj Height Baje List To Suite Fiction End Of The Year - - - - How To Find Every End Of The Year - - - - How To Find Every End Of The Year - - - - How To Find Every Day For All The Best Solution Is 200 Ko Left Boundary Eye Dubai Starting Index 1200 - - - - - 4a Index 1200 - - - - - 4a Index 1200 - - - - - 4a CR Inductive 15000 also left right 10 wave all aware of intense pain on the left arm ki subansiri has this every field pure depth and area and can update serial depending to subscribe to a will take and medical store the length of the are a serious issue Be busy Hindustan ki the Indian delegation right Arya when will be decorated but this happened in here laptop zero bells minus one key and right ascension Vikram and a why not extinct to then dictionary app tomorrow morning start with force and research torch light and variable Previous Which Food Is - Spand Supercomputing Is The Previous Greater Than Equal To Zero And Top Leaders To Bag No Request To Content With Others To Share Me Shopping Song And Similarly It Will Come In A Serious Lesson And Thanks Loot Luti New TVs Equal To right pillar and finally e the site of a girl on laugh heartbeat various fields near wits and area hai to kabhi again local i20 anis appointed a bit setting khol do a right - select - one and area equal ko a right - select - one and area equal ko a right - select - one and area equal ko maximize aa giri tour at Home Phone The Elections Code That Gandhi Now Water Tight Result Latch Related And Submit It Over All Of You All Subscribe To In View Of Daily Sex Similar To Tawang Valley Shopping Question Writing To Increasing And Decreasing The Yesterday Morning Yes Line Area For The Element At Present E a love you find area with cotton element from the states in the element area which comes to top that multiplied by current batter chief currents one is remedy - - 1 remedy - - 1 remedy - - 1 that boat office sperm 0n specific gravity morning area which comes to multiply by karan is For any wall at index for wood reddi elements in this pack plus current 1947 to for this is improve young area of ​​pain and this improve young area of ​​pain and this improve young area of ​​pain and this update day that area in top 10 where the area of ​​the height of do the area of ​​the height of do the area of ​​the height of do the four tiller is not regret and Serious serious about it hua tha word after 10 pirhas follow us on jai hind school will take video force reason hi situated ki dubi is inc80 otherwise a that your smartphone find in the meantime is this the current hybrid comes great money slow hai high to top Element of distic planning pray that some deposit increasing sequence is the opposite point and extract white apple cider volume further down not mt and the current account is lesson so with dot c in 10k sweety's semen laptop with good health department subscribe now to 9 That with equal 2f activity will be compiled otherwise Begum Right - - - compiled otherwise Begum Right - - - compiled otherwise Begum Right - - - - A - A - A tomorrow morning of wealth will find area which will be easy because height multiply back the west that unmarked area Vikram Shubhendu ko maximum bodh area is Who is the smile on this not android increasing scene that oo a push dhoi index of chronic written on the elections code mein bandhenge isko pane submit thas ends the girls at a time and space complexity of a
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
1,598
hey everybody this is larry this is me going over weekly contest 208 of the leeco contest um it turns out 208 is my lucky number so we'll see how it goes um so for this problem we're gonna go over quarter log file a folder um so this one i actually don't know if you need the child photo x if you wanted to go faster and some people do you probably can actually just skip that um but basically it becomes a stack problem right where if you use dot and you have done command line before it goes to the previous um previous directory so then you pop off one level of the stack and if you just one dot that's just at the same level so you could skip that entry because it does nothing otherwise you append that entry because that's the uh you're one layer deeper in the stack right so that's kind of the short story about this um i don't know if there's any tricky explanations i think you can you don't even need to define uh the directory name because i think you just keep on appending them and it shouldn't matter either way as long as you can assume that they exist um but yeah so this is linear time i guess linear space or height of the uh the longest path space um we are pretty straightforward um if you have trouble with this definitely play around with the stack get familiar with it um problem like this is going to be on you know like on an interview level even you know or problems harder than this requiring the stack will be on a lot of interviews so definitely check that out um yeah so that's what i have with this farm i'm you're gonna watch or you can if you like self watch me stop just live uh next so there's two the party next door is still going on in case you're wondering i'm gonna do this recording because well i want to remember that one time i did really well but basically for this problem uh i knew how to solve this right away um it's basically i mean it's stacked right uh because some of this is the intuition behind knowing how directories work because i you know i've been programming for many years i've been using computers for many years uh so i knew that's how you would represent it most naturally so that's basically what i did uh i think i just want to make sure that um the only question that i had was if you change directory you know in real life uh you can actually see these two multiple depths at one time so i had to read it a few times to make sure that you can only go at most one depth uh and that's basically what i did uh for this one um yeah uh for one dot you ignore for two dots you pop the stack and then for anything else we just push it onto the stack uh and it turns out that we don't even care about the name we're gonna push to anything because you know duplicate names are okay and it doesn't change anything so yeah i was being a little bit careful here but at the end i just changed number stack because that's the number stack is how you get back to the beginning uh and i had a typo because i don't know i was using another language or something it looks good submit bam q2 um uh hey thanks for watching uh let me know what you have about these problems uh hit the like button to subscribe and join me in discord and it's been a very lucky contest for me so if i'm a little too kitty anyway i'll see y'all next problem bye
Crawler Log Folder
crawler-log-folder
The Leetcode file system keeps a log each time some user performs a _change folder_ operation. The operations are described below: * `"../ "` : Move to the parent folder of the current folder. (If you are already in the main folder, **remain in the same folder**). * `"./ "` : Remain in the same folder. * `"x/ "` : Move to the child folder named `x` (This folder is **guaranteed to always exist**). You are given a list of strings `logs` where `logs[i]` is the operation performed by the user at the `ith` step. The file system starts in the main folder, then the operations in `logs` are performed. Return _the minimum number of operations needed to go back to the main folder after the change folder operations._ **Example 1:** **Input:** logs = \[ "d1/ ", "d2/ ", "../ ", "d21/ ", "./ "\] **Output:** 2 **Explanation:** Use this change folder operation "../ " 2 times and go back to the main folder. **Example 2:** **Input:** logs = \[ "d1/ ", "d2/ ", "./ ", "d3/ ", "../ ", "d31/ "\] **Output:** 3 **Example 3:** **Input:** logs = \[ "d1/ ", "../ ", "../ ", "../ "\] **Output:** 0 **Constraints:** * `1 <= logs.length <= 103` * `2 <= logs[i].length <= 10` * `logs[i]` contains lowercase English letters, digits, `'.'`, and `'/'`. * `logs[i]` follows the format described in the statement. * Folder names consist of lowercase English letters and digits.
null
null
Easy
null
1,609
hi in today's video I'm going to solve this question of e or Tre um the question is we are given a binary tree is named even not uh a tree is binary tree when it meets the following conditions the root of binary tree is at level index zero okay so the root of or B is at zero index okay its children are at level index one and their children are at level index two for every even indexed level means um 0 2 4 all nodes at the level have OD integer values okay so uh at e index all the nodes will have odd values okay all the nodes will have all values okay in a strictly increasing order okay strictly increasing order from left to right okay and at or index means 1 3 or four all noes will have all notes at the level have even integer values in a strictly decreasing order okay so values will be even and in decreasing order uh it will be also from left to right so okay I'm going to write it again okay so I'm going to have a binary tree wait me is it I'm going to have a binary tree which is called even not okay the root will be at zero index and uh at every even index level uh I'm not writing even index level I'm just writing uh 0 2 4 values will be value of node will be OD in increasing order I mean if it's first three then it can't be one it will be 3 5 7 9 okay and it will be from left to right increasing from left to right okay and at odd index which is 1 3 or five the value of node will be even okay uh the value of node wait the value of node will be even uh it will be decreasing and also from left to right so okay uh given the root of a binary tree return true if the binary tree is even not otherwise return false okay so how we are going to solve it even means following all these conditions okay so we are given an example we are going to see this 1 10 4 okay 1 10 4 3 null okay so it is what is this doing is uh BFS it is doing depth for search in pre-order okay because root then left pre-order okay because root then left pre-order okay because root then left then right okay uh the notes value on each level are uh level 0 1 uh me means uh one thing is fixed that at level zero at index one I mean the root value is always going to be an odd number okay this is fixed okay 11043 the nodes values on each level are these since level 0 and two are level0 and two are all odd and increasing and levels one and three are all even increasing the three is not okay so how we are going to check it the node value on each level are this okay so what it what is it doing is okay let's assume I'm going to do dep for sech okay so in three okay 1 10 4 uh what I can do is z 1 2 3 4 okay so I can again use DFS with pre-order in this because it will write pre-order in this because it will write pre-order in this because it will write something like this okay so what I'm going to use it that for search Okay method will be pre-order by pre-order because it will pre-order by pre-order because it will pre-order by pre-order because it will go from root then left and then right okay so uh it will first go in root then left and then right okay so DFS will do depth first search and we can write it something like this you know if I'm getting root will be in level zero it will go in left and right it will be level one so it is like the question we Sol before okay so how are we going to solve it is even or three okay we are going to use three order and then I can use recursion here okay so I'm going to make a recursive function DFS wait first I'm going to initialize I'm initialize in private okay private I am going to have a function called DFS it will be a recursive function and set it there will be two things uh level current and I can say something like of current value and trde of current and then um of current and we'll go there so I'm going to take and okay I'm going to I need to give it a base value because I'm using Deion so this value is like if I can say if level zero is not if that t that zero is not uh OD then it will return it and it will return fourth okay so our base is not okay need to store the values okay to store the values in an array store the values of each level in an ARR so declare then we will declare our function value okay so our base case will be if current is equal to then it will return true okay why because and M3 is part okay because an empty trade is even not it will return true then we will go so how we will do it is we will check that um now check okay now check the value at the OD level should be even okay so me Che the value at the OD level should be equal to our level is ided by 2 then what will happen it will return us FSE okay uh we will declare and level let call it so size can be anything okay here iore is large enough to store maximum size of any object it is used in uh C++ okay so we going toiz it for next step we need to resize the value or values val. the size our values size so okay now we need to check for increasing and decreasing okay so at even what should happen at even never value should be deing should be increasing at all level should be decreasing okay increasing means current is great than previous it means current value is less than previous value so how we are going to check it if our values at dep is not equal to zero and then at tab is divisible by 2 = means it is even and current well is thanal to dep is divisible by is not divisible by it will return and current Val is great than equal to or well for okay all the and left comma depth + comma depth + comma depth + what and H DFS current at right will be + curral current okay current and then current spee 10 for now
Even Odd Tree
find-all-the-lonely-nodes
A binary tree is named **Even-Odd** if it meets the following conditions: * The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc. * For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increasing** order (from left to right). * For every **odd-indexed** level, all nodes at the level have **even** integer values in **strictly decreasing** order (from left to right). Given the `root` of a binary tree, _return_ `true` _if the binary tree is **Even-Odd**, otherwise return_ `false`_._ **Example 1:** **Input:** root = \[1,10,4,3,null,7,9,12,8,6,null,null,2\] **Output:** true **Explanation:** The node values on each level are: Level 0: \[1\] Level 1: \[10,4\] Level 2: \[3,7,9\] Level 3: \[12,8,6,2\] Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd. **Example 2:** **Input:** root = \[5,4,2,3,3,7\] **Output:** false **Explanation:** The node values on each level are: Level 0: \[5\] Level 1: \[4,2\] Level 2: \[3,3,7\] Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd. **Example 3:** **Input:** root = \[5,9,1,3,5,7\] **Output:** false **Explanation:** Node values in the level 1 should be even integers. **Constraints:** * The number of nodes in the tree is in the range `[1, 105]`. * `1 <= Node.val <= 106`
Do a simple tree traversal, try to check if the current node is lonely or not. Node is lonely if at least one of the left/right pointers is null.
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
563,1005
989
If you have understood, then you want to try it yourself, see what is there, normally you do not have to do anything, this is the last value, just add this value completely inside it, okay, we will get it completely added. What will happen, I told him to see that the value of the last key is 34. Now there you will keep only single digital, so keep only single digital and then get the rest of the values ​​added on for the future, values ​​added on for the future, values ​​added on for the future, meaning instead of carrying, you will keep the entire value of Puri also. You can shift it, think a little about it and keep it as a carry, it is yours, okay, then a little bigger question will be easily asked on it, there is no question, okay, the one who is coming from the problem, what do you want to call the question? Look at the implementation about it, understand that he was just saying that here 1200 is given to him, it is okay, what should he do within this, he has to add on 34, he was just saying this question and what to do by donning it. Aayega said 1234 Will he come, is this our answer? Said Han, this is our answer, ok, but what was the biggest problem here, that no, van is given separately, you are given separately, zero is given separately and next. The zero is given separately. Okay, this is not a complete number, so you cannot perform your direct addition in it. Very good, very good, so now what will be the approach in it, meaning the story of approach is needed, this is the question, approach. There is no need to say, I mean, if I start from its last value, then in the last value, if I have added on 34 inside the zero, then what will come inside it, then I can get the entire red on said. 34 will come, is there any problem, said no, and in the last, Apna means one if there is Apna letter or one, if there is Apna number, then how many Apna can be there in it, 9 can be kept, is there any problem, said no, okay, if it is 34. So how much of it can be left? He said, it will be the last value and whatever it is, the entire carry will get burnt. Han, what did my friend say to all of us? This is the last value, whatever it is, it will remain, okay, there is no problem, then my friend. What did he say, he said, pick up whatever element of this next, he said, if it is zero, then back inside the zero, add on whom, now three is okay, so 3/1, what had whom, now three is okay, so 3/1, what had whom, now three is okay, so 3/1, what had come, the single digital element of It will come here, there is no problem, Van said and okay, let's understand it with another example, okay, there should be no problem in the concept, rest all are very edgy questions, like understand here, it is 274, okay, it is different. 74 Okay, now you have to add yourself inside it. Suppose 181 should not be a problem. Okay, so what can you do? He said, take the last digital one and add 181 inside it, meaning is it okay like this, get it done. If given then what will come? Said 1805 Is there any problem Said no Okay now only one letter can always come So which letter will come first Which one will come last Okay then here Which letter is fixed Last one If you get it done from 181 What was the whole red one? Said 5 And how much will it come here Another five And how much will it come here 2 3 Okay 455 Tell me this will come It is absolutely correct So now what do you say here Said the last one value van It was according to me, okay, then what did you say? Now Carrie, what's going on, she is 18, she is gone, 18 is okay, then what did I say, now it is 4 here, what did the second letter come, she said, 7 is okay, take 7. Got the seven switched on within 18. Said, what will come? On 17th, if you stay within 18, then 25 will come. No problem. Said, okay, take the last date, it is absolutely right, okay, what now? Said, you are done now, you are okay, it is 7 also, remove it, now take this letter, it means how much is it, adding on 2 within 2, how much is 4, okay four, there will be a single letter here. Was also left 4 A went okay 4 5 This was it, what did you say now this is it, that's it okay, first of all, initially from here, treat your last with the last, it is on, why do with the last, it is a normal thing, brother, Sam does it. I will do it last only, your blessings are there, okay then I started being last stepney tech, till what extent did I do till the first value, okay then what is the first date, okay, very good, then what did you say, what is there inside whatever is the last one ? Said add it on, ? Said add it on, ? Said add it on the cake, said ok, put the cake down inside it, then what did you say, now reduce one, decrease the cake, divide it by 10, see the meaning as if this was your 180, ok within 181. Apna had made 4, so within 181 Apna added on 4, did it come to 1805? Now what do you say, Apna said last value, Apna will give that, it is ok, we will replace the four with 5 and what do Apna say here? Only 18 should be left, it is absolutely right, only 18 should be taken. Han, so what are you doing? If you divide by, then what will come is 18. Okay, it is not a matter of , just keep doing this. is not a matter of , just keep doing this. is not a matter of , just keep doing this. Okay, tell me one thing, what is there in this? It happened that there was only 30 and 4, okay, you have added on all the values ​​of the cake, added on all the values ​​of the cake, added on all the values ​​of the cake, so it is 34, it will end only on two values ​​here, so it is 34, it will end only on two values ​​here, so it is 34, it will end only on two values ​​here, then it will be added on later, said, look here, understand what is here. What happened inside the zero is 34, okay, that's great, so your first came 34, so what did you do as the last value, so you signed it, okay, that's great, then what happened after that, you got your zero and three, okay, so this is it. It is still there, it has become what it has become, what has it become, still there, it is still there, it has become what it has become, what has it become, zero means ok, there will still be an addition, but it will have an addition, that means it will be zero, so it does not matter, so it is just the same, what will happen here? Like, whatever happens, if it releases zero, then there is no need for an edition, it is very good, then has your question been solved here, you had told only this in the implementation in the board, now here in the board, you and Where did they start fighting and said, okay look, understand what happened here, suggest that the name has Apna 12, is there any problem, there is 1 com, 2 and here what is Apna K is Apna, sorry, Apna Man. Take 1801 man, let's go, okay, so if Apna is 181 and here Na I Apna is 12, then what will be the answer, he said, let's check the answer, Apna answer will be within twelfth, so do 181 within you, okay 18 I gave money and got it done with the van, then how much did it cost, he said, it is 90, what happened to 19 that the 9 which will be replaced by the van, the work will be done, 19 will be replaced by the van, it is fine, it is very good, now after that, I will replace it with the van. There is nothing left in the future, there is nothing left in the future, but now the value here is left that it has not become zero yet, what it is worth has also not become zero. If the van is saved, then this van will have to be written here, right? But according to this code of ours, it is absolutely right not to do anything of our own, so we will have to do something, so what we said is that as long as this value is there, until this value is not zero. So, if your entire look is done and despite that, this value of yours has not yet become zero then what should I do at the time that this is this actor of ours, in this actor, keep on inserting further, meaning keep inserting in the beginning, what is this? What is the meaning of module off body after turning off the model? It is okay to break it once, so as if only the van was left here, then the van was directly pushed into it. It is okay, but if for supposing, there is something bigger than the van here. Number is left, meaning here 20 would have been left for supposalli or it would have become 25 was left, ok supposalli, then what happens here, first 5√3 came and then here you first 5√3 came and then here you first 5√3 came and then here you were broken, ok, no problem. It was ok, that's it, what will we do in the end, we will get it returned. Hey kids, you must have understood. Still, if you have any doubt, then unbox only submit. I have tried it is working very easily, its code is You will find it in the description box. Thank you.
Add to Array-Form of Integer
largest-component-size-by-common-factor
The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. **Example 1:** **Input:** num = \[1,2,0,0\], k = 34 **Output:** \[1,2,3,4\] **Explanation:** 1200 + 34 = 1234 **Example 2:** **Input:** num = \[2,7,4\], k = 181 **Output:** \[4,5,5\] **Explanation:** 274 + 181 = 455 **Example 3:** **Input:** num = \[2,1,5\], k = 806 **Output:** \[1,0,2,1\] **Explanation:** 215 + 806 = 1021 **Constraints:** * `1 <= num.length <= 104` * `0 <= num[i] <= 9` * `num` does not contain any leading zeros except for the zero itself. * `1 <= k <= 104`
null
Array,Math,Union Find
Hard
2276
1,637
hello and welcome to another video in this video we're going to be doing widest vertical area between two points containing no points and this problem you're given points that are X and Y points and you want to return the widest vertical area between two points such that no two points are inside the area vertical area is fixed with extending infinitely along the Y AIS and the widest vertical area is the one with maximum width know that the points on the edge of a vertical area are not included in the area so in this example these things are points here so we have a point at 74 we have a point at 87 97 and 9 and essentially basically what they're really asking so it's kind of an easy problem is what's the biggest distance between any two points horizontally essentally because the vertical area is going to be infinite and so really what they're asking is like what the biggest distance is so it's really so if you can draw like these little things that go all the way up uh infinitely and essenti you're asking basically what's the widest like distance here and so here it would be one because this is length one and notice that this like area the points can be on the edge of it the like it says points on the edge of it are not considered included in it so essentially if we just have a bunch of points like let's just draw a bunch of points like a point here Point here and so on basically it's kind of straightforward all your being asked is just go through your points and anytime you have a point just draw like a line like this right that covers sure we could probably actually use a line instead and let's make it wider so it's easier to see so let's do something like this sure anytime you have a point you have something like this there we go and where else do we have points right here and basically all you're being asked for is like what's the width for each one of these chunks what's the width here right what's the width of this and what's the width of this so in this example this would be let's take a look one two three four five six this would be three and this would be three that's kind of how you do it and so to actually break it down even easier let's say we have a bunch of points you're just going to want to sort them by x value so let's say we have some points like five or one six uh 210 220 like what whatever you want right and let's say last one is like 10 20 essentially all we really need to do is figure out what's the distance between these two points what's between these two points and that's going to be your area right so that's really all you have to do you don't really care about the Y values because notice if this point is anywhere on the y- axis like if point is anywhere on the y- axis like if point is anywhere on the y- axis like if this point instead of being up here was down here it would be the exact same thing cuz the Y goes up infinitely and really the question is just basically what's the farthest distance between any two points if you just sort them and so that's literally all we have to do so we're just going to sort our uh points by x value and then we're just going to compare every two adjacent X values and get the difference and just return the largest difference so I'd say this is kind of like an easy problem again but uh the hardest part of it honestly is like reading a description and figureing out what they want okay so we're going to sort our points and then we just basically have to check for every two points what's the distance we'll make a result equals zero and then we'll say like four ion range and we'll go up until length points minus one because we're going to compare every point to the point after it so we'll say result equals Max of result and points I + one remember the x value and points I + one remember the x value and points I + one remember the x value is zero the Y value is one so we'll say points I + 1 0 minus points i0 right so points I + 1 0 minus points i0 right so points I + 1 0 minus points i0 right so the point after the current one and the one itself and we can result okay so yeah once you understand like what this problem wants it's really easy um because you essentially don't care about your y-v value at all and care about your y-v value at all and care about your y-v value at all and it's basically just kind of like rewarded given an array of numbers find the longest distance between any two consecutive numbers right s array of numbers that's basically all you're being asked so yeah hopefully this is helpful pretty easy one and uh the time is going to be n log n and the space is going to be A1 so yeah not much to it hopefully this is helpful and if it was please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
Widest Vertical Area Between Two Points Containing No Points
string-compression-ii
Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._ A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the maximum width. Note that points **on the edge** of a vertical area **are not** considered included in the area. **Example 1:** ​ **Input:** points = \[\[8,7\],\[9,9\],\[7,4\],\[9,7\]\] **Output:** 1 **Explanation:** Both the red and the blue area are optimal. **Example 2:** **Input:** points = \[\[3,1\],\[9,0\],\[1,0\],\[1,4\],\[5,3\],\[8,8\]\] **Output:** 3 **Constraints:** * `n == points.length` * `2 <= n <= 105` * `points[i].length == 2` * `0 <= xi, yi <= 109`
Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range.
String,Dynamic Programming
Hard
null
9
all right we're recording let's welcome guys Nick white here so I do twitch in YouTube coding and tech stuff so if you want to check that out look in the description and you'll see it well I'm doing a leak code serious so I'm going through all of the problems on leak code and explaining them all this is the third one I'm doing number nine we're doing easier ones first this is called palindrome number if you guys don't know what a palindrome is it's basically like think of the word racecar same it's spelled the same way forwards backwards so we're doing that with numbers here we just did something like this in another video called the reversed integer so determine whether an integer is a palindrome when it reads the same way backward is forward well not too bad so first we can check do a base case and if X is equal to zero all we have to do is return true because palindrome zero is a pound rum zero is the same way forward as backwards then next we can check if zero if X is less than zero then it's negative so obviously it's not a palindrome because no negative number is going to be a palindrome or if X percent of ten is equal to zero then we're going to return false so sorry ok now we'll get to the meat and potatoes of this so you know we did the reverse in a jewelry reverse an integer so you might think well if we just reverse the integer and then we check if it's the same way backward is forward then it's obviously a palindrome right so that's an easy way to do it right so what we can do is yeah we have this and just like the reverse then video I recommend go checking that out I'll explain it again here though really quick so we can do this is what I want to explain is yeah you can reverse the entire integer and do a comparison at the end but it's smarter to just reverse half of the integer and compare the two halves that way you only have to iterate through half of the digits in the number so if you do X is greater than Ray J what's Lee code lead code is a great way for you to kind of study for algorithms and technical interviews so while X is greater than reversed int because we're gonna be incrementing reverse tent with all the digits we're gonna do int pop just like the last video and you don't is equal to X percent of 10 to get the last digit from the number then what we're gonna do is we're going to in any order we can do this but we'll just do it you know how we did it in the last video X divided by equals and divided by equals it means x equals x divided by 10 right to remove the last digit and then we'll just obviously increment this reversed int so you're gonna multiply by 10 and add pop for each iteration and that's going to reverse the integer until you get to the halfway point so this is what this is gonna work perfectly except for odd numbers so in the end like you have the reversed integer is half of the number reversed and then you have X is the first half of the number so they should be exactly the same so we can just do a comparison if FX is equal to reversed int then it's a palindrome right well you might think that but actually it's not because in an odd number there's gonna be this extra number so reversed int it's gonna iterate until reverse 10 is bigger so in a case where there's an odd number of digits so like 1 2 3 2 1 you know reverse 10th is gonna have 1 2 3 well you know X is just gonna have you know two digits reversed and we'll look 3 2 X 1 sub 2 digits we have to you know account for that case and to account for that case all we all have to do is you know or X is equal to reversed in 2/10 all right so if we run this in 2/10 all right so if we run this in 2/10 all right so if we run this should can I find symbol what's the spell reversed wrong or something sorry there it is yeah my bad there we go so I'll put it true expected true we'll submit the solution and my Wi-Fi is kind of bad the solution and my Wi-Fi is kind of bad the solution and my Wi-Fi is kind of bad and I noticed a bug in lis code where the Wi-Fi that runtimes depending on the Wi-Fi that runtimes depending on the Wi-Fi that runtimes depending on the Wi-Fi so this would change if my Wi-Fi so this would change if my Wi-Fi so this would change if my internet speed was faster which doesn't really make that much sense but see the solutions accepted so you know I hope you guys understand that it probably make a lot more sense if you go through the reverse and reverse a number problem I just did that right before this so it's pretty straightforward check it out easy algorithm a good one to know just know that using the remainder can get you the last digit of a number and dividing by ten can pop that last digit so that's how you really reverse an integer and for the palindromes you only have to do half and a half because you know if the first half is the same as the second half then it's obviously a palindrome and account for that last letter that might be stuck in the middle so you know pretty easy algorithm please subscribe follow me on Twitch or whatever and thank you guys for watching we're gonna do some more right now so see you guys in the next episode
Palindrome Number
palindrome-number
Given an integer `x`, return `true` _if_ `x` _is a_ _**palindrome**__, and_ `false` _otherwise_. **Example 1:** **Input:** x = 121 **Output:** true **Explanation:** 121 reads as 121 from left to right and from right to left. **Example 2:** **Input:** x = -121 **Output:** false **Explanation:** From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. **Example 3:** **Input:** x = 10 **Output:** false **Explanation:** Reads 01 from right to left. Therefore it is not a palindrome. **Constraints:** * `-231 <= x <= 231 - 1` **Follow up:** Could you solve it without converting the integer to a string?
Beware of overflow when you reverse the integer.
Math
Easy
234,1375
272
guys welcome to my channel virginia coder if you guys are new here i pretty much do the cube style questions and explain things in the summers what pops but today we have an amazing problem today so let's quickly go ahead and read the problem statement guys so the name of the problem is called closest binary tree value number two guys which means that there was a one before which i've already done in this channel so i highly suggest you guys go check that one out right it's gonna give you a lot of contacts right and kind of help you out i'm saying in a way i think this is a probably a follow-up follow-up follow-up to that previous question right so it's a very good question right so let's quickly go ahead and read the problem statement guys so he says given the root of a boundary tree right a target value so we're going to be giving a root a target value and an integer k right we return the k closest values and the bst right that are the closest to the target you may return enter in any order right so which is a very good thing it's a very good problem guys so since we're guaranteed to have only one unique of k values in the bst right i'm saying that are closest to the target right so she's pretty good so guys how can we solve yeah so uh how can we solve it guys so pretty much um let's go look at the example real quick so we had four so this is a binary search tree right and uh we're given a target of 3.71 all and uh we're given a target of 3.71 all and uh we're given a target of 3.71 all right k equals two so which means to return the two closest um values right in the binary search tree that are close that are closest to this target value that we're given right so this is yeah so the two closest one obviously uh looking at this rank is four right and then three right because i'm saying um yeah threes yeah and four oh the closest one right uh two is not club saying if there if k was equal to three right the three closest one it would have been four three and then five right those things would have been the top three integer transitions look at this one right we're giving one and the target zero and we want the closest value to zero right and the boundary tree is only one binary search tree there's only one in there right so one is the answer that gets returned right because i'm saying yeah so pretty much guys we can kind of um get it some kind of intuition right based on this guys so how can we solve it guys well i'm going to be copying this i'm going to be bringing it to the whiteboard so that you and i can uh brainstorm i'm saying so we can come up with the perfect algorithm right there let me also copy that but we can have the perfect thing that we want guys right so let's the how can we go about this guys what's going to be needed right so um so this is kind of similar to beyond right let's say you know i'm saying we that's tommy um traversed the whole tree right to pretty much find the closest one right so pretty much we had a instant rubric that was pretty much in helping us and keeping track of the closer so pretty much we go to revisit the nodes right as we're visiting guys we check does this node we calculate the distance right i'm saying of that node to the target value right let's say what i'm saying uh initially we're gonna i'm saying everything's gonna be like infinite away from what i'm saying and then now once we see this is the closer this is closest to uh the max right we mark this one as mark that node as the closest one right i'm saying and as we're traversing right now we keep doing that right calculate the distance of the target node to uh of the target value to of the and then that node that we're on right the value of that node area alright we calculate the distance if it ends up being closer than the previous closest one right we update that closest one to be uh of that node right this was the logic that we use and that other problem right so what kind of launch do we need but this problem got right so for this problem we're going to need a lot of logic right a lot of stuff so because now they want us to return the k closest ones right so pretty much k can be i'm saying it can be whatever it can be two three four five or it could be whatever guys right so we need to account for this right so it's not as simple as doing the other one right so maybe it is that simple right so let's kind of see how can we do it what's different now is the uh then the other problem the k thing right that's kind of uh it's kind of throwing us off right so it's not like we can have let's say you know because it has to be dynamic right so it sounds like we could say a cool um so k equals two then and we need to have two instance variable that pretty much keep tracks up the two closest ones right so i don't think that would work so it because k might be three k might be ten right we can't have 10 variables to keep track of all that's not efficient right so it has to be dynamic guys right so we need some kind of data structure to kind of help us in storing this collection of items right and only storing those k closest values right i'm saying so now a light bulb should be going off in your head guys when we kind of here we need a collection and keep the k closest be based on a certain dimension that i specify right okay um the thing that comes to mind guys obviously is i hate guys because we've done a lot of heat problems on this channel so i have a playlist on that so go check that out guys so the heap guys right it's going to help us in pretty much keeping the cable sorry so pretty much what we're going to have guys right pretty much um we want a max heat right because all the big numbers right i'm saying on the bigger numbers are pretty much going to be um all the big numbers right are pretty much going to be exit out for sure so the dimension that we're gonna do it right i'm saying that the heaps gonna be organizing itself anyway it's going to be if a node right i'm saying if a node oh it's gonna be based on the distance of that notice of the distance of that node's value to the target right so this is how pretty much uh it's going to be based on the dimension that i want the comparator that'll be specified right to organize the prioritize the node right so it's gonna be a priority queue guys and this is how our way to prioritize right based on the distance of that node value to there so pretty much we're gonna add the nodes value to some kind of heap right and then we could easily return that so pretty much this is uh exactly like the other problems that we've done right so that involves us to keep track of the k closest uh k largest k small strike k uh closest we've done many of them right so it's the same logic right because we already know that this uh thing that we're going to do right it's going to constant and lock k guys right i'm saying pretty much when i propose it to us right we need to traverse the whole a binary structure and as we're traversing guys we put every node's value to the heap right the heap is gonna be a size k guys so as soon as we go over the capacity right we're gonna need to remove um elements right so and at the top of the heap every time right it's gonna be the node right that's on the maximum that's the largest distance away from that um from that value from that number right so uh from the target value right so because that we could remove it and easily keep it our heap only of size k guys right so um yeah adding and remove is going to cost this lock okay right so that's why we have that guy right so see n lock k uh this is a pretty good efficient uh we can use also quick select guys which will give us a template i'm saying worst case is n squared but average case is a lot of n right so quick select could also be used to solve this problem if you want me to implement the quick select version of this problem let me know in the comment section and i'll gladly do it for you guys right so uh pretty much guys this is exactly what we're going to do guys we're going to traverse the boundary structure as we're traversing we add every node to the heap right and then our heap is going to pretty much organize itself uh pretty much um the criteria that the dimension that we're it the comparative i'm gonna have right it's gonna pretty much organize these things in terms of their distance from the target guide right so all the num all the numbers that are closer to the target right are always going to be like on the bottom chilling right and we have the thing at the top uh the thing at the top right that's the if it any other item needs to be removed right that's the item that will be removed uh as soon as possible i'm saying and just like if it was like a reverse logic right now let's say we wanted to the k uh furthest items right it would have been a mini heap uh right which means that um the closest ones would have been kicked out first right everybody would have yeah lodged right so let's quickly implement the um let's go ahead and implement the logic guys so fully get everybody to understand everything right so i know this problem can be a little bit confusing right so pretty much uh we decided that we're going to use keep guys right so let's uh have our um a data structure and all that we decided we all agreed on right so it's coming for rdq guys which is going to help us in doing the um all right the heat that we agreed upon right so integer right and then pq will be new for cue right all right and then yeah so we got our heap right so now we need to pretty much uh tell the um say um on which they mentioned that it should organize it all right i'm saying uh the damage that we're going to save you know right or custom comparator guys right i'm saying we set the comparator that's going to be so we're going to organize stuff based on their own distance from the target guys this is how we're gonna pretty much have it sorted out right so the sim card priority guys if you were to use and do another solution which involves sorting right pretty much at all of the values as some kind of array right and then sort the array the same comparator right you could use that in your um in that sorting method you could achieve that you could get an answer i'm saying that solution would be n log n right which is not too efficient this one's a little bit better because this is n lock k guy because of the heat guy we're keeping the heap of size k right so this is what i'm doing right there guys right so pretty much the integer uh pretty much we're gonna write my method right there finally then compare right okay so we're gonna take in so i need some space to work guys let's get some space all right once you watch space all right looks good all right so what we're going to do guys as parameters we're going to be passing in a and b ring i'm saying okay so for so now we need to calculate the distance for each of the ground of those two things that are being compared okay so distance a right so it's going to be pretty much um the absolute value right i'm saying of the distance where i'm saying so which could be a minus target right so i get the distance from for b as well right because that's important i need that right so it's b minus the target guy hopefully you guys are following that right so now we get we have to above other distances right so now we have something to compare them with right i'm saying so if right if the distance of a right is less than the distance of b then would return a one guys right don't say good case and then the other case if the distance of a right greater than the distance of beats okay they return negative one okay let's else we return a zero guys right so this is our custom paragraph i'm saying it's pretty much gonna help us right so yeah so that's where we're going to end up having a max heap guide right which is i'm saying all the nodes with the distance i'm saying uh that's far away from i'm saying so that all the closest uh items right i'm saying no values right it will be at the bottom every time right so every time we need to kick one of the nodes away right once we go for a certain size right that knows that's at the top right since it is a maxi break uh will pretty much be the furthest nude value that's away from the target right i'm saying so we don't worry about that number j we just kick it out right so we don't worry about that knowledge value right because we're storing values in the next example so guys uh we're going to have an output function we're going to pass in the root and we're going to pass it now for rdq okay all right and after we're done got the party the heap right should only have that right uh the k closest values right there are needed to return them so we're going to pretty much return that answer in an arraylist right so okay so public i will now return anything void helper okay so as parameters uh we're gonna take in the new three node which is with the groups and a req guys right i'm saying which is important i'm saying already req so if the root is normalized we already know what we're going to return and then it's going to return right there right no need to right so now uh what we're going to have to do we're going to do pq that add on the nodes value right let's see so now we do a check uh if the uh size of the heap right goes over the limit that's given to us right so that's why we also need to pass in k as a parameter right because we need that and uh if it goes certain then we do pq that poll we just remove that node right i mean that value right so and then after we do that guys we go to our left side because we need to right and then we go there we go also to our right side which is important right so we do all of that guys so i think just like that i think we're pretty good man um we wrote up wrote out the stuff right which is the uh custom comparator guys right actually and now we organize the element based on their distance from the target right which is i'm saying i'll make sure you guys understand that right so yeah so that's pretty much the gist of this problem right we organized the items so that it based on a certain criteria or a certain dimension or whatever right so let's think i think that we're fine right so let me see uh this is a double purpose this one always gets me all right ah double okay looks pretty good man all right so we uh let's check all the test cases guys awesome guys we were able to pass all the test cases guys so i want to thank you guys for taking the time to sort of watch this video guys if you guys found out make sure you give me a like if you guys are new here make sure to subscribe guys because i'll be doing a lot of other videos just like this one so thank you guys for watching and i'll see you guys in the next
Closest Binary Search Tree Value II
closest-binary-search-tree-value-ii
Given the `root` of a binary search tree, a `target` value, and an integer `k`, return _the_ `k` _values in the BST that are closest to the_ `target`. You may return the answer in **any order**. You are **guaranteed** to have only one unique set of `k` values in the BST that are closest to the `target`. **Example 1:** **Input:** root = \[4,2,5,1,3\], target = 3.714286, k = 2 **Output:** \[4,3\] **Example 2:** **Input:** root = \[1\], target = 0.000000, k = 1 **Output:** \[1\] **Constraints:** * The number of nodes in the tree is `n`. * `1 <= k <= n <= 104`. * `0 <= Node.val <= 109` * `-109 <= target <= 109` **Follow up:** Assume that the BST is balanced. Could you solve it in less than `O(n)` runtime (where `n = total nodes`)?
Consider implement these two helper functions: getPredecessor(N), which returns the next smaller node to N. getSuccessor(N), which returns the next larger node to N. Try to assume that each node has a parent pointer, it makes the problem much easier. Without parent pointer we just need to keep track of the path from the root to the current node using a stack. You would need two stacks to track the path in finding predecessor and successor node separately.
Two Pointers,Stack,Tree,Depth-First Search,Binary Search Tree,Heap (Priority Queue),Binary Tree
Hard
94,270
113
Hi gas welcome and welcome back to my channel so today our problem is Parth Sam you so what have you given us in this problem statement here you have given us a bounded tree okay and what we have to do is we have to find from the root. Where are the parts from the beginning till the leave notes, what is your target, the sum of all the notes between the root and the leaf notes is your target. Okay, here we have given you the targets and so if you get that path. You will store the value of all the notes in that path in a vector and you will insert all the parts of all the notes you have received so far in one vector and finally what will you do with it by turning it, okay? So this is your problem, let us first understand through the example whether the problem is exactly ours, then we will see how we can solve it. Okay, so look, we have taken the first example here, what have we given in it, we have given you a binary. And one is your target. What we have to do is to look at the SAM of the SAM note from the root note to the lift note. Then we have to see whether that SAM which is your target is equal to the SAM. If it is equal to the targets then it is called path. So what will we do, we will insert a van de vector meat and store it in it, you can have any value, then what will we do with this van de vector, we will keep storing it in a final tutive, then as close as we get, we will get it here finally. What will you do, you will return it, see, here is one thing, this is the second part, what has been done to these two parts, one, you have been inserted in the director, right, so we will see how to solve this problem, see, let us take care of this thing. We have to keep that we have target Sam, which is our note, here it is possible that you have a target in the middle, so now will you consider it or not? You have to come from the root till the live note, you have to see the Sam in between. If our target is equal then we will consider it, we will not respect it, then for this we will have to come till the lift, otherwise what will we do, we will come here till the lift, ok till we reach the lip, I will give you whatever note you get on Monday. We will insert it in the factor and see, we will also take a variable in which we will keep doing sum and see whether it is equal to the targets and if it is, then you will also insert it in the vector which we had prepared vandivector, okay do it like this. If we find all the parts, then what will we do here? We will do the same with DFS because we have to come to the depth, we have to come to our lift, so we will start from here, okay, start here, we will take a variable with a name here Sam. It will start from zero and what do we do, we will start then insert this pipe here and also insert 11 here, then we will come towards its left, then what will we do with seven, we will insert it here and add 7 and Here we will insert seven, then we will see what is the left side and right side of this note, what is null, date mains, what is yours, leaf mode, then SAM, then we will see whether your SAM, which is the target SAM, is equal to the target SAM. Five four nine 11 20 plus 7 if it becomes 27 then are your targets equal to them or not then what will we do when we go back ok we will see out if possible when we go back then we will remove 7 from here and here Also, we will remove 7 from it. Okay, then what will we do? We will go here to the right of this. If we go to the right of this, then this is the note, Han, this is the leaf node, so the targets, let's see what Sam is there yet, is that the targets and k? Is it equal? 5.99 11 20 + 22 Okay, if the target is 5.99 11 20 + 22 Okay, if the target is 5.99 11 20 + 22 Okay, if the target is equal to the target, then what will we do? This is the vector that has been stored here, all the elements that have been stoned in it, what will we do with it, if you store it directly. What will happen to you here, I will write it down here From here we will remove you, we will remove this too, okay this is my left and right, I have seen both, he will come back, so this is also 11, this will be 11 Okay, this is gone, after that we will look at its left side, this is a tap, so there is no need to look, then there is four, we will have to come back from 4, then four will have to happen, this phone will also have to be removed, okay. Now this five has seen its left side, it will look towards its right side, then when it goes towards its right, it will look towards its left, first it will go towards its left, then it will go towards the left, along with it, what do you have to do, here the pluses come. You have to do the same, okay, you must be coming at 13, so you will add 13 here, okay and add 13 here too, you will do 39, then you will see if your sam is there, why will we see because we are on the leaf note, right now its left right. If the left side and right side are null then till here we will see five coming 1330 36 Is it equal to our targets and if not then what will we do from here we will back track it, remove it from here, so we have left side. See, now we will look at its right side plus four, here we will make plus four and here too we will put four inside. Okay, then we will look at this side here, we will look at the side here, we will do plus five, insert five here also. Do it, then now you will see because it has taps on both its left hand and right hand, so you will see the sum of 58 134 175 22, so this is your target, so whatever you have inserted here, people will just insert it here, what will happen? Your 5 will go to 840. Okay, then now you have seen its four on your left, now you will look on its right, you will see on the right, van is 1 +, you see on the right, van is 1 +, you see on the right, van is 1 +, you will do 1 inch here, then when you do 1 inside, here you will see that you do this. Take note because both its left and right children are null, so till here we will see the oath, 58 + 4 and plus one, so we will see the oath, 58 + 4 and plus one, so we will see the oath, 58 + 4 and plus one, so what will happen to you, if it becomes 18, then it will become 18, which is not your target, so it is okay, we will keep back tracking - These mines, sorry, will keep back tracking - These mines, sorry, will keep back tracking - These mines, sorry, mines team will give it this four, if it goes from here, if it goes back from four, then four will also go, this is four, if it goes back from 8, then eight will also go, and let's see from here. Okay, in this, the root node is provided by you. Targets end has been provided. Okay, here we have taken one of these SAMs from zero and zero SAM has been taken as our own. So what will we do with it? We will insert it here i.e. we will insert such parameters in this and that. Okay, i.e. we will insert such parameters in this and that. Okay, i.e. we will insert such parameters in this and that. Okay, DFS function is your root target SAM and Sam, we have given three parameters here, now let's look at the de function, what we have done here is also taken two vectors, one is the factor in which we are going to store the answer, in which we are going to store the path means a single path, okay. So the first thing you have to do is the route your tap? If it is tap then you return it. Okay, you adervise the path which the van gives you. You talk something about the value of the route and in everything also the value of the route. Add it, okay, so here we will put it in the condition, if it is done, then is the note on which we have come, is it our leaf note, will we check for it, is it the left child of whatever note is in the root? Are both nulls present? If so, what will we do? We will insert the answer factory. Okay, then we will call it on the left side and we will call it on the right side. Okay, what will we do when we are checking back? So what will we do this time? Pop back your which you are removing the element from the path so look at the punch you are removing the element here look at your look here and if you have done that then what you have to do is you have to remove this from Sam also from here The value of the root because why you have to do this is reading because what M percent means here is that Sam has taken his variable, what is he doing, the diode is going to its address and adding it, okay whatever value. The thing is happening directly in its memory and getting changed, so what do you have to do when you have to go back from here to here and come from here to here, then your Sammi, you have to remove the 7 that you had added. Do we even need the value of 1? After 11, we removed 11, then we did that with 2, we did that with seven, what if we didn't do that, then we will remove seven from here, okay when we go back from tu also, you If we remove the value of from here, then what happens in send on Here, when you come back to this function, you call this question number from here, this question number ends, now when you come back to this function, it does not end, its value does not end, okay, if this is a local value variable, then the local variable. In this case, what happens is that with the end of calling the function, the value that has changed also gets lost. Okay, but this is your difference, so you can return to the function that you have called to use it. If it ends then what is its value in case that we have done 7 by going to this address, will it be a channel or not, will it not be that thing, you will have to change it. Okay, so when we will be sending it on M, then we will have this He will have to do the mines case but if we do this simple thing then we will not need it. We will not need it. Even if you do it will not make any difference. If you do it then it will not make any difference. Why? You will not have to, let me tell you, see what happens in the case of local variable, when you are calling here, when you are calling this, then you are adding its value to everything, whatever is the value till now. It happens that even after seeing what you are doing here, you are inserting this Sam here and sending it, okay then if you are looking for this intake, then you are adding the value of intake to everything, okay. You are adding it to the se, then you check whether the target is there or not, but then this function of yours is getting finished, then what will happen in case the function calling which you had done for this is finished, then its At the same time, the value that will come back to him, the value that will be in it will be up to this extent, okay, it will be up to this extent, whether you do it with calling or not, it does not matter, he says, I already have it till this much. The value of is fine, you minise it there, do plus it, do multiplication, nothing is going to be affected there, it is fine because that which was yours, even Sam's, it had ended there, okay, I have only this much. So in this case we do n't do that. Okay I hope you have understood. If you liked the video then please like, share and subscribe. Thank you.
Path Sum II
path-sum-ii
Given the `root` of a binary tree and an integer `targetSum`, return _all **root-to-leaf** paths where the sum of the node values in the path equals_ `targetSum`_. Each path should be returned as a list of the node **values**, not node references_. A **root-to-leaf** path is a path starting from the root and ending at any leaf node. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22 **Output:** \[\[5,4,11,2\],\[5,8,4,5\]\] **Explanation:** There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 **Example 2:** **Input:** root = \[1,2,3\], targetSum = 5 **Output:** \[\] **Example 3:** **Input:** root = \[1,2\], targetSum = 0 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-1000 <= Node.val <= 1000` * `-1000 <= targetSum <= 1000`
null
Backtracking,Tree,Depth-First Search,Binary Tree
Medium
112,257,437,666,2217
205
See, in this video we are going to do a question on isomorphic strings. The question is saying that you will be given two things. You have to determine whether it is isomorphic or not. Now what is the meaning of isomorphic? It is saying that is the occurrence of a character. Replaced with Andar character will be present in the order of characters like the next one is in front of me then I can replace any one letter with a particular letter, ok then all the A's that come I will replace them with this particular letter like here If Egg is written on it, then I can replace A with A. Okay, so now whatever A is, it has been mapped to A. You understand that at night, in this way, I can replace G with G. Bye di, now whenever. Next in the string, if 'G' Bye di, now whenever. Next in the string, if 'G' Bye di, now whenever. Next in the string, if 'G' comes, I will always replace it with 'D' comes, I will always replace it with 'D' comes, I will always replace it with 'D' and if you also come 'G', then I and if you also come 'G', then I and if you also come 'G', then I can replace it with 'D', do you understand? Okay, can replace it with 'D', do you understand? Okay, can replace it with 'D', do you understand? Okay, now I will see this example and one more time, okay, you will see, 'F' is ok, no problem. okay, you will see, 'F' is ok, no problem. okay, you will see, 'F' is ok, no problem. No problem, I can replace F with B, F I can replace B with B, no problem. Okay, here comes O again, I can replace O with A, no problem, O, I can replace A with A again. Now, if O comes again, I will replace it with A. Okay, there is no problem, so whatever is Fu, what will it become, it will become Ba A, but what did we want, we wanted 12, do you understand? It means that there should be one to one mapping, okay, it is a simple story, if F is mapped to B, then F will remain with B, okay, now F will be replaced by B in the next string, similarly. Here, when will you replace O with A? Now it is okay for the next O, you will replace O with A only, but here you should have R. Do you understand that this is the story? Now let's see the paper and title, I can replace the third P with P. Here you will see that P is also being replaced by T. It is fine in 121. A is fine with I, there is no problem with A. L is fine, there is no problem with R. It is fine, that is, three mappings are being made here. And saree is unique, there is 121 mapping, it means this can also be true, so let's start, let's see what we will do, let's take a map of the direct character, let's take a map of it, what will we do in it, we will run a loop in the sting and one by one. Look at what we will do on the map, we will put it on the map that brother A has been mapped, G has been mapped with A, we will keep it with G like this, it is okay, let's do 4 and i = 0 i &lt; s dot is okay, let's do 4 and i = 0 i &lt; s dot is okay, let's do 4 and i = 0 i &lt; s dot length will be written here. If the key is equal to both in the constant then there is no need to check it because if the length of both was different then obviously I SO MORE will not be fixed. Okay, so I will reduce one, I already have one character in the name which is Will say brother, what character is lying in S on the current index? Similarly, what we do is look in T, what character is lying on the current index and call it T, okay, I know, we will give what T is, okay brother, which is A. It has been mapped to A, it is fine, there is no problem, it will go, then we will come again. It has been mapped to D, it is fine, it will go in the second loop and then it will come again. Yes, if it had come earlier, we will have to impose some conditions that brother, yes brother. If you look at it then listen carefully if something else happens instead of 'pe' here, you listen carefully if something else happens instead of 'pe' here, you listen carefully if something else happens instead of 'pe' here, you understand, the first time the loop was run, there is no problem, it got lost in the map, the second time it was added to the map, then it is ok, then you will see for the third time. Yes, yes, we have already seen it. So we will check if it already exists in the map. Okay, listen carefully. If this current character already exists in the map, then what should be its value. Tell me its value at this time. Tell me its value. What should it be? The value of G is already written in the map. Do you understand? Look carefully, we have entered it in the map. Is it here? I am now you are G. It is okay, now the current iteration is here. So what should be the condition, our conditioning honey. It should be equal to the value of this lamp which is kept in front of this lamp. It should be equal to the value of the lamp which is lying in the already existing map because one and one mapping has been done, always through lamp only. If it is replaced, then obviously D should be kept here in front of G. The example will see, I have also placed it in front of F. I write here, I have placed it in front of F also, I am okay and that means I have placed it in the map. Okay, I have placed it in front of the map, it is okay, then we will see again, Okay, here R is placed in front, but I had written earlier that brother, okay, A is in front, so that is what I am talking about, that is why I am worried about you. We will check that if the current character already exists in the map, the current one is fine and we will also check if the current character exists in the map and its value which is A, where it is kept in the map. It is not equal to I am noting it from the gate, it is equal, what is it, if it is so, then burn the return, it is okay, now let's see by running it, let's run it will be run, but there is still something missing in it and I will tell you this. So okay here it will be run, there will be no problem, there is a problem of content, obviously here you will have to return true, if the return is not true, then make the return true, accept ok, but what will still happen, it will not be submitted, I will tell you. Tell me, what issue will come, how to write a test here, reduce it, write a test here, then one will see how to write one's test, A B C is correct and T has to be written A B, see wrong A, we have given true. It has been returned, it was expected, that is, our logic has gone wrong, how will we see what we have done, if A is mapped to A, then we have added A in the map, then it is ok, then the mapping of B to B will be ok in the map. Then he did not get C in the map, he will get C in the map, so this is return first, never understood the matter, but we know that it is visible here that A was already mapped, this was mapped from A itself. If you understand then what condition should be imposed? Look at the condition. We will impose it here if the current character in S is ok, the current character in S is this note in map this is note in map but which is the current value in T is ok whatever is the current value is that is map. I understand that you are sleeping, you will look carefully, if C is not in the map, it is okay and A is lying in the map, where is it lying in Waluj, please post the map, okay, I will tell you by putting the bracket here or So is this condition or else this condition? Is this condition not in the map? Our current character is not in the map but it is in the set that comes by doing map.values. It has the set that comes by doing map.values. It has the set that comes by doing map.values. It has the content. What comes from map.values? What comes from map.values? Is our set comes from map.values? What comes from map.values? Is our set comes from map.values? What comes from map.values? Is our set containing values ​​correct, are the containing values ​​correct, are the containing values ​​correct, are the contents correct in it, that is, what is the meaning of this, that is, what is A, this has already been mapped, it is better than any other character, if it has been done with the character, now then the current Jo In the current iteration, there is a character in 'S', Jo In the current iteration, there is a character in 'S', Jo In the current iteration, there is a character in 'S', why is it not there in the map? Are you understanding everything? Okay, brother, let's try this time. This time the ABC test of that test has been accepted. I have tried everything. Okay, let's talk about time complexity, let's talk about space first. Let's talk about space complexity. Big off and space complexity is okay, it won't even be N, it will be as many as there are ask characters. Okay, it's not unlimited as many as you want. If it is of 1 crore length, then there will be no power map of 1 crore length. The number of valid ask characters is the same, it is very good. Talking about time complexity, a loop has been placed in front and nothing else has been done, content gate etc., all this is just off content gate etc., all this is just off content gate etc., all this is just off one. It gets done in time, okay, now see, we can use another approach here because we know that we have limited characters in front of us, okay, obviously okay, so we can use count here, will count. We can use it here, let's do it, now for this you should know what I was asking you that how many characters can be different, our Aashiqui is okay, so the total number of characters in the table near us is that. There are 256, that is, 256 different characters can be used here, okay so I am two inches long, look carefully, I am two inches long. T is the name of S, it is fine, it is very good, but we take it like this, we call it 'cent', it is okay, a little will call it 'cent', it is okay, a little will call it 'cent', it is okay, a little will remain like this, and we say 's', okay, let's go and we remain like this, and we say 's', okay, let's go and we remain like this, and we say 's', okay, let's go and we fill it in minus one, now zero is lying, why are we doing only -1? Because -1 why are we doing only -1? Because -1 why are we doing only -1? Because -1 No one has a love interest Hey this dot fool st com -1 Hey this dot fool T S now fool st com -1 Hey this dot fool T S now fool st com -1 Hey this dot fool T S now see what I am doing now brother I will see what I am doing here S you in T what will I put in T you S in What will I put now, like Maa Li, here I will put these keys, how will I put it, everything will be clear, okay, a simple loop has come, let me see what I want to do, let me see, we have made the characters like this NTT, okay, S, it is equal, you are S Now look carefully, this means that two of our length is 256 and here the mapping is kept, what is written in cent, instead of A, mother, what do you see, mother did 256 length, in place of A, it is written G. The place is written like this, now what does A mean, hey, why would A's ask come out first? He must have fallen in love with his lover, must A have read this a little, his today too will be big. Do you understand the point? If it is 103, then 103 out of 80 must have been on the index. In my understanding, our word will become cent like this and similarly it will become ts. Okay brother, A has come, we have given pulses. In that, G has come, we have given pulses and similarly, reverse weight has been given. I am doing it, so now I go again, so let's reduce one, let's put a NOT condition here, let's put a condition IF ST-SS-S Equal put a condition IF ST-SS-S Equal put a condition IF ST-SS-S Equal-1 Not Equal Two Mins Not Equal Two Equal-1 Not Equal Two Mins Not Equal Two Equal-1 Not Equal Two Mins One Else Not Are you understanding equal tu mines i.e. if A is not mapped to anyone, it is i.e. if A is not mapped to anyone, it is i.e. if A is not mapped to anyone, it is Rakhi i.e. A has Rakhi i.e. A has Rakhi i.e. A has not been mapped to anyone, till now only one has been mapped to anyone, so far it is okay, so we will update this. But see here, now if I have two Rakhi of G then this condition will become Jal, so here I have to write Ls condition and Lc also see what will I write with L. If you see in this example it will be seen that we have put O in place of F. In place of 'A' we added 'A' and in the opposite direction we have put O in place of F. In place of 'A' we added 'A' and in the opposite direction we have put O in place of F. In place of 'A' we added 'A' and in the opposite direction we added 'B' instead of 'B' Ok we added 'B' instead of 'B' Ok we added 'B' instead of 'B' Ok we added 'B' at the same place 'O ok now he is already added 'B' at the same place 'O ok now he is already added 'B' at the same place 'O ok now he is already agreeing ok we will check this ok 'O I have something lying around' ok 'O I have something lying around' ok 'O I have something lying around' Okay, but there is nothing in R, so we will not run this block. Okay, so let's check one simple thing, we have seen this in the first time, instead of brother O. If there is something lying, it is okay, but if there is nothing lying in place of R, then color matching puts color matching condition here, ST SS S is not equal to t or S t is not equal to tu, so return first. I told the thing that if there is wrong mapping then burn return. If return is never burnt then burn return. Let's see it going. I have made a mistake here once, it won't give, so what have I done to the blender, it will be equal or not if first. For this, if there is no measurement then do the mapping, now I have tried it is accepted, I am submitting, okay, now you will see, here the time complexity is of N, the length of our string will be and space complexity is like the previous algorithm, here also the space is constant. It is okay, you can say because of one, just say so, we did not do anything here, we two took the arrangement, first of all I checked whether there is no mapping of either of them, okay, we checked whether of the two There is no mapping of any one, if it is not there then do it, I have done it is ok, but if there is mapping of any one, like here there is O and there is R, then check this condition, then what to check if it is not mapped to R. Or if there is no R map then return first, then I have finished the video, you will get the link of the next video
Isomorphic Strings
isomorphic-strings
Given two strings `s` and `t`, _determine if they are isomorphic_. Two strings `s` and `t` are isomorphic if the characters in `s` can be replaced to get `t`. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. **Example 1:** **Input:** s = "egg", t = "add" **Output:** true **Example 2:** **Input:** s = "foo", t = "bar" **Output:** false **Example 3:** **Input:** s = "paper", t = "title" **Output:** true **Constraints:** * `1 <= s.length <= 5 * 104` * `t.length == s.length` * `s` and `t` consist of any valid ascii character.
null
Hash Table,String
Easy
290