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
1,545
hi guys so today we are going to do the question uh find the kth bit in the net binary string right so given two positive integers n and k the binary string s of n is formed as follows initially s of 1 is equal to 0 like a 0 string and then s of i each successive string is made of s of i minus 1 that is the previous string plus we add 1 and then reverse uh on inverting we reverse the s of i minus 1 at string so we look at it what this has to say to us where plus denotes the concatenation operation reverse of x results returns the reversed string x and invert of x inverts all the bits in x zero changes to one and one changes to zero so we are given this um like the sample cases how we have to build each successive string and we look at how this is being done so and what the question actually has to say is return the kth bit in s of n it is guaranteed that k is valid in the given n so let's look at the pattern so initially s of one is given as zero string right and then what we have to do is after uh like s of two will be s of one plus we'll insert one extra and then what we would do is like invert s of i minus 1 so inverting 0 means all 0s are converted to 1 and ones are converted to 0 right so it has a 0 in it so we'll do we'll invert that character and then what we have to do is reverse this right so reversing one will again create one here so what would be the string s of zero is zero plus 1 and 1 so this is the s of 2 that we will produce right and then s of 3 will similarly be s of 2 plus we will add up 1 at the end of s of 2 and then what we will do is first invert s of 2 and then reverse it right so inverting s of 2 would mean each 0 is converted to a 1 and each one is converted to a zero right so this is the inverted string and i'm reversing means that the zeroth bit becomes the last bit and like uh first and the last bit are reversed are swapped and then the second and the second last bit are swag similarly this split remains the same uh so after reversing it becomes zero one so here we can write this and initially s of 2 is 0 1 and we'll add of 1 and then 0 1 so the string becomes this which is equal to 0 1 and then 0 1 right so this is a string that is s 2 s 3 right and similarly we will continue this process and number of times with n number of um k number of n number of times and then we will have to find the kth bit for example the second bit and s of 3 will be um z so the second bit will be one and two so the second bit will be one right so if we use the zero indexing then it will be um like s of k minus 1 bit is what we have to return so let's start with the coding part so basically what we are given is n and k so we'll initially take the first string as zero because it is what we are given with and then we will take a temporary string temp and ah another string s so we will have to hydrate n number of times because we have to find the nth string what it is right and then what we are doing here is uh we are basically uh so actually what we need to do is we need to have an unmodified string as well as we need to have a temporary string like uh what we are doing is like uh suppose s of 2 is 0 1 right so in the manipulation that we have to do we need to invert it so we will make a temporary copy to the string as temp and then update the string like we need to first reverse it right so we have a inbuilt stl function for reversing a string that will be reverse and then we'll pass in the temporary string from starting to end right so uh let's see what we're doing here uh so basically temp equal to s this is the string that is formed in the uh last step right so this was the first step so uh f at temp equal to f and then we reverse the string right so what happens to this string is uh it becomes 1 0 right and then we'll iterate over this string 10 so because we need to invert the string so basically we are manipulating the values in the string and so we are passing this ampersand sign if we do not pass this ampersand line then the updates are not permanent right so care ampersand c of temp we are basically iterating each character right so the string is one zero so we take the first character we check if it is one we convert it to zero and then we again iterate to the next element that is one so it is one so we update it to 0 again since it is 0 we will update it to 1 so this is what the for loop is doing if c is equal to character 0 not 0 it has to be character 0 then we update it to character 1 else character equal to 0 and then what we do is now since we are forming the nh string like whatever string it is so what we are doing is s of n minus 1 that is the original string s of n minus 1 was the string in the previous iteration right then we are adding a 1 concatenating 1 to it and then we are adding the temporary that is the manipulated string temp string is basically inverted plus reversed string so here we get the string in the in this iteration and after n iterations are done we need to return the kth string uh kth character so we return it and on submitting we will get a correct answer for this code so talking about the time complexity we can see that we are doing n iterations and for each iteration we are basically alternating over the string once right so we are talking of a time complexity in uh n and there are n iterations and each time we are iterating over the length of the newly formed string so this will be the time complexity i hope everyone is clear with the approach and the code is this so bye guys
Find Kth Bit in Nth Binary String
form-largest-integer-with-digits-that-add-up-to-target
Given two positive integers `n` and `k`, the binary string `Sn` is formed as follows: * `S1 = "0 "` * `Si = Si - 1 + "1 " + reverse(invert(Si - 1))` for `i > 1` Where `+` denotes the concatenation operation, `reverse(x)` returns the reversed string `x`, and `invert(x)` inverts all the bits in `x` (`0` changes to `1` and `1` changes to `0`). For example, the first four strings in the above sequence are: * `S1 = "0 "` * `S2 = "0**1**1 "` * `S3 = "011**1**001 "` * `S4 = "0111001**1**0110001 "` Return _the_ `kth` _bit_ _in_ `Sn`. It is guaranteed that `k` is valid for the given `n`. **Example 1:** **Input:** n = 3, k = 1 **Output:** "0 " **Explanation:** S3 is "**0**111001 ". The 1st bit is "0 ". **Example 2:** **Input:** n = 4, k = 11 **Output:** "1 " **Explanation:** S4 is "0111001101**1**0001 ". The 11th bit is "1 ". **Constraints:** * `1 <= n <= 20` * `1 <= k <= 2n - 1`
Use dynamic programming to find the maximum digits to paint given a total cost. Build the largest number possible using this DP table.
Array,Dynamic Programming
Hard
null
111
hey guys welcome back to another video and today we're going to be solving the lee code question minimum depth of a binary tree all right so we're going to be given a binary tree and we want to find its minimum depth the minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node and a leaf node is basically a node which does not have any children so it's left child and its right child both have a value of none so for example 9 15 and 7 are all children notes but whatever year is going to be our answer so the question again is the minimum depth so between 9 15 and 7 we can get to the number nine the fastest and in other words the number of nodes we have to go past in order to get to nine is one over here so the root node itself and then this over here is gonna be the second one so we end up outputting two another way to look at this is we can just find out what the current depth we're on is at so we're going to consider this as one and then this over here is at a depth of two so we're going to end up outputting two okay so that should be for our question and we have this one as well so let's just uh see how this looks like as well so as you can see for this tree over here so two common null comma a three common null and you can see the rest so in this tree what's happening is that we have everything which is the right child of its parent node so in this case what exactly are the three nodes we only have one tree node which is the number six and what we want to return is how many nodes do we have to get through to get that number so in this case it's gonna be one two three four five so our answer should be five solutions look up and the answer is five so i'll just go through two different methods of how we can solve this one of them it's a breadth first search and the other is a depth first search so let's see how both of them look like and yeah all right so let's say we're given the exact same tree over here and i'll go with the breadth first search first because i think that's a lot easier to understand so over here we're going to be using a cue and i'll just be using the last list to represent it and the first thing that we're going to have in our queue is going to be the root note which in this case is three so we're going to have the root node over here and along with that what we're going to be having or storing is going to be the current depth that we're at so we're going to start off with the depth of one and the reason we're calculating the depth is because that way it's going to be easier to return the number of nodes it takes in order to actually reach a leaf node so we're going to go over here and what we're going to do is we're going to pop out the zeroth element so in this case we're going to pop this out and so currently we're at the node 3 and we have a depth of one so what we're going to do here is we're going to check does it have a left child so it does have a left child with 9. so over here what we're going to do is we're going to add this to our q so we're going to add 9 comma and whatever year is going to be the depth so depth actually increases by 1. so we're going to do one plus one which is two now simultaneously one more thing that we're going to do is we're going to check if it has a right child and it does have a right child so that's 20 and in this case we're going to add that as well so we're going to add 20 and its depth is also 2. so in this case currently we popped it out so this does not exist anymore so we're done with one iteration now we go on to the next value so now we pop out whatever is at the zeroth index which in this case is nine comma two so when you pop out nine comma two you're gonna get the node as nine so which is this one and the depth is two but one thing that we wanna notice here is does it have a left child it does not and it also does not have a right child so in that case when we do not have a left child and a right child that means that we are at a leaf node currently so in that case when we're in such a position like we are right now we're directly just going to return the depth so in this case we're directly since uh nine does not have any children we're just uh going to return the depth which in this case is two so that's how a breadth first search looks like and we're going to keep going until we either until we reach the first leaf node all right so now let's look at a depth first search so dfs and how this is going to work is we're basically going to split down our tree into smaller sub trees per se so what we're going to do is a simple logic how it works is we're first going to look at the entire left side of the tree compared to the root so the root is 3 and we're going to look to everything on the left of it and simultaneously we're going to look at everything to the right of it so we can kind of divide it into two different subtrees so we have nine and then we have one more subtree over here consisting of 20 15 and seven and each time we go down one of these sub trees we're going to be increasing our depth value right so in this case what we're going to do our left subtree cannot be divided furthermore so in that case actually what's going to happen is we're just going to end up returning this value so let's just say it just kept going on so for example let's say we have 20 15 and 7. so what we're going to do over here is we're going to split this further more so this 20 15 7 is one subtree and we're going to split it further more into a smaller sub tree which in this case would just be 15 and seven now by doing that we're actually going to end up reaching all of the leaves and now the question is which leaf do we reach first and the first leaf that we're actually going to end up reaching is going to be nine and that is going to have the minimum value in terms of the number of nodes it takes to get to it so in this case that's what we're going to output which is the number nine sorry which is the number two since that's how that's the depth of it and uh if dfs doesn't really make too much sense i think it should be easier to understand once we write the code for it all right so i'm gonna start off with the breadth first search solution and how this is going to look like is the first thing we're going to check for is we're going to check if we even have a binary tree so if the tree is empty so if not root it has a value of none in that case we can just directly return zero and that makes it a lot easier for us so after this we're going to over here we're going to actually establish our cue so we could use a inbuilt list from python but instead we're going to use the cue from collection so collections.dq cue from collection so collections.dq cue from collection so collections.dq okay and the reason that we're using this is because it has faster lookup times compared to a list okay so now we want to add the root node to this uh queue over here so to do that we're just going to do q dot append and the value that we're going to be adding is going to be a tuple and it's going to have the root and the depth that we're on and the depth that we're starting off at is going to be 1. okay so now that we have this we're going to go inside of this while loop and we're going to stay inside of it until everything in q is popped or unless we actually return something inside of it so now that we're inside of this we're going to pop out whatever is at the zero index so to do that using the dq we can just do top left and that is going to get whatever is at the zero index okay so now that we have this we actually want to get it into its two values so we have the node and the second value was the depth and that's going to be equal to q dot pop left alright so now that we have these values we're going to check whether a left and right node exist so if not node.left so in this case it so if not node.left so in this case it so if not node.left so in this case it does not have a left node and not node.right so in this left node and not node.right so in this left node and not node.right so in this case it also does not have a right node and in that case we can just directly return the depth and that means that we reach to an ending and we're done right so that's what we're going to do now if that's not the case we have two conditions we might have a left node so if no dot left in that case we want to add that to our queue so q dot append and we're going to be appending a tuple again and the root node over here is going to be node dot left and the depth is going to increase by 1. so to do that we can just do depth plus one perfect and now we're gonna do the same thing except we're gonna check for the right so if node.right and in this case if so if node.right and in this case if so if node.right and in this case if that exists we're gonna add it to our queue again and it's gonna be two full values of node.right node.right node.right comma and the depth increases by one again all right so that should really be it so if you submit this our submission should get accepted so our submission was accepted and now let's look at the dfs all right so in our dfs uh solution over here we're going to be calling our min depth function over here recursively so let's start off by laying down the few base rules so first what we're going to check is what if we have a null value same as before so if not root and in that case what we're going to do is we're just directly going to return zero okay so we have this and now we have one condition where we're at a child so when we're at a child it means that we do not have root.left we do not have root.left we do not have root.left and we also do not have root.right so in and we also do not have root.right so in and we also do not have root.right so in this case we're currently at a child and in that case we're gonna end up returning one so when uh when we're at a child that means that we're gonna have a value of one or a depth of one and the reason that it's one is because like i showed you earlier we're just breaking it down into smaller subtrees so that's why it's gonna have a depth of one okay now over here we have one of two conditions so one condition is where we have a left child but not a right child and the other is where we have a right child and not a left child and actually besides that we have one more condition is when we have both a left child and a right child okay so now let's just see how we can first handle the previous conditions so if not root dot right so in this case we do not have a right child but we do have a left child and root dot left so in that case what's going to happen is we're going to return and the value that we're going to return is we're going to add 1 to this value over here and over here we're going to call this function recursively but the root over here is going to be root.right because root.left just does root.right because root.left just does root.right because root.left just does not exist so that's exactly what we're going to do so let's call this function so self dot min depth and the root over here that we're going to be using is going to be root dot left all right perfect um and now all we have to do is we want to replicate this function again but instead of root.right we want it for but instead of root.right we want it for but instead of root.right we want it for root.left so i'm just going to copy that root.left so i'm just going to copy that root.left so i'm just going to copy that over paste it and over here we're going to have root dot left so if we do not have a left node but we do have a right node then in that case the root that we're going to be referring to is going to be whatever root.right is going to be whatever root.right is going to be whatever root.right is perfect and now we have our final condition is when we have both a left child and a right child so in this case we're going to call our function on both the left part of the tree and the right part of the tree but which one are we actually going to end up choosing so what we're going to do is we're actually going to end up choosing the minimum of both of those okay so we're going to have one plus and we're going to take the minimum between self dot min dep so we're just calling the function on itself and the root over here is going to be root.left here is going to be root.left here is going to be root.left and now let's call it on the right uh and so let's just copy this so self.minddep and root.right so self.minddep and root.right so self.minddep and root.right and this should be it for the dfs solution and let's see if this is accepted uh i made a small mistake over here so this is supposed to be if not root.left this is supposed to be if not root.left this is supposed to be if not root.left and not boota right i'm pretty sure i mentioned that but i didn't write it sorry okay so this should probably fix our problem so let's submit this and as you can see our submission was accepted so finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thank you
Minimum Depth of Binary Tree
minimum-depth-of-binary-tree
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. **Note:** A leaf is a node with no children. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** 2 **Example 2:** **Input:** root = \[2,null,3,null,4,null,5,null,6\] **Output:** 5 **Constraints:** * The number of nodes in the tree is in the range `[0, 105]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
102,104
336
hello friends today let's solve palindrome pairs problem give a list of unique words return all the pairs of the distinct indexes ij in the giving list so that the concatenation of their two words i plus words j is a palindrome so the question statement is pretty simple but how to solve it the beautiful solution will be we iterate all the words and then we have an inner for loop to iterate the words again to concatenate these two words and check it whether it is a palindrome but you know it at this big o n squared times m is the length of the two words can you do better sure let's first see the pattern of uh the pattern the first zero one and the one zero which is abcd dcba this is a palindrome and the um the center is this line and the d c b a and the one zero can also be a palindrome d c b a b c is the center line and the 32 can also be a parent drum z y x a o l x y z and the first three can also be a pattern draw x y z aol z yx so can we have some intuition from these patterns the first two is that if current word is abcd then we just need to check whether there is a word of which is a reverse of itself so we can find the dcba so we get a result the same for the second one tcpa the reverse of it is abcd and we define the abcd in the word list how about the next two patterns z y x and a o l x y z you can find that well this is the first word this is the second word in the second word it first part is a palindrome and the rest part is actually the reverse of the z-wack x is actually the reverse of the z-wack x is actually the reverse of the z-wack x so that is if current word is 0x we want to find another word that it first part is a palindrome and the its rest part is the reverse of this word okay how about next the last one x y z aol well in this word the right part is apparently aol and the left part x y z we find that this z y x is the reverse of the x y z so that means for a given word a if in the right part it's right part is apparent draw we just need to find whether there is a reverse of its first part in the word list if yes they can be a pendulum so just these three cases okay so let's see the first one the rest of the a the palindrome and we find whether there is a b is a reverse of the first part this is a call corresponds to this case well how to check the rest of the palindrome we just needed to do it when we checked uh we iterated the word a and for the case one we found whether there is another word b the first part is the pattern drawn and the rest part is the reverse of a which corresponds to this case so for z x we just need to find another word the first part is the pattern drawn and the red part is a reverse of itself the last part is quite pretty simple just to find the whether there is a verse or beta exists in the word list so from these three cases you may find the reverse of a word is pretty important so how about saving this information that you want to think how to save it you can use a hashmap but it's not efficient because it has many strings and they have the same prefix so we can use try so we can save each string in the try and we save the reverse of this string is other is there any other information we need to save yes for this example we want to check whether it is a word so in the um original try we have is a word or it's and this is a boolean a variable here we can use integer to save its index in the word list because in the end we need to return two indexes right zero one and one zero o three two so the index is important so when we save the reverse of the word we only save the word index in the very last character so in this case dcba we try to insert a b c d into the try and when we reach d we save it the word index two one okay and we also want to know whether the first part is a palindrome so when we save the reverse of a string we know like z y x when we reach x we know it's the rest part l is a palindrome so we can save the word index of the two in this x but is the only word no because it can be there is another word called the aol xyz so the aol which has a 4ao is also appending job so we can save mostly one word index in this x so that means for every tri node we also want to save how many uh word index there are rest of her little head injured okay so that's the information and this is the three cases now let's write the code hope you can understand it's better so let's see we need a class it's called the tri node and uh it should have the children because it only have uh lower cases so we lower case in english letters so there is 26 and also we want to save the word index at begin at the beginning it's negative one we also need the uh it's a code the rest is pad linger right palindrome so uh which is tri node we just initialize it apparently draw new array list okay well in this part we need a root node which actually is empty we also need an n is the word lens we also need a return the result we call it a result you array this so we actually first needed to add every uh words oh sorry this is an i plus so we add the words i and the index to the try and the four every i zero i less than and i plus so we search a weather another word that can be concatenate to it right so this part is words i and i so finally we just return the result okay so then we implemented the void add so for this word and the word index what should we do first is a root we should get a reference of it so cur equal to root and then this is the string it's pretty slow so we can get a char array charts which is word to charm array okay then we entered every chart so i could desire unless center star lens like plus so what's next um well it's add we should add the reverse right so it's not from zero it's from charge star length minus one and i create equal then 0 i minus so here um first if we should get the index right it's a charge i minus a so that is if the what's it if the curve chosen children j equal to none if it's equal to none then we should knew it new tri note and then we put the curve equal to ker children j but we also want to save the rest of having drones right so if it's paddling drone pattern which is charged and to the rest parts throughout so it's from zero to i if it's patent drone we save uh to the curl arrest is perfect right rest is patented add this word index okay so here is it so we need another function we just call it boolean uh is palindrome whoa that's a word that's oh sorry uh it's not word it's a chart array so this is charles and i j uh so how to check with this subheading draw so we just let the i less than j if the charge i not equal to charge j which has to return force is not a palindrome uh if we carry the end the zen will return true but every time we should move this i forward and then move j um backward they go to the center okay this is palindrome so when we get to the very end we should mark could occur the word index to the current word index do not forget this line okay so how about this search void search string word uh word index so the same thing we get as a curve which is equal to the root and we get the charts which will be word to char array and the 4 into i equal to so this is the correct order so that's i plus so we'll get to the j equal to charge i minus a right minus a okay what should we do now we actually needed to translate these three cases the first one is if the current word the rest part is a palindrome right we just get a this is z if the z the rest part is a pendulum and the z has a word index because it's inverse x y z so z has a word index there we know these two words can be a result so if occur word index not equal to negative one and is palindrome it's a charge from i to the very last character their result should add arrays as list so that will be word index plus curl oriented index don't forget to let occur equal to curl children j right but this is the search so there is a chance the curve child equal to noun so just a return okay so in part this is only one case another simple case is just a reverse so when we iterate a b c d we go to d we check whether d has the word index if it has it can be a result but let's see there is a uh example is aaa so when we go to the a 80 that has a word index it can be the self so in this part we need to check if current index is not equal to negative one and it cannot be the self so not equal to the word index then the result can add arrays s list the word index and the curl word index this is this example okay we already figured out this case and this case how about this case so we already reached the end this is the curve then we want to get the x it rest is paranoid so we get another word index we just concatenate this cube part so how to get this word index we just need to iterate to the current term rest is paralleling trump right so result needed to add a race as list so there will be word list and the curve oh sorry this is j okay we already figured out all the three cases so i believe that's it okay thank you for watching see you next time
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
1,689
hello coders welcome back to my channel let's solve lead code medium problem 1689 partitioning into minimum number of decimal binary numbers our decimal number is called dc binary number if each of its digits is either 0 or 1 without any leading zeros given a string n that represents positive decimal number return the minimum number of positive dc num binary numbers needed so that they sum up to n okay means uh we are given with the n and we have to make uh we have to return the minimum number of positive we have to break this number into the dc binary number so that they add up to n for example 32 means 10 plus 11 is 32 see 32 can be formed with any two three numbers like 30 plus 2 or 16 plus 16 but we have to make the division into the dc balance numbers with only 0 and once for example this eight two seven three four the answer is eight and for this uh this very large number answer is nine it is how nine uh different numbers will be needed to form this number and that will be the minimum number of dhc binary numbers let's saw the linear time complexity and constant space complexity let me explain you the solution first then we will write through the code like we were given with the number 32 and we have to find the minimum number of dc binary numbers see when you see the number and dc value number will contain only zero or one then main thing is like for each digit we have to see whether it can be formed with zero or one and it is simple like for two we need two ones so we will write one here and for three we will need a minimum of three months so that because there will be no carry because we were making sure that the each digit is minimum and to get that number we need that number of ones because 0 will not contribute to the number like three four three we need three ones then all when you combine it then it will we will get three different numbers that will add up to 32 and then from this you can see that the main factor contributing to the answer is the largest of the digit similarly for this uh large number we need four ones three seven uh different ones but the main contributing factor will be eight the largest of the character integer similarly then we can understood that for this very large number we do not have to worry about the uh large number just we have to see which one is the maximum contributing factor like 9 is the maximum so uh result will be 9 let's write the code for it if we walk through the code like we have taken the result variable with which is containing 0 initially we are looping through the string and then what we are checking is the maximum of the characters like uh result and n dot carrot and we are subtracting with zero so that we can get the ask the value subtracted and get the result and then we are returning the result let us submit this code yeah it's successful thanks a lot and if you like this video please hit the like button and subscribe to the channel and share this video so that others can also benefit from this video thanks
Partitioning Into Minimum Number Of Deci-Binary Numbers
detect-pattern-of-length-m-repeated-k-or-more-times
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** numbers needed so that they sum up to_ `n`_._ **Example 1:** **Input:** n = "32 " **Output:** 3 **Explanation:** 10 + 11 + 11 = 32 **Example 2:** **Input:** n = "82734 " **Output:** 8 **Example 3:** **Input:** n = "27346209830709182346 " **Output:** 9 **Constraints:** * `1 <= n.length <= 105` * `n` consists of only digits. * `n` does not contain any leading zeros and represents a positive integer.
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
Array,Enumeration
Easy
1764
318
Ko a Hello friends in this section we appointed discuss in another light the problem maximum product of violence you will be given string are the first step into votes which did not show any common latest multiple between the boobs 920 multiplication in all possible point to subscribe characters and Multiple Equations of Land and Final Returned Maximum Possible Product During More Return with Example to Understand Problem Id Add No Eddy It Boiled Between the Subscribe Nine in Dad Write Novel by Voting Unique Months Between December is Length This Flight Land Cruiser Products 4000 Seervi Products Six Inch Width Product Maximum Products Six Maximum Possible Products In the given section the discussion on has to be directly jumping into the optimal solution we interviews with manipulation technique to address this problem not considered input first step will generate interviews 5065 index in different parts of birds and How to Identify Your Character Will You Want to See the Character C - Will You Want to See the Character C - Will You Want to See the Character C - Character Subscribe Character Noida Sector 97 322 Ki Inductive Represented by Characters Page Will Calculate Character Index Position Please Not All Important Things Will Be in Lower Case Problem Statement Will Fielding Other Vid0 On Vansh Only Know Members By Different Fields With Shyam Lets Check The First Time Character AB Defense Character Exams Will Smith 180 Abs Hai Isse Exit Wilv-Vriksh Reference Will Visit Us At That Name Lets Consider 180 Abs Hai Isse Exit Wilv-Vriksh Reference Will Visit Us At That Name Lets Consider As Acid Member From Left To Right The Binary Number Valve 101 Backward Equal Two Lemon Juice Press One CD Refill Wishes Member 800 Quantity Na Will Ply Between Us And Operational Dheer Va 09 Subscribe Operation Aadhi Number 90 Subscribe Notice This Tikhi Me Novel Considered As Input Singh And Calculate Bittu Is Interior Value Serial Field Is Character With CCE Waste Oil And Press 0a Number 210 Will Perform With Toys Operation And Distinct Will Remember Number 10 Play List 2000000 Subscribe Channel Not Subscribed Products 620 How Will Calculate Product Possible Combinations Share Chapter Between Them And Finally Will Return Maximum Product Haunted Allergic Plates Turn Off Lights There Are Already Copied Mitra Signatures Complete Code Will Do Basic Validations Will Return 0f Here Input Is Channel And Input Are Language Were How To Declare A Variable To Hold Input Are Length That They Will Declare Slogans Which holds a bit set interior value of its imports Thank you that there is missing internet on lettuce and an input tray is n't it will calculate set interior value batting between characters in let calculate product before the will declare variables told in product villu sallu 225 witch Letter on jhal the effigy toys and operation returns 10 runs mana letters between two words oo loot let's calculate product of vote bank par hu is the current products greatest one max product day update max product value hai to finally return max product value2 ko a very Religious Coding Letter Error Fall Return Death Something Sharp Calling Max Product Function With Multiple Inputs Electronic SIM Summit Sensitive Topic Loot Lakshmi Hanuman Sakane A That Now He Is The And Twitch Ad Expected For This About How To Find Maximum Product Award Leg Piece Like And Thanks watching please like this video and subscribe the Channel thank you
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
1,846
hey everybody this is larry just me going over q3 of the buy wiggly contest 51 maximum element of after decreasing and rearranging so hit the like button hit the subscribe button join me on discord let me know what you think about this problem you know now or during the contest so yeah so the thing that i noticed about there's a couple of observations to make about this problem um the first one is that you can rearrange the number in to array in any order and that for this array you know adjacent elements has to you know the difference has to be you go less than or equal to one so combining those two um combining those two uh we basically have a greedy solution where we sort the array um if we sort the array then the smallest element will be one and then we just basically go up to mountain as far as we can and that's basically the idea here because um yeah because that because when you sort it that way then um you can only go that way anyway so that's basically my solution i saw the way i set the first element to one and then for next one i basically made it so that it is either you know the minimum of either itself it's meaning it's smaller or the last element plus one because that's the most um incrementing that you can do from the last element and then at the way and i returned to the last element which is going to be the max element because we will we rearrange it because i think they try to follow you an example where you know you can go back to one but if you really think about it doesn't really make sense um because you always want the biggest number at the end um so what is the complexity well it's gonna be dominated by the sorting so it's gonna be n log n um yeah uh that's all i have for this form and to be honest you may have you may wonder why or how i can prove this greedy um i don't have a great answer for you uh for the people at home uh during the contest and you're watching me celebrate live during the contest afterwards but i think some of it is just about doing enough problems when you do enough problems greedy properties of greedy you can yo uh you can guess a little bit better and make educated guesses and that's the way that i did it here because after i sort it um then this way a you know because another way of phrasing this is that you know because we always want to make the max number we always want to increase by one or you know stay the same if you're made you go to so it doesn't make sense to decrease and here it just means that you can change the number to the lower number of whatever you like um so that so all those things together uh allow me to kind of produce this solution um i don't really have a better answer than that or proof than that per se but uh but yeah uh watch me stop in the live dinner contest next hmm so uh yeah thanks for watching hit the like button as a subscriber and join me in discord let me know what you think about today's farming contest and so forth and whatever uh i will see y'all later bye take care of yourself stay good stay healthy and to good mental help bye
Maximum Element After Decreasing and Rearranging
maximum-element-after-decreasing-and-rearranging
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`. There are 2 types of operations that you can perform any number of times: * **Decrease** the value of any element of `arr` to a **smaller positive integer**. * **Rearrange** the elements of `arr` to be in any order. Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_. **Example 1:** **Input:** arr = \[2,2,1,2,1\] **Output:** 2 **Explanation:** We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`. The largest element in `arr` is 2. **Example 2:** **Input:** arr = \[100,1,1000\] **Output:** 3 **Explanation:** One possible way to satisfy the conditions is by doing the following: 1. Rearrange `arr` so it becomes `[1,100,1000]`. 2. Decrease the value of the second element to 2. 3. Decrease the value of the third element to 3. Now `arr = [1,2,3], which` satisfies the conditions. The largest element in `arr is 3.` **Example 3:** **Input:** arr = \[1,2,3,4,5\] **Output:** 5 **Explanation:** The array already satisfies the conditions, and the largest element is 5. **Constraints:** * `1 <= arr.length <= 105` * `1 <= arr[i] <= 109`
null
null
Medium
null
1,003
um hello so today we are going to do this problem check if words is valid um after parenthesis after substitution so um what this problem says is we get a string um and we want to determine if it's valid and what do we mean by valid here um it means that we start out with another empty string T and we want to transform that t to the S string that we get after performing some number of operations um and we can are allowed to do any number we want right and the operation is inserting the string ABC exactly into but into any position of the string T so basically means we insert in any position and so at that position we put ABC and then to the what's what was to the left side of it or concatenated to the left and what was to the right we concatenate it to the right so basically if we formulate it's like this if T was composed of a left part and the right part okay and T also can be empty and we can just insert ABC that way T becomes ABC and when I return true if it's valid which means basically we can do it we can transform T into s so let's take a look at this first example here um so for this first example we start out with an empty string like this and then we'll insert ABC in position zero and so that would give us like this and then we insert it again in position one and so that would be like this and now it matches the string s and so With It intro so that's the idea now um how do we handle it um okay so how do we handle it um so we have a let's first understand the problem a little bit so we have t first like this and S is like this so we insert in a at the start we insert of course at position zero because we don't have any other choice and so at the start position zero T becomes ABC right zero one two and now where do we insert well it makes sense to insert here right because otherwise it won't match so we'll start in position one and we get BC then the rest of so this is the left part we can cut in it here this the right part and then the left part we can calculated here and this is our new string okay and now if we check it matches and so can we think about this problem a little bit differently so here if we think about it in terms of T and actually doing the exact operation it becomes a little bit harder how do we think about it in terms of the string s itself well you can see if we find ABC like this for example in t we can insert it because it's Contin we can insert it right we can just pick the position and insert it like we did here and so whenever we encount ABC let's just remove it and now we have another ABC again after that and so now that means also we could have inserted it at the beginning and so we remove it as well and when we reach an empty string that means it's possible because exactly what we do in T is just insert in any position so let's just do it in s and if we find ABC remove it and then once we remove it if we find another ABC because that would mean we inserted at this position right then if we find another ABC that means we inserted in the previous operation right and so we can remove it now if we are not able to get an empty string that simply means it's not possible right so how do we how does that work let me actually let me give you a check the other example we have which is true as well so ABC Aba b c okay um so for this example similarly with t initially we'll set in position zero we get ABC on certain position one ABC we said in this position right we get a b c right and then we insert in this position we get ABC and then this C from the previous operation so let's see if it works with deleting so with deleting well first there is this means we insert it initially at this position right so we delete it and now we insert it at this position right and now we see that we have another one here inserted at this position and now what's left this here okay and you can see it becomes an empty and this Maps exactly now how do we do this deletion easily because you can see it's not just going through the string because for example here once we deleted this we ended up with another string starting from the previous character and this actually is so sort of like Tetris right when you get three blocks that are matching colors in that are matching shapes um it collapses the similar ones right and so how do we do that well sort of like Tetris sort of like a in a stack format right so what does that mean let's take the first string let's take this a b c so we can do we get a string we add it we get a string a we add it we get B we add it we get C we added but anytime we get three letters that match ABC in the stack right three letters consecutive letters that match ABC we delete them and so we delete this one and then we push B again and we push C and now we have also three other third number so we can see where the stack is useful because we are able to delete and we are able to find if there is a new match so we delete it as well and now at the end how do you find if it matches well if the stack is empty that means that there is a map there is a match right it's possible to construct the stick so yeah that's pretty much the idea um so we just each time we push we check the three previous characters in the stack if they match that means we have a solution now let's try it on just another example just make sure this is uh on an example that doesn't work just to make sure this is clear so a b c b a for this one it's not possible because we can insert here but then this one is reverse it so even if we insert here it won't work right if we insert another string then it will increase if you insert two times then it will be different than S so it's not really possible to get T that matches we'll see if with the stack we can see that so first we add a then B then C now we have three strings that match so we pop them up sorry about that so we pop them up and then we have C B we don't have a string that matches we have a right and this doesn't match remember the string that matches that we are looking for is CBA in the order of the stack is CBA and when we check it as a list because stack is a list we want to match ABC but this is this here if we check it as a list it's CBA and so it doesn't match and so we've we don't pop and so we when we finish this string we check is the stack is empty it's not and so would return false okay because the order matters and that's pretty much it now what's the time complexity so we are doing this just one Loop right and then pop in from the stack you just owe one so it's oven time um and then in terms of space we are using the stack which can be up to oven if we have let's say cctc right because the at the end the stack would be the length of the string um yeah so that's pretty much it for this problem let's uh code it up and make sure it passes okay so let's cut up what we saw in the overview so what we want is we want to have a stack and then we want to go through the string s and we want to append the character and we want to see if after appending it we get ABC and so to do that we can just check if the length of the stack it needs to be at least three right to get ABC and then we want stack minus three right so basically this will give us the three last characters right we want to check if that's equal to ABC right so a since it's a list BC not CBA right ABC in this order if that's the case that means we want to pop all three right we want to remove all three so we pop three times so we do sec pop three times and then we return at the end we just check if the stack is empty ah sorry empty okay now let's submit and this passes okay now we can simplify this a little bit or at least like make it a slightly not check not at first so what we can do is if it's two and this is a b and the current character you see that would be the same check right that will be the same check except to check before appending c so in that case we can just pop two because that would Pop A and B um and then otherwise then we append because we don't want to append this C that we are going to pop with the with a and b right um so let's run this again and submit yeah so same it passes as well um yeah so that's pretty much it for this problem uh please like And subscribe and see you on the next one bye
Check If Word Is Valid After Substitutions
minimum-area-rectangle-ii
Given a string `s`, determine if it is **valid**. A string `s` is **valid** if, starting with an empty string `t = " "`, you can **transform** `t` **into** `s` after performing the following operation **any number of times**: * Insert string `"abc "` into any position in `t`. More formally, `t` becomes `tleft + "abc " + tright`, where `t == tleft + tright`. Note that `tleft` and `tright` may be **empty**. Return `true` _if_ `s` _is a **valid** string, otherwise, return_ `false`. **Example 1:** **Input:** s = "aabcbc " **Output:** true **Explanation:** " " -> "abc " -> "aabcbc " Thus, "aabcbc " is valid. **Example 2:** **Input:** s = "abcabcababcc " **Output:** true **Explanation:** " " -> "abc " -> "abcabc " -> "abcabcabc " -> "abcabcababcc " Thus, "abcabcababcc " is valid. **Example 3:** **Input:** s = "abccba " **Output:** false **Explanation:** It is impossible to get "abccba " using the operation. **Constraints:** * `1 <= s.length <= 2 * 104` * `s` consists of letters `'a'`, `'b'`, and `'c'`
null
Array,Math,Geometry
Medium
null
1,198
all right so let's talk about the final smallest common element in all the rules so you're given environmentary so for every single row it's actually sorted in increasing order it doesn't matter and then return the smallest common element in all the rules so let's just look at a copper so if every single element is sorry if there is a common element in every single row right which means the size is actually what the fruit the frequency size is going to be what method length right so methyl length so look at this the common element is fine one two three four all right which is what the size is actually Master length which is four right and the common element is five and so we definitely need a counter so if you look at this kind of problem so if you say like find the smallest common element you need a counter it doesn't matter you are using a hash map or using the inner array so since the size is actually small it's only from 1 to 10 to the fourth so I would rather to use the inner array and then I'm going to just say frequencies at least right and the sizes won't be 1001. we will have to include in the index deal the index 0 is actually important you don't miss it so once you keep track of the frequency you'll get a value so let's just start coding so I'm going to say in count sorry in three new end ten thousand one and then you if you cannot find it you'll return negative one right and then I'm going to Traverse the math and then for every single in array in inside the M I need to Traverse the value right and then I will just keep uh increment level right so at some point my frequency for the current value is actually equal to Method length right which is equal to what the size of load was right and then you will definitely know okay I have to return that so this is a simple solution and um yeah so let's talk about time and space the space is this 1001 the time all of n times n right all of M times n and I cannot use the debug mode because if I use it I will definitely print out the frequency array like every single element inside the frequency array is about 1001 so on the left side window of the development is actually what is pretty uh it's pretty dirty to be honest so if you don't believe it then just you know take a look all right so this is not how you look right so uh the idea is what you increment the counter based on the value when you Traverse the mat and then when there is a size which is equal to up when there's a value uh the size of value is actually equal to the master length like you return the value so this is an entire solution and if you cannot find it and then you have to return negative one all right so if you have any questions leave a comment below subscribe if you want it alright peace out bye
Find Smallest Common Element in All Rows
unpopular-books
Given an `m x n` matrix `mat` where every row is sorted in **strictly** **increasing** order, return _the **smallest common element** in all rows_. If there is no common element, return `-1`. **Example 1:** **Input:** mat = \[\[1,2,3,4,5\],\[2,4,5,8,10\],\[3,5,7,9,11\],\[1,3,5,7,9\]\] **Output:** 5 **Example 2:** **Input:** mat = \[\[1,2,3\],\[2,3,4\],\[2,3,5\]\] **Output:** 2 **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 500` * `1 <= mat[i][j] <= 104` * `mat[i]` is sorted in strictly increasing order.
null
Database
Medium
null
1,642
To my channel Quote Surrey with Mike So today we are going to do question number 28 of our Grady playlist. We are going to do video number 28. Okay and today's question is going to be very interesting because you are going to learn a new thing. Lead code number 1642 It is not at all medium, it will be quite easy for you, this is my guarantee by the end of this video and as I told you will learn something new today, okay if you know then it is good, even if you are new. Well, right, let's see, the question says to the queen that you have been given an integer whose name is Heights representing the heights of the buildings and you have been given some bricks and some ladders, okay you start your journey. From Building Zero and Move to the Next Building by Possibly Using Bricks and Ladders Ok the height of every building may be different, may be bigger next building or small next building so yes to move from small building to big building You will either need a brick so that you can lay the brick or you will need a ladder and that is why we have provided a ladder and bricks here while moving from building one to another. This means let's assume that from this building you will go to the next building. If the current building height is greater than and equal to the next building height you do not need a ladder brick. There is no need for anything, you can jump directly, but if the next building where you have to go turns out to be very big, meaning it is bigger than where you are standing, then it is obvious that you will need a ladder or a brick, right. So the same thing is saying that if the current building height is less than the next building height you can use one ladder and this amount of bricks and see how many bricks you can use, as much as the difference is, let us assume that the height of this building was 10. The height of this building was 15, so 15 - 10 bricks will be required for you, was 15, so 15 - 10 bricks will be required for you, was 15, so 15 - 10 bricks will be required for you, then you can go from here, after placing five bricks, you will climb on it, okay, after that you can go to the next building, so this was told but Here he told one very good thing in advance that you can either use ladder or you can use bricks, you did not see the option here, you should have grabbed it from here itself, that if there is an option then it is the best. First forget all the tricky solutions or whatever is going on in your mind. If there is an option then first of all say in the interview that I can see the option. I have I can know both the options that are very frequent. Okay, I have told you many times. This thing has already been told, if you see the option in the question, then you should write Ration. Okay, after that we will see what can be done to return the building you can reach if you use the given ladders and bricks. Optimally it is asking how far the building is. You can go up to, okay like look at this example, here we have given you height, Brix is ​​five and we have given one step, so let's Brix is ​​five and we have given one step, so let's Brix is ​​five and we have given one step, so let's see, I have made a drawing here and let's see what is its output. Bricks will come, there are five, ladder is one, right and you are currently standing at index number zero, I have written the height of every building as 4 2 7 6 9 14 12, so see, currently you are at index number zero, then from index number zero you will get the index number. If you want to go to the forest, then obviously how will you go here, you will go comfortably because the next building is smaller than your building, it is right, neither can you go comfortably, so you have come here, right, so after this, now look carefully. Dena, the next building is seven, it is bigger than you, so to go up you either need bricks or you need a ladder, then look at the bricks, if you want then how many bricks will be required, let's see if the building in front is from the current one, if you are standing on two, then it is 7 meters. 2 That is, you need five bricks and you have five bricks, then what will you do, you will put five bricks here, one, two, three, four, and if you were here, you will jump here, otherwise if you have used five bricks. Brix, now you have become zero, ok, now from here you can go to six, just because the height of the next building is less, so now you have come here, right, now from six, if you want to go to nine, then look, pay attention. If we want to go from six to nine, then you are looking at the bricks, so you have them, don't you? We need three bricks, 9 or 6, but we have three bricks, we have zero bricks, so we don't use bricks. Is it a ladder? Yes, is it a ladder and what is a ladder? There is no need to worry about the height of the ladder. If you install a ladder, you can go to any big building. So what did you do? Install a ladder and you have come here. Okay, now you have finished the ladder too, after this you can go. What not, after this look, the next building is 14, neither you have bricks nor you have a ladder, so you have been able to reach the maximum fourth building, meaning if you have been able to reach the building with the fourth index, then you have to return the index, then your answer should be four. No look, the output was fo here, ok, it is quite simple, so if you had told me, why didn't you use the ladder here, then okay, you could have used the ladder here, sorry, yes, you could have used the ladder here, let's say you would have used the ladder here. So let's see what happens, now the ladder has become zero, I was here, then came here, then from here using the ladder, I came here. Okay, now from seven to six, I can come comfortably, so I came here, but yes, success. To go from Se to Nan, I will need bricks. It's okay because there is no ladder, so how many bricks are needed? 9 - 6 That's three bricks, only needed? 9 - 6 That's three bricks, only needed? 9 - 6 That's three bricks, only one, two, three bricks are needed. Two bricks are left. 5 - 3 Two bricks are left. 5 - 3 Two bricks are left. 5 - 3 Two bricks are left. After that. It will be seen that now I am standing here, I have come here, but to go from nine to 14, I do not have a ladder, I also have a brick, so only two bricks, but how much will I need to go? 14 - 9 That is five how much will I need to go? 14 - 9 That is five how much will I need to go? 14 - 9 That is five bricks. But I don't have five bricks, so I remained at four for the fourth, so in this case also my answer is four. Okay, so till now many people might be thinking that this is simple, it means I have put bricks. When the bricks are finished, then I will keep climbing using the ladder, so that greedy approach is what you are actually thinking, what are you thinking that as soon as I get a big building, if I have bricks then I will use the bricks and if there is a ladder. So I will keep using the ladder and see how far I can go. So actually it is greedy. You are trying to move forward by directly using bricks and ladder but you will fail there due to greedy. Okay, so first of all let me show you the proof. Why will Greedy fail? After what I told you that if there is an option then you should have hit recurse try. If you go there then first of all we check why Greedy will fail. We understand why Greedy fails. I know it is very strange because of the playlist. The name itself is Greedy but still Greedy is failing but wait a little, there will be a very big U-turn, but wait a little, there will be a very big U-turn, but wait a little, there will be a very big U-turn, okay, this is our example, let's start, first look, I am standing here, okay, I will write on the index number row. Am 0 1 2 3 4 5 6 Is it right and now you are currently standing at index number zero on the building, so now it is obvious that from one to five, if you have to go, then one thing you can do is that brother, you will say, the ladder is very amazing. The thing is that no matter how big the building is, it takes me to the next place in one go, so I save the ladder, use bricks, okay, so what did I do now, 5 - one, okay, so what did I do now, 5 - one, okay, so what did I do now, 5 - one, I have to go here, 5 my one, that's four. If I want bricks, I used all four bricks, then I have zero bricks, but now I have reached here, right, I used four bricks, one, two, three, four, okay, now after this, look, from five to one, you can go. Yes, because it is a small building, you can go there easily. There is no need to climb. You have to get down directly. Now see how you will go from one to two. If you have to go from one to two, then you need a ladder or a brick. How much of one is needed? 2 - 1 That's one brick is needed but one is needed? 2 - 1 That's one brick is needed but one is needed? 2 - 1 That's one brick is needed but you don't have a brick otherwise unfortunately you will have to use a ladder, so if you use a ladder then it is fine, there is no limit in the ladder, it can take you to any building, no matter how much. If it is a big building then you have installed this ladder and you have come here, okay now you have also finished the ladder, now you cannot go ahead because the three after two is a big building, neither you have bricks nor you have it. If you have a ladder then what was your answer that you can go up to index number three but this answer is wrong ok now let me tell you why this answer is wrong first let me write that when we walked Greedy Gradly we saw that good bricks If yes, then we kept using bricks. Okay, after that the ladder came, so we used the ladder. What was the mistake in the trick we used? So first I will write again that when I went from one to five, remember how much bricks I used. Four bricks were used, okay now after that from F to one we went easily. Nothing was used from one to two. When we went from one to two, we used one ladder. Okay, this was my greedy trick that brother, I have a brick, use a brick. Let's keep doing it, in the end, when a big requirement comes, I will use the ladder because the ladder is an amazing thing, okay, if you can reach the index number th in it, now see what I say, if you, I will erase it back if. You were in the index row, right? If you use the ladder, let's see what happens. Had you used the ladder, you would have directly reached here. Okay, so you have come here. Now you have no ladder left. Right, the ladder has become zero now. After this, you can easily get down here, so you have come here, you don't need anything because the height of the building is small, the height of the next building after this is two, so how many bricks will I need, see if there is a ladder, otherwise how much. Bricks will be needed 2 miles because the next building is two, the current building is one, okay, so one brick will be needed, I have four bricks, so I used one brick, three bricks are left, so I placed one brick here and came here, okay. I still have three bricks, so look how many bricks will I need to go from two to three, 3 minus two that is one brick will be needed, so now I have taken one brick, now two bricks are left, okay, put a break here. Now I come here, still look, three to four, I can go, I want one brick, I have two bricks, so I put one brick here and I came here, okay, so now I have only one brick left. And obviously I cannot go to Haj at 4, so you see, this time I was able to reach the fifth index, so the better answer is my 5. Okay, what does this mean, you have to explore that brother, you cannot do that. Just keep using bricks, once the bricks are finished, then we will use the ladder. In the end, you can never do this. It is okay or you cannot use direct approach. You will always get stuck on some example or the other. Either you have used this approach. Lee said that brother, keep using the ladder continuously and then you will use the brakes in the last or else keep using the bricks continuously and use the ladder in the last, otherwise you will have to do the mixture of bricks, ladder, bricks, mixture of bricks, ladder. In this you will have to put some mind and you can do that only. You can try both, one, you have two options, either try the ladder or try the bricks, then you have the option, otherwise explore all the options sequentially and see, the one from which you can go the furthest is yours. This is the best answer, isn't it, this is what happens, okay, so he is greedy, that is why he failed and it was very important, that is why I have dedicated this part separately in this video that it is okay if he is greedy, so now let us come back to our old method. What did I say, don't you have options? Put recurses. Okay, let's come to our recurses technique and a tree diagram will definitely be made. If we have options, then let's accept the index number. But right now I am standing, who do you want to know? If you have to go from one building to the next building, you have to do the same every time. If you have to move one building at a time, then two. First of all, I noticed that the next building is bigger. If it was smaller than the current building, then there would be no problem. I move ahead, if the next building is bigger than me, then I first check whether I have enough bricks or not. If I have bricks, then I will try with bricks and also with ladder. If there is a ladder then it is fine then I saw that it is less than that means I need either a ladder or the like so I have two options, the first option is that I should use bricks but I should also have bricks, that doesn't make sense. How many bricks are needed 3-2 bricks It must be sense. How many bricks are needed 3-2 bricks It must be sense. How many bricks are needed 3-2 bricks It must be less than or equal to my current number of bricks Ok I need only one brick and I have three bricks so yes I can go in the ladder There is no problem how big If there is a building, you can go, but the count of ladder should be greater than zero. So yes, if you have a ladder then you can try both options. If it is for the sake of value, you have used bricks, then in this case, remember that bricks are ours in the beginning. Pass was through and ladder we had one, okay so now if you use brix then yes you will come on index number one okay so now index has come here and look pay attention now how much is your brix now your Brix 3 my t it is done ok here I am writing brix now your t is done ok now look after this you have to go from 3 to 19 look here look at this path i.e. this here look at this path i.e. this here look at this path i.e. this is your i+ 1 to 3 How many bricks will you need to go to 19? is your i+ 1 to 3 How many bricks will you need to go to 19? is your i+ 1 to 3 How many bricks will you need to go to 19? 16 bricks will be needed to go 16 why 19 - 3 But you needed to go 16 why 19 - 3 But you needed to go 16 why 19 - 3 But you don't have that many bricks otherwise do you have a ladder? There is no option, you can't go there, okay, so I hit ladder try, so if I hit ladder try, then obviously I can go 2 3 193, I came here and the ladder count is now zero. Because there was a ladder, I used it. Okay, now see, 'r' comes after 19, meaning index ' now see, 'r' comes after 19, meaning index ' now see, 'r' comes after 19, meaning index ' i' is 3 in P, so yes, it is small, so I i' is 3 in P, so yes, it is small, so I i' is 3 in P, so yes, it is small, so I can go there comfortably. I neither need a brig nor a ladder, so come here. But it is an obvious thing, now look at how many buildings I have jumped. I was at index number zero in the beginning, then came to index number one, came to index number two, came to index nth. Okay, so the father of all. I have reached index number three, okay, now look, let's look at this path, if you had taken the ladder, then it is okay, 2 3 19 3 If you came here, you would have reached here, but the ladder would have become zero again because the ladder is not there now. Now but look, from three you have to go to 19, you need 16 bricks or you need a ladder, now you don't have the ladder and you also have only three bricks, how will you be able to go, you will not be able to go, you will get stuck here, okay what does this mean? It happened that you were able to go only till A and you were not able to go till P, so look what is your index here, then your index is index number zero one, and if you were able to go only till index one, then we explored both the paths. Best Answer I got this answer number three, so looking at the options, we applied here, okay, and yes, if you notice how simple this recursive code is going to be, and I would suggest you to see one or two examples by making more tree diagrams. If so, its code is also going to be very simple. First of all, look simple, we will write a function named solve, okay, we will send the index, there is no need to send anything else, okay, yes, we will send bricks and ladders, how many bricks are left, how many ladders are left. It's okay, now look, first of all, pay attention that now you are on ID Then there is no problem, Brix Chander, you go ahead, I mean, I am asking to check if the building with heights of ID one point next is either less than or equal to my current building. Where I am standing right now is fine, it is an obvious thing, I would not need anything, what will I simply do, I will return that brother, I have jumped into one building, I can go to the next building easily, no plus, now solve the next building. As per the answer, you bring me the ID, I used no comma, no bricks, I did not use ladders, it is clear till now, okay, why did I do this one plus, because I have jumped from a building now, okay, and if it is not like that, then it means. If the next building turns out to be bigger, it means we need either bricks or ladders, okay, so let's see, we need both options, so I write two variables, if I go by bricks, okay, then what is the answer? If I go by ladder, then what is the answer? Whichever answer comes, I will store it. Okay, now look, pay attention, look, when can you use the break, when the height of the building you have to go, one + 1, you will get this Had to go to the building minus + 1, you will get this Had to go to the building minus + 1, you will get this Had to go to the building minus current height heights of a d a is ok as much bricks as you need it should be less than or equal to my current as many bricks are available with me only then you will be able to make this jump ok so you by Brix go, you will jump is equal to one jump, plus now father you can go E We will store it in the variable minus diff and write this many bricks, I took the ladder, so we did not use the ladder here. A simple eight is quite simple, this is done by the brick, I have come up with the answer. If you want to go by the ladder, then there is no problem. It is not there, so why am I doing by ladder equal two plus because I am telling that I have jumped into this building in the index, so I have added no plus that I am increasing the count, I have jumped into one more building. I gave ID Pw Bricks but I did not use it at all. In this case I used only Ladder so I added minus to Ladder. I minus Ladder till now it got cleared and what will I do in this case. Maximum return off by Bricks by Ladder out of the two. I will return the maximum that came, that's the end of the story, it was so simple, that's why I said, make a recursion tree, then see once, okay, now let's write the base case too, now think for yourself, pay attention here, when you reach the last building, it means index number. n - 1 So means index number. n - 1 So means index number. n - 1 So after this do you have to go or not? If you want to reach the last building then write here in the base case that if e = n - 1 then yes it is true that = n - 1 then yes it is true that = n - 1 then yes it is true that you will go a little further. So make the return zero so that now you can't jump any more. Make the return zero. Okay, you can't go further into the building. Okay, it's clear till now, so we have written the base case also. It's a very simple recursive code. Now comes the point. For its memorization, if you notice that three variables are changing then you can use D are for memorization but if you try using tree diagram then you will notice that ID one is changing for every call. If there is only one call for this, then you will be able to identify a unique state, your work will still be done, but unfortunately the constraint is so high that you can do this. Even if you take it will exceed the memory limit, why did I tell you this solution so that you can tell it in the interview and it is important that you go with the most basic approach, further you will have to tell two things, if such a question comes in the interview then similar question. There are more like this, I will tell you in the last, what is the similar question, you have to solve it will be your homework, you will have to tell why Grady is failing, secondly you will have to tell that okay, there is recurse, there is option, so I have written recurse and why 3d. Instead I am taking 2d because I can uniquely identify any state using bricks and ladders only. Okay then I will do memorization with bricks and ladders. Now let's see and the memory limit will come because the constant is very high so quickly. Let's submit it and see whether the memory limit is reached or not. After that we will come to our final approach which is the most important part. Let's do our code based on this video and also try it with memorization and see if it's ok. So, first of all, I told you what we will do, first of all, let's find out the int a e it high. Okay, after that I have to write a simple solve function. I told you that I will start building the index number zero and send the height. I give how many bricks do I have, how many ladders do I have, I had to send these three or four things int solve what is the thing I am sending int what is the current index and heights I am sending and after that how many bricks do I have and how much ladder is that I am sending it till now it is clear and I had told you base that if you become adamant then father, you do not have to jump, you do not have to return zero, it is okay and if it is not so, it is okay, then what do you have to do. First of all, check that the current height ID You have already beaten it, now you can go to the next building, 1 ps i 1 pv is ok, there was no need for height bricks, there was no need for ladders too, so there was no change in them, but if it was not so, then we also need Bricks and Ladders is okay, if it is clear till now then let's see, I will write down, if I go by bricks, how much will it cost, at what rate can I go, by going by ladder, how far can I go, okay, so first of all we have to see that Brother, if I go buy bricks, do I have that many bricks or not? Bricks are greater than equal to the next building I have to go to. Next building, I have to go here. Okay, minus where I am currently standing. The difference between the two is as much as I need to have the same number of bricks, so already I should have this many bricks. Greater than equal to two. In that case, I can go by brick. So by brick by be equal to two plus solve I one. Okay, heights and I have already this much. There were bricks in it, so much has now disappeared, the difference which was mine, I write it separately, int diff is equal to this much, I want so much, bricks should be greater equal to diff and this much diff in brick is gone, it has become minus ladder. So we did not use it, in this case, the ladder of the ladder is r and if it is not so then sorry Brix, if it is greater equal diff then we will explore the path of Brix also and if the ladder I have is greater than zero then we will also explore the path of the ladder. If we do then we will also explore by ladders, no plus solve i one pv heights bricks are used otherwise bricks of bricks will remain, ladders will be -1 of bricks will remain, ladders will be -1 of bricks will remain, ladders will be -1 because this time I have chosen only ladders till now it is clear ok and in the last What will I return here? Return maximum of buy brick or buy ladder. Okay, see here, there can be only two cases, either this or this, and then nothing can happen. In the end, nothing, return anything - Do 1, there is nothing, return anything - Do 1, there is nothing, return anything - Do 1, there is no problem because I will either return from here or I will return from here. Okay, let's run it and see if the athlete passes the example test. Then let's try to memoize it. Okay, see if you pass. There is a big constraint for memoization, you see the length which is the number of bricks which is the power of 10, it is not that big, you won't be able to take it but still I will memoize it and show you, right here I have mentioned the vector of I have taken the vector of int, I have given the name to it's ok and here I inline it, since what I told you is that I do not need an index, I can also do the unique identification with Bricks and Ladders. Just okay so it's vector of int how many bricks are there neither bricks psv vector of int ladders plowed everything down to minus and okay so before I do anything here I'm going to check that it's of Bricks and Ladders is not equal to mine means I must have stored it, so I will simply return it. Bricks and Ladders is ok and I will store it here before returning. I will store it here also before returning. Ok then run it. Let's see, but yes, the memory limit sheet will come so big, you can't take it for memoing because the size of the bricks is too much, there is no power of 10, so let's see, after that we will come to our last look memory de seed. It is okay in 11 test cases only, so let's move quickly to our last i.e. final approach. move quickly to our last i.e. final approach. move quickly to our last i.e. final approach. Okay, to our final approach which is very popular and my favorite approach. Okay, this is called Lazy Grady approach, so let's actually understand. What is this? Okay, so now look, pay attention, remember this example, I told you where your Grady approach was actually failing, here the Grady approach, what did you do, you saw that it was good, first you kept using bricks then At last you got a ladder and used it so now you are here, you saw how many bricks you need, diff is equal to 5 minus one, you need four bricks, you had four bricks, you used four bricks, okay, pay attention to each step. But pay attention to Y, you have come here after using it, okay, this was your first step, you have come from index number zero to one, so how much Brix did you use on Y, I will write Brix used equal 4, okay So your Brix has become zero, isn't it? After this you could have easily come here. Okay, so now the next step, what did you do? You jumped directly because the next building was small. Third step, what did you do? You saw that okay here, next. The building is bigger than me so I have bricks so can I see how many bricks are needed two minus one bricks I have zero bricks so brother I can't use bricks so I used a ladder Ladder was equal to two Ladder or 1 minus and zero Ladder is done, now I used it and came here. Okay, index number 012 has come to 3, so I have reached index number 3. Now pay attention to one thing, when you have come to index number three, now you jump from here. You ca n't because you neither have bricks nor you have a ladder, okay, you will also think of a real life scenario, you will not know what will be your first regret, you will think, oh man, have I ever had such a case in the past where I Had I used too many bricks? Okay, had I used the ladder there in the past, would I have benefited? This would have been my first regret and I am doing the same regret here too. Look how I became sad when I came here. That now I am not able to go, then I regretted that I must have used too many bricks sometime nearby. Okay, so now look, pay attention that there might have been more buildings in the past, as per the example. Take it as it is, maybe I used two bricks here, maybe I used four bricks here, two bricks here, okay, now I am not able to climb further here, I am stuck in this case. Here, in the past, I will check that brother, which was the case where I did too many bricks and I wish I had used the ladder, there understand the first thing, think of the real life scenario, I am going with it. Let's say in real life, if you are doing this incident, then what will be the first regret you will have that man, I must have used a huge amount of bricks somewhere in the past. If I had done it, I wish I had used the ladder there. If it is ok then no problem friend, do you have the information of past or not, you store it somewhere then I will store it here brother, remember in the past I had used four bricks, ok so I have stored it. Suppose, take any data structure, I have stored it in it that yes, I had used four bricks, now let's go by the value and in the past, I am taking a different scenario that you had used eight bricks, then you used eight bricks. Have also used it in the past, so now pay attention to one thing, now these eight and four bricks, this is the second example, I have given eight and four bricks as an example, so when you are sitting here and crying, then first of all you should do this. Brother, will you recall which was the place where I had used the most bricks and I wish I had used the ladder there? Then I know what you will do. You will go to the past and see where I have wasted the most bricks. I will say brother, there was a building at one place where you had used eight bricks to jump, so I wish you had used a ladder there, neither is a ladder, but a ladder is independent of height, no matter how big the building is in the next building. If you can reach there, I wish you had used that ladder there. If you had not used these bricks, then you know, don't do anything. Go to the past. Where did you waste the biggest brick? If you have wasted it here, then remove it and take that much brick from back. Now You don't have zero, now you have eight bricks and at that time you should have used the ladder. Okay, you should have used the ladder at that time. So you say yes, I used the ladder at that time. If you have a ladder now, then I will put a minus and in the ladder. Okay, yes, there should be a ladder as well so that the ladder which you had wasted now, you have used it in the past and now you have recovered the biggest brick. Whatever you had wasted it, so what are you saying now? No, no, I have not, instead of that eight, I have climbed up the ladder there, I have climbed up, that is, now I am recovering it, so eight bricks are mine. Now those eight bricks will be saved, I can use them here, okay, that is, I told you what is my thought process, which is obvious, in real life scenario, my regret would be that I wish I had used the ladder there, now I am of the same mind. Let's see, here it may seem that no, okay, let's start again, there were bricks four, there was ladder one, right, let's erase all these, now let's see if I keep taking care of this thing, then I will be able to succeed. No, okay, so look, pay attention that right now I am standing at the starting, index number is at zero, I am standing here, now I have to go, here I have to go to five. Okay, so look, right now I have used the brake because to keep the ladder. One advantage of this is that no matter how big a building I build in the future, I can use the ladder. So let's use the brick for now but I will keep a note that brother, I have wasted four bricks here, the bricks have now become zero but I Note down that four bricks have been made, okay, after using four bricks, I have come here, I have used one, two, three, four, now look, you can go from five to one, so easily you went into this building from one. Okay, so now pay attention to one thing, first of all, check whether there are bricks, if there were bricks, I would have used them, but I would have stored them here, I have used some more bricks but I don't have bricks. If it is ok then look at the bricks. If not then it is obvious that you would like to use the ladder. You may want to use the ladder only but you will first check whether you have used bricks in the past or not. How will you solve that? Look at how much you have right now, you need 2 minus 1 brick, you need it now, okay and look at the bricks you have used in the past, you have used four bricks and think, the four bricks you have used, the brick of the past is very much. It is bigger because it is much bigger than my diff and I am regretting that man, I wish I could have used that brick here because look, right now I need one brick. If we assume that right now I would have needed 10 bricks, then remember in the past. I had used four bricks so there is no use in bringing those four bricks because I need 10 bricks now but now I need only one brick, you see and on the pass I have used four bricks, you see the pass is much greater. Then what I require right now, I need only one brick and in the past I have used four bricks, that is, what I require, that is, different than what I need, it is much less than what I have used in the past, so obviously. I wish I could bring the one from the past here, so I will do the same, I will bring the one from the past, when did I use the most brick in the past, I used this four one, so I brought the brick back, okay and I will say that Brother, at that time I should have used the ladder, it was four, which I recovered, it would have been better if I had used the ladder then, because now look, my requirement was only one, not one brick, and I had four. If I used a brick last time, then I will use only one brick and I will still have three bricks left, so instead of using the ladder now, I have used the ladder in the past and in the past, when I had wasted the most bricks, that was not it. I just brought it, look, I have got four bricks back and I have used the ladder in the past, so I reduced the ladder, this ladder became zero, now how many bricks are left with me, 4 minus def three bricks left, okay And this guy came here from here, okay now you store it here. Which one brick was used? He used just one brick and came here. After that, how many bricks are left with you? Out of four, one is gone, three bricks. You are saved, now after this you can hit the feather jump again, by using one more brick, you have two bricks left, now ok, after this you cannot jump, right? Now look, pay attention, here again you are regretting that Friend, I have only two bricks, how do I jump, then again you will see in the past that first of all, see how many bricks are needed, how much is 1, let's say 100 minus 4 is 96. If you need bricks, then you remember when you were not able to jump with the help of bricks, then you used to look in the past and not when I have used the most bricks, then when you go to the past, you see that okay, I have used the most bricks in the past. If I have used one, then is that one brick, I can get help in 96, I cannot get it, that is, what happened this time that the difference is very sorry, much greater than the maximum which I had used in the past, okay in the past. The maximum that I had used can never be achieved, that is why I will not be able to use it this time, I will stop till index number 0 245 only, the thing is clear till now, please note that I have given you an example. That there may have been many cases in the past when I might have used different amounts of bricks. It's okay and the amount required by me currently is different to go now. How will I compare it with where I have wasted the most bricks in the past? I will first look at the maximum that I have used in the past, because if it is not possible then it is obvious. Apart from that, how will it be possible with the small bricks that I have used in the past? So, the biggest brick that I have used in the past is I have to take care that I should be able to use the one with the maximum number of bricks. Okay, so it's an obvious thing, what will we have to use? What will we have to use? Max is the same, right? What will happen with the help of Macp is that we will be able to store all the usages of our bricks, but They will be able to store in descending order, meaning the maximum usage will be at the top. My brick is fine. If it is cleared till now, we will have to use max heap of max u. Now see, this is a simple story, how can we code it? First of all, what did I tell you that brother, if the heights of i + 1, where I have to go next, heights of i + 1, where I have to go next, heights of i + 1, where I have to go next, if it turns out to be less than or equal to the heights of a, then it is okay, then don't do anything, just continue. If no then it is obvious, see how many bricks you need, how did you calculate the heights of i + 1 minus the heights of aa, so you heights of i + 1 minus the heights of aa, so you heights of i + 1 minus the heights of aa, so you need so many bricks, you have taken them out, now you have to see whether you have that many bricks or not, meaning the current that you have. Brix is ​​there, if it turns out to be greater than equal to have. Brix is ​​there, if it turns out to be greater than equal to have. Brix is ​​there, if it turns out to be greater than equal to diff, then it's okay, use the brix now because we will be able to recover later, okay, so I write here that brix minus equal to diff, I have used this much brix. And but I will put in the priority queue that I have used a different amount of bricks at this moment so that if needed in the past, I will recover it from the priority queue and the priority queue is the max heap, mine is the maximum. The brick I did will be at the top, right? After this, if it doesn't happen then consider that I do n't have brick. Okay, then what I told you was that I will go to the aisle and first of all check that. In max, when did I use past bricks, how much did I use, then it will be on the top of the priority list, otherwise first check whether it is as much as I require right now, if a greater day has passed, then in max, I have used as much maximum as I have. If you have used a brick then it is okay then it is not possible then nothing is possible if the diff is greater than the max pass then you cannot do anything you just break from here itself no means the diff is less than the max pass brick If it happens, then I will take out the max pass brick from there, okay, that means I will pop 'p' and say, 'Brother, I will pop 'p' and say, 'Brother, I will pop 'p' and say, 'Brother, I have taken out that one now, that one's bricks are fine and after this the current one I have is bricks plus e is equal to as much as max past. Brick was that, I will bring it, okay, Max past bricks, okay, I brought this. After this, let's subtract in bricks. Bricks minus is equal to two as much as I needed. Bricks minus diff. Now you have used diff amount of bricks, so you have to enter Why do I give priority to this for the future that I have just used a different amount of bricks, okay, it is clear till now and yes, if this case does not happen, if this else case also does not happen, meaning here if less than is not equal to less than. If not, then remember here I said that we will break, there is no option, less is not equal, if it was greater, then we would not have been able to move ahead, the story would have ended there, it is fine for us, but we have missed one thing here. What did you do? Remember what I said that I took out the bricks that I had used in the past. Look, I have recovered them again. This means that the ladder I had now, I will use that ladder nearby and will use it in the past. I will do it, okay, but there must be a ladder, so put the else if here that the ladder must be greater than 0, because look what you are doing here, you are saying that if I have a ladder, then don't use it right now. If I had used it sometime in the past and if I could have brought back all the bricks that I used in that past, it would have been very beneficial for me. If you have brought the bricks in the past, then you will have to send a ladder there. If you are okay, then the ladder is yours. You should still pass, so what would you say, if you have the ladder now, then you are trying to say that the max bricks I have used in the past, if it is more than my diff, then it is obvious that I will recover. Look, I have recovered here, but now I will say that I have used the ladder in the past and I have recovered the bricks that I used there. Okay, so here we have the ladder. Should have done minus also, ok till now it is clear, ok, if I write in then see, something is happening that if my next building is smaller or has equal heights than the current building, then I will continue or I will have to make as much difference as I want. I need so many bricks to go to the next building. If I have it, I will use it, so I minus the bricks and I kept the amount of bricks used in the priority queue so that in future I can recover them if needed, then it is okay. What can be the third case that if I do not have bricks then I will check whether I have a ladder. Yes, if I have a ladder then I will check whether I have ever used more bricks in the past. So the best way to check in the past is First check whether I have put anything in the priority queue or not. Okay, if the priority queue is not MT, then I will check how much bricks I used in the past in max. Okay, how to remove the top? Okay, I am in max. So in the past, I have used maximum number of bricks in each instance, which one is on the top because of priority, that is its max value, so I will check this, current which is my requirement, what is the requirement of diff, is it less than my max? Close is fine, if it is less then it means that I wish I could recover the brick from max past and the present ladder is used only in that max past because what does it mean that I used so many bricks in max past? Useless and now I have less requirement than that, so I could have jumped the current one by using it and using those bricks. So let's recover those bricks. Bricks plus equal to two have been recovered from back. Look, I have so many bricks. And okay, now what did I say after this that the bricks have been recovered, now I remove as much as I want from the bricks, removed the bricks minus it diff and in the puck, remember friends, we had taken out the puck from the top and not even the puck pop. Is it okay to do this and push the pkdot? Who is it okay to push this diff? It must be clear right now since you have pasted here, what are you saying that if you have ladder greater than zero then you Either recover the bricks from the past and use them in the ladder past. It is okay, that is, do the ladders minus here, or if it turns out to be MT, that means there are no bricks nearby, not used, what will happen in others. Only ladder will have to be used, right now you don't have any option, it is clear till now, okay, first of all, it is a case that if there are bricks, if there is no brick, then there is ladder. If there is no ladder then brother, do something. Can't break anything else, this break condition should have been written here, I accidentally wrote the break condition here, there can be only three conditions here, either I have bricks so use them, or I have a ladder, so You can use ladder but check whether you can recover bricks from past or not. In any case, you have to reduce the ladder because you must have used that ladder in the past or use that ladder now. If there is none of these two, then break it and finish it. Let's code it quickly and finish it. Let's code it with the final approach. First of all we have taken out the height size of 10 and defined the priority. What is mine is max heap, okay now after this what did I tell you that brother int will start from aa = 0, right what did I tell you that brother int will start from aa = 0, right for aa is less than n, it will go till n myv only, remember the last index is n-1 or not, sorry n myv last index is n-1 or not, sorry n myv last index is n-1 or not, sorry n myv From i will go to less because look, if you are currently at a, then what do you check whether you can go to i point or not? Okay, from i you have to go to i point 1, but if let's say you go to i -1. If you come, then but if let's say you go to i -1. If you come, then but if let's say you go to i -1. If you come, then where will you go after that is why I have done n-1, less than, okay, so let's go, the I have done n-1, less than, okay, so let's go, the I have done n-1, less than, okay, so let's go, the first thought was that brother, if the heights of aa are where I have to go, if it is less than or equal to the heights of aa, it turned out that What does it mean? Continue, there is no problem. It will be done here. Is it right? And if it is not so, then let's calculate the difference. How much will it be? What does it mean that where I have to go next is a big building. Right, from my current building, I have calculated the difference that I need so many bricks, so check whether I have that many bricks or not. If bricks are greater than equal to diff, then let's use bricks minus it's diff. Cud push diff I used enough bricks so that I can use nearby ok else sorry else if you assume I don't have bricks then else if I will check if I have ladders or not ladders are greater than if If there are ladders then you can either use the ladder or check in the past to see if there is any case in the past where I had used too much int max breaks under past peak top, it will be stored in it, why is it a priority now? Why are you using? Why are you not keeping the max value in a single variable? Because brother, in the past you may have come across many such instances where you have used bricks at different places, so you will have to store all of them, right? Okay, so now look, pay attention, the cake has topped, if the bricks I have used in the past are too much for my current requirement, that means I have used too much in the past, I should recover it, then I Recovered this one Brix plus equal to max Brix past I had used p cud pop the past one because I have recovered it now isn't it and now I have taken whatever requirement I have in brix, removed the diff and p cud Push that now I have used diff amount of bricks have been used, okay till now it is clear and if and yes since I must have used ladder in the past, in that case it is fine but ladders should be minus because past I have just brought the brick here, so the ladder I have now is the one I have used in the past, so I have made the ladders minus here, but if the max bricks are a greater difference than what I am seeing in the past, then it is not a greater than difference. So brother, there is no option, then you would have to use ladders only, then you would have done minus, okay, this is the case when priority queue is not my MT and if it was MT, then brother, you have no option. Only ladders have to be used, ok, look, pay attention, if the greater day is 0 then there are two options, either I can recover from the pass, if I am able to recover, I will do so and the current ladder must have been used in the past, hence ladder minus. If I am not able to recover then I do ladder minus in others. Even if I have not used anything in the priority queue past, I still have to do ladder minus. It is better than doing ladder minus so many times that you end up in so many parts. Remove the 'else' completely and remove the 'else' here you end up in so many parts. Remove the 'else' completely and remove the 'else' here you end up in so many parts. Remove the 'else' completely and remove the 'else' here too, then anyway your entire case will be handled. Okay, I wrote that for the sake of simplicity, to make you understand, if you understand it in a basic way, then it will be very easy to understand that past If you have tried to recover from the ladder, then it is a good thing. If you have done it in my minus, if you have not been able to do it, then you will have to use the ladders. If you use the ladders now, then it is the same thing, there are ladders nearby. If you have used or have just used the ladder, then it is an event. Or even if the priority queue is vacant, even then the ladder is still an event. You will have to use the ladder only because the ladder is greater than 0. Okay, so why do you create so much trouble and go directly outside here? Make the ladders minus times because if you have ladders minus greater than zero, then either you use the ladder after recovering from the past or use the ladder in the past or use the ladder now, there is a fear that it will be minus, that is why I said it once here only. Wrote 'either I said it once here only. Wrote 'either I said it once here only. Wrote 'either used in past' or 'present', you have to do it. used in past' or 'present', you have to do it. used in past' or 'present', you have to do it. Yes, if you have neither bricks nor ladder, then you will have to break, then you stop. Now just return it at the end to see how far you have reached index number I. Isn't that your answer? Okay, let's see that the operation of time completion test is also going on. In the worst case, p cud top p cud pop, it seems to be log of n. Let us assume that the maximum size of priority k is n, then log of n. It feels like pop and pop in operation and push will take n, its time will be complained n will be taken off n because we have taken priority q so I hope I was able to help in a lot of detail. I made this video intentionally so that you You can understand this concept, okay and now what is your work, your homework is that you have to make a question which is very similar to this, know the name of the question, what is the minimum number of refueling stops, okay, this is in the lead code itself. If you search, you will find it, but it is your homework that you must try it is very similar, not exactly similar, not very similar, so see you in the next video, thank you.
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
114
hi guys welcome to my channel and today let's talk about lead code problem 114 so here is the problem and as you can see you are given a binary tree and you want to turn this into a linked list so for this kind of problem my recommendation is that you start with a very simple binary tree like a binary tree that has three nodes and then try to move that around try to get a linked list you will gain some insight from doing that and then apply that on a bigger binary tree and see if you can generalize it that's the way i approach this kind of problem whether it is a um like you know the graph problem or dynamic programming problem you always start with a small one and then try to see if you can find a pattern yeah so this is how i approach this problem initially so you start with very simple binary tree one two and three so how do you flatten this binary tree into a linked list so basically you would have to move two to here and then three should go to the right so right child of this node two so what you set this current node points to this one and then you want to find the rightmost node of the left sub tree there will be two so you set that equal to p so p points to this two and then you also set this guy this is just current notes right child so if you set current note dot right this will point to this guy now you can set p write equal current node.right what that does is node.right what that does is node.right what that does is you will create a um so this guy doesn't have anything this guy has no right no left child but if you set p dot right equal to current note dot right you will set your points to this guy and then what do we have well we have this guy initially now we want to move two and three to this to the right so that we have flattened so that we have a linked list with no uh with no left child so how do you do that you should so this one is still current node so we have a c so current node.right is node.right is node.right is if you look at here currentnode.right is if you look at here currentnode.right is if you look at here currentnode.right is empty it is null so we set that equal to kernel dot left that means the right child will point to this guy but notice that we had current note on left that points to this guy and current node.write points to this guy as well node.write points to this guy as well node.write points to this guy as well so we have we must have this kernel down left set to none otherwise uh we don't get the right answer if you do this what that does is you basically cut this linkage yeah cut this relationship so that's uh this is a very simple problem you only have three nulls but yeah let's try to generalize this so here you have uh seven nodes total so if you look at here we first have to find this guy p the rightmost node in the left sub tree how do you do that well you initially said p equal to kernel the left so they'll be here p will be here now then you would have to use the while loop to get to go all the way to the uh rightmost node in the left subtree of one so if you had like three like all the way here you initially said p equal to current node.left then p will point here node.left then p will point here node.left then p will point here and then you said as long as p that right is not equal to none or in python it is none then you set p equal to p dot right what that does is he will move here and then all the way here like it will keep go going on and on until there is no until this is not true so in this case p dot write is not none so you so p will be here now when p is here what is p dot right in this case would be none so we exit while loop and p is here so that's how we get here and then down current node on right is here and you as you saw in here where we had p dot write equal to current node.right current node.right current node.right we do the same thing then this guy will move here and then we create this um we create this linkage now we do the same thing where we move all these left subtree to the right subtree and we do that by kernel.right equal to and we do that by kernel.right equal to and we do that by kernel.right equal to current node.left current node.left current node.left and don't forget we must set this guy equal we must cut this relationship when we do that by setting current node.left we do that by setting current node.left we do that by setting current node.left equal to none then this guy will be this linkage will disappear then we will get this okay and we have to find this guy again okay so we move current node to hit the sky and we do that by current setting current node dot current node equal to coronal dot right and then we use this relationship discard this while loop to find the p will be here and we do the same thing we move this right subtree by setting p dot right equal to current node dot right and this is what we get and we do that we do this cut this part here again here then we will get one two three four five six seven and this guy will disappear yet this guy will just move here and then we cut this linkage so this is what we get and now notice that for both node 3 and node 4 we do not have the left children so we want to be here and then our p in this case will be this guy so how do you skip all this guy we first check if cardinal.left is in this case current node on left is not equal to none however in this case in for both three and four this statement is false so if this is false then we shift current node we set current node equal to kernel.right then what that does is this kernel.right then what that does is this kernel.right then what that does is this guy will move here and it will go here and then here because current node.left and then here because current node.left and then here because current node.left is not equal to noun kernel current node will point to this guy and then we will do the same thing to find the p and then we move this guy to this guy's right child and then we move this left subtree to the right subtree and that's it yeah so um yeah so as you can see the take domain take away from this problem is that you want to try very simple model and then see if you can get an insight if you get an insight how you want to try a slightly bigger model and then try to come up with generalization this approach works in like in really pretty much anywhere in liquid problem and i highly recommend it
Flatten Binary Tree to Linked List
flatten-binary-tree-to-linked-list
Given the `root` of a binary tree, flatten the tree into a "linked list ": * The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`. * The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree. **Example 1:** **Input:** root = \[1,2,5,3,4,null,6\] **Output:** \[1,null,2,null,3,null,4,null,5,null,6\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-100 <= Node.val <= 100` **Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Linked List,Stack,Tree,Depth-First Search,Binary Tree
Medium
766,1796
1,047
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is remove all adjacent duplicates in a string in this question we given a string s which consists of lowercase English letters in this question a duplicate removal consists of two equal and adjacent letters which have to be removed from that string and this has to happen repeatedly so we repeatedly have to make the duplicate removals until s does not have any adjacent duplicates in it so finally we have to return the final string after all such duplicate removals have been made it is proven that the answer is unique we are given a string s so here in this question you can see two BS adjacent to each other so this will become a c a because you remove these two BS and again you see here two A's are adjacent so you have to remove this so this will become CA and now no more duplicate removals can be made so C A will be your final answer so that is the matching answer here now let's see how we can build the logic so now that we have the string s we iterate through the stringers from left to right and we can use the Stag data structure to build our logic so we access one character at a time starting from the beginning till the end and add those elements into the stack and check if that element is already present in the stack and then if it is present we can remove that element from the stack and finally the elements present inside the stack will be our output so let's build the stack so initially you start with a so add a into the stack now let's go for the next element you're pointing at B now we check if that element B is equal to the uh Peak element in the stack no it is not equal so add that element into the stack so stack follows the first and last out so first in last out mechanism push the elements from the top and you also pop the elements from the top so now you add that element be to the top and now you go for the next element next character is also B Now using stack. Peak so using stack. Peak you compare this element with the peak element inside the stack yes the both are equal if the both are equal you pop that element out of the stack so you remove B from the stack and you go for the next element is a you check if a is equal to the peak element inside stack Peak element is a so they both are matching so remove that element from the stack now go for the next character now stack is empty so if stack is empty you directly push it into the stack now go for the next element check if this element is present inside the stack no it is not matching so add this element from the top a will be added into the stack now we reach the end of the string so whatever is present inside the stack will be our output so here you can see stack has the letters a c but at the order of occurrence C A so you reverse this using the reverse method on the stack so you get C A as the output now let's take a look at the code so here you can see that you're declaring the stack and then you're using a for Loop Tate through the string s that is the input here now I'm accessing one character at a time and storing it into the character C now you check if the stack is empty if stack is empty push that element into the and here you're checking the topmost element inside the stack is equal to the current character if it is that then remove that element from the stack that element is not matching then push that character into the stack so this will happen for all the elements in a loop so this will happen for all the characters inside the string s and finally you building the output from the stack you have our answer inside the stack so until stack is empty you keep popping the element and appending into the string Builder so string Builder will have our output and now the return type is a string right so the string Builder is built from the stack so now we have to reverse the string Builder and then convert that into a string so this will give you a string so now the time complexity of this approach is O of n where n is the length of the string s and the space complexity is also o of n because we're using a stack to solve this question that's it guys thank you for watching and I'll see you in the next video
Remove All Adjacent Duplicates In String
maximize-sum-of-array-after-k-negations
You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them. We repeatedly make **duplicate removals** on `s` until we no longer can. Return _the final string after all such duplicate removals have been made_. It can be proven that the answer is **unique**. **Example 1:** **Input:** s = "abbaca " **Output:** "ca " **Explanation:** For example, in "abbaca " we could remove "bb " since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca ", of which only "aa " is possible, so the final string is "ca ". **Example 2:** **Input:** s = "azxxzy " **Output:** "ay " **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters.
null
Array,Greedy,Sorting
Easy
2204
1,186
it boosted like an 808 my product Cartesian this is maximum subarray some with one deletion given integer given an integer of integers given an array of integers return the maximum sum for a non-empty subarray with at most for a non-empty subarray with at most for a non-empty subarray with at most one element deletion in other words you want to choose the subarray and optionally delete one element from it such that there is still at least one element left and the sum of the remaining elements is maximum possible note that the subarray needs to be not empty after deleting one element okay so you can't just have a you can't return an empty the sum of an empty subarray okay so for this problem right we have one negative two zero three obviously we should skip negative two so we add one add zero add three we get four for this problem since we can only skip one right it's best to just choose three right because I'm never gonna get this one if I want to use this one I'm going to have to use this negative two which to get me to negative one plus three is two so it's best to just use three alone and not skip anything um in this problem I can't just choose one element and then skip an element so I might as well just choose one element alone right you can't return the sum of a empty Subaru all right so for this problem we have to choose a continuous sub array and the only kind of additional aspect is that we can Skip One Thing right so really what this problem is if I thought about it in terms of the elements like if we looked at this example here right we have these nodes one negative two zero and three okay and from any node right I can either skip it or I can go to the next node from the next note I have the choice of going to the next node or skipping and from the next note I have the choice of going to the next node or skipping right and that means that for this problem right I'm just trying to find the maximum path in this system right the maximum path in the system starting from any state right like the maximum path in this system starting from this state is here to here and then across here right and if we were to draw this uh so this makes sense right but I guess the only issue with this problem is that you can only skip once right I can use a skip Edge but I can only do that once right when I use for example this graph is almost correct but if we thought about this example right so I'm looking at example two here why did I do that right so if we look at this example well that wouldn't do it either so let's say we had this as an example here you know you may feel inclined to say okay well from any node I have the choice where I can go to the next node directly or skip go to the next node directly or s I can make this cleaner or skip go to the next node directly or skip right well then what would be the longest path in this graph well if you started from this node you could go here to here but then you could go here to here so the issue here is that this graph doesn't encapsulate the fact that I only get one skip right I don't get two skips I only get one so in this system I've already used my Skip by using this graph here so I can't skip again so this system needs to somehow address for the fact that I've already used the Skip and if I've already used the skip then I can no longer Skip and I just have to use the elements in front of me if I want to consider a maximum path so in order to do that we'll take this system of graphs right and what we'll do is create a copy of it where the copy will be the state where we've already used the skip so essentially what I'm saying is if I get down here that means I've used the skip if I'm up here that means I haven't used skip so if I haven't used the Skip and I'm in this state what can I do well I can go to the next node directly or I can skip and I can do that for every single node at the top right I can go to the next node directly and not use my skip or I can decide to use my skip in this state go to the next node directly or use my skill what about at the bottom well if I'm at the bottom I can't skip anymore my only choice is to go to the next node directly right so now this system if I wanted to find the maximum sum well if I was to try to draw this same wrong thing oh did I copy and I didn't yeah right if I try to do one to one like I had before notice that's no longer possible in this new graph because I've captured the fact that you know there's a different state right there's a state where I'm at this node and I haven't used the Skip and there's a state where I'm at a node and I have used the skip so that's kind of a aspect of these problems you should think about right it's like sure I have these states being the numbers that I'm at but is there more information that would increase the number of states well there is right because there's a state where I have used a Skip and there's a state where I haven't used the Skip and that's true for any node that I'm at this node and either I have skipped already which means I'm down here or I haven't used the skip already and that means I'm up here so if we try to make that again right notice now that we've graphed it we've modeled this graph in such a manner that it encapsulates the fact that I've already used a skip so I can't skip again so this problem really comes down to how do I model this problem as a graph such that it encapsulates the fact that I only get one skip right if I had infinite skips right then this old solution would be correct but I don't have infinite skips right I can only skip one thing so since I can only skip one thing um I have to draw it like this where that information is captured right these bottom nodes represent you skipped top nodes represent you haven't used it skip it so then this problem really comes down to just simple dynamic programming right I would look at any state I would start from the very left and I would look at any state and I'd say what's the best path ending at this state right what's the best subarray ending at this state well the best subarray let's just go through so we look at this node first we'd say the best subarray ending at this state is what well it's just itself right it would have to include itself so that would give us one what's the best subarray ending at this state again that would just give us one and then we look at negative two the best subarray ending at negative two well it'd be a terrible subarray but at least it would be greater than negative two right either the sub array is negative two itself or it's one leading into negative the best sub array ending at one leading into negative two right which is going to give us negative one right so that means for this option right I can look at this previous node and get information from that or I can just look at myself so I can look at all the arrows going into me to make a decision about what I should do um and then the same thing here right I could look at myself but I'd also get better information from one so I might as well just use that negative one okay now it's where it's going to start getting a little bit more interesting we look at one here the best subarray ending at one well if I try to get the information from this previous note right the best subarray ending at negative two that provides me with negative one so I shouldn't use that information right if I include negative two the if I include the best sub rate ending at negative two it's gonna make my score less than if I just used myself alone so the best subarray ending at this one is just one itself right what I keep doing it's just one itself so what I'm saying is I'm not including this negative 2 here because I have the choice right generally right for any node right what I'm basically saying in this problem if you have a node X and a node y the way that we're processing this system is the value at y will be the maximum subarray ending at y right so it'll be some subarray with Y in it so when the next element is X x can make the decision well if I want to include y that would mean the maximum sub array is and then I include x as well or I can just not include Y and say okay why is bringing my score down or I can just use x right so it's the maximum of these right adding an additional element it's either going to be the maximum of the sub array ending at my previous element or the maximum of just me alone so that's the general idea for that we'll keep this around because so x equals the maximum of this we're going to keep this around because in a second I'm probably going to use this generalized graphic again to prove something else okay now this is where the bottom gets interesting so remember we just calculated this saying that okay the best subarray ending at this one is just the one itself we don't want to include the best sub rate ending at the previous element because it'll just bring our score down right my neighbor should bring me down now when we look at one well this one has options right this one can use this previous subarray but that's just going to give it negative one it's going to bring its score down right it's the same case here but it also has this edge here that it can consider and that would provide it with one so the best subarray at this point would be two right because it gets one from here and it gets one here so it skips this element all right so generally what that means is if you had um an element Z here that would mean X was here right for Z the maximum of this Z here is either Z itself right just not including anything before it so that means you just choose your own element so Z equals the max of the value of Z itself I don't know why this notation's a little bad or I could skip X right maybe X is causing issues here so I could just skip X so I could take all the elements up to y and then negate X right not negate just not utilize X I don't want x is bad for my situation so maybe if I skip it so that Subaru right here right because everything up to Y is the best well is the best subarray up to why right so I set y to the best Subway up to Y so then when I skip X I get here so then I can attach myself to the best subarray up to Y and attach Z to it or I could attach myself to the best subarray up to y where y has skipped some series of elements right so these are not the same this is the suburate down here's the sub rate where I skipped some element to get the maximum Subaru ending it Y versus this is the maximum sub array ending at Y where I didn't skip an element so I can use you know I can make either of those decisions I can take or sorry at X right so I can take the maximum sub array ending at X where I skip some element I can take the maximum sub rate ending at Y where I didn't skip an element and that would mean that I skipped the next element to get here or I can just take myself okay so that's a generalized example here so that's why you get to this solution here right so for two the for this element the best thing I could do is just myself or I can skip this negative two or I can use the best subarray ending at negative two where I skipped somewhere previously and then you just go through this whole solution and I think you kind of see generally how this problem works okay so there's an for these kind of problems I like to use um obviously this is end time right because I'm just going to look at each node twice I guess and look at previous information and try to get to the solution I'm going to do a non-constant space I'm going to do a non-constant space I'm going to do a non-constant space uh which is a manner which I like to approach these problems approach the problem using dynamic programming create your entire catch using non-constant your entire catch using non-constant your entire catch using non-constant space and then see if the nature of the problem will allow you to just use a couple variables to capture the information each iteration to create a situation where it is constant space right so basically what I'm saying is use non-constant space just to get your use non-constant space just to get your use non-constant space just to get your problem working and then see if it can be tweaked to use constant space so that's a common approach that I've found um usable and just more intuitive so let's go ahead and get right into it so we need information for all the nodes twice right because there's a haven't used the skip State and there's haven't used the skip State how do they use the skip state so we'll just create that catch we'll call it d um now I'm going to make it length of array plus two just because you know we looked at this as d all right so let's look at this situation here let's erase some of this stuff let's say what's a general formula right if this is d this would be d0 this whole thing right and this would be D1 I want D1 would be this whole thing right so this is d00 d01 so generally right if we said I was here if this was I so I being an index in the array what is the value of this system here well it's going to be D at one at I equals the max of the array at I right because that's this value maybe I should have done it the generalized way I don't know and then I could take the element that comes just before me the array and I could do D at one at well what's this previous element with respect to this element well that's D of one I minus one plus this element or I could take d0 what is this element with respect to this I well this is I minus one I minus two d0 I minus two or I could do a raid eye Plus d0 I minus 2. right so that's all the information I need to solve for this one right for any element here it would be the max of itself plus the max of the previous one right so for this element if this was i d 0 at I equals the max of you know you have the element alone and then you have the element plus the previous which is d0 I minus 1. right because this is if this is I then this is I minus one so these are generalized formulas for how this is going to work so let's keep track of that and consider that when we solve this problem all right now why are we doing plus two that was our first question uh because right if we solve for this we're going to go negative two to the left so we don't want to basically over count we don't want to over reach our boundary so we're just going to kind of create this little buffer of I plus two um I we're just creating a buffer of plus two that way when you try to check something negative it doesn't wrap around and pull values just basically since I'm going I minus 2 I'm going to do plus two to create a buffer okay and then we do that for range two right because we're just creating two copies so we're gonna look at each number I guess I'll do index I and the element in the let's enumerate the array and then let's just do this formula so D of 0 at I equals the max of the element and the element plus the previous sub array so d0 error I equals the max of the element and the element in the previous position right so this is going to wrap around because it starts at zero so this will be negative one so if we have two zero buffers on the right it won't cause any issues and then if we did D1 of I what do we say that equals it's the max of the element itself the element plus skipping a preview plus this side here so that's d1i minus 1 plus element so D of one I minus 1 plus the element or D of zero I minus two so we skip something plus the element and then we just do that for each system and then at the end we just return the max of each row so we'll look at each row for D and D right because any it could end at any point right so we're looking at some sub array that ends at some point but we don't want to consider the last two elements because the last two elements are zero we never even populate those right because we go to the length of the array so we don't want to consider those zeros so we'll just do negative two here okay right if we I just so that we see what's going on yeah no that's gonna be confusing so that's fine all right so let's go ahead and submit that oh what have I done wrong here everything seems no d0 of I is the maximum of the element because it is skipping too you notice that uh what am I doing wrong here I don't know oh because I have to add the element in I can't skip the previous element right and I wrote that here I just forgot to put that here right d0i equals the max of the element and the element plus the previous element okay so good this works right so what's the time and what's the space okay so for let's say n equals the length of the array right for time we just have o of n because we just look at each element and we do a constant operation and a constant operation so we do n constant operations just o of n and then for space well we have to create this decatch array which has the size of the array uh twice so that's 2N but that's Big O of n as well so this is a o of n time o of n space but something that you'll notice right is that we only need to keep information about a few things right we need to keep information about the current iteration so we need to keep information about d0 I we need to keep information about D 0 I minus 1 right I'll call it i1 so this is I minus one so d0 I minus 1. we need Kim information about D 0 d1i sorry so that's this we need information about this here we need to give information about D1 I minus one and we also need to keep information about d0 I minus two these what five variables I guess this might be adjusted in a minute right but these five variables that's all we need to keep count of so we don't need to keep count of everything that's ever occurred since the beginning of the array that we processed just these five things regardless of how big the array is so if we can somehow keep track of just these five things for the iterations of this Loop we can make this a constant time algorithm okay so how are we going to do that efficiently well d0i minus one for the next Loop iteration becomes the max of this for the previous iteration okay the same thing with I minus one so if this was I minus 1 in the next Loop iteration or for one I minus one this will be I minus one in the next iteration all right and then I minus 2 is I minus 1. in the previous iteration but that would be I minus is that right that's why it's so confusing okay if I minus 2 is I minus 1 foreign so this can actually happen first so I'm not like intuitively thinking about the relationship between these things I'm just trying to replace using these four constant pointers or actually there's just three that we need okay and then we'll just say that the max so now we're no longer we'll just keep track of what the maximum value is so we'll just call that M and that'll be the max of definitely whatever these things are and then we'll just return that at the end and then we'll set these variables in the beginning okay so that was me just trying to kind of cram through making this constant without actually thinking about the implications fudge and the fact that I didn't think about it really screwed me now because I don't know I forgot to put this is I minus two oh shoot where did I okay here okay so let's comment this out and let's see if that works so that's me literally just trying to see if how I replace variables again I'm not thinking through ah fudge maybe I should be thinking through because I'm apparently an idiot um so the value here becomes the maximum of the element whatever I think the previous is in the element would be the same thing and the same thing now the previous skip is this previous skip and then this just becomes the element Plus whatever it previously was oh because I haven't updated what M is so m M starts at flow negative Infinity I guess all right so this is what's problematic when you try to make something constant because it's not that easy but you know you can tweak it the problem is are you going to capture everything in the interview okay so this is saying zero right but you can't skip so you have to leave at least one element so something in here causing it such that yeah so setting d0i to d01 this starts at zero so then if you take the maximum of that but that's just the previous element so well no because I had the element something here is getting updated inappropriately okay there we go so we don't need to consider that right so either the maximum of taking a skip or not taking a skip getting to the end like it's possible that you get to the end and never take skip and technically so that means that this is now oh one space so that's what I had to do to make this old one space it's much harder to read maybe someone could look at this and be like come on man you're making this really ugly but uh screw you man you don't know what I go through yeah I think I can make this one line actually so that's pretty much it for the solution if you want to stick around and watch me make this more confusing than it already is go ahead to I'm just going to make this as short as possible because I hate myself foreign and that means this can go on one line error no okay so this is technically speaking this is now a three-line solution that this is now a three-line solution that this is now a three-line solution that doesn't work but uh yeah whatever I don't care I got it right it's done
Maximum Subarray Sum with One Deletion
building-h2o
Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible. Note that the subarray needs to be **non-empty** after deleting one element. **Example 1:** **Input:** arr = \[1,-2,0,3\] **Output:** 4 **Explanation:** Because we can choose \[1, -2, 0, 3\] and drop -2, thus the subarray \[1, 0, 3\] becomes the maximum value. **Example 2:** **Input:** arr = \[1,-2,-2,3\] **Output:** 3 **Explanation:** We just choose \[3\] and it's the maximum sum. **Example 3:** **Input:** arr = \[-1,-1,-1,-1\] **Output:** -1 **Explanation:** The final subarray needs to be non-empty. You can't choose \[-1\] and delete -1 from it, then get an empty subarray to make the sum equals to 0. **Constraints:** * `1 <= arr.length <= 105` * `-104 <= arr[i] <= 104`
null
Concurrency
Medium
null
763
hey what's up guys let me just make all right hey what's up guys Nick white here I do Tekken coding stuff on twitch and YouTube check description for all my information I do the Premium Lee code solutions on my patreon if you want to reach out to me join the discord trying it back to everyone this is a partition problem called partition labels he has a lot of likes I like the problem pretty cool pretty good perfect medium problem perfect difficulty label I like this problem a lot a string s so we have a string s of lowercase letters is given so string out so we're given a string s of lowercase letters for example all these lowercase letters we want to partition this string meaning split it up into as many parts as possible so that each letter appears in at most one part okay that's a little bit confusing the way they said that but if a letter appear we want to split up the string and if a letter appears in one part it cannot appear in the other parts that we split on okay and we want to return a list of integers represent rep not representing the size of each of the parts so if we split up this giant string so that when we see a it is in only one of the parts so that means that you know we have to make sure that we split anytime after the last index of a this we have to split at least this far for the first part because the last day is right here and if we split it right here this a is going to be in a different part we can only have one particular letter in one particular part of our split so whenever we see a letter we're gonna have to make sure that the we split it after the last occurrence of it so in this example we have to split after the last occurrence of a because we have a we're like okay let's put this into one part okay well now we have to put go all the way to the end to the last occurrence right here so you'll also notice that when we add these letters in these can't be and the other parts either like B and C so for example when we see B luckily there's no bees in the rest of the string we also have to make sure we're split we're splitting after the last occurrence of B and likewise we have to split after the last occurrence of C because we have to add C eventually so this is one where it has a B and C so we add all of those it's all the from first to last occurrence of each of the letters and then the next split is here so we were like okay let's add D to the next split but now we have to go to the last occurrence of D here's one but while we were in between these two DS we see EF and G so we have to go to the last occurrence of EF and G luckily there's no more F and G so we just go from here to here so that's the second split and then the third split is right here we add H at first and we're like okay the last occurrence of H right here but now we saw I and J so now we have to go to the last occurrences of I and J which is all the way at the end so this is the last split with all of those letters only being within one particular group then we just returned the lengths of each of the splits hopefully that makes sense to you guys let me know if it didn't make sense I think I explained it pretty well oh so how do we do this well if you just think about the way that I did it that's pretty much how you solve the problem there's no like sorting or anything like that we're not doing that we want to solve this in a linear run time and we are going to you know we're gonna have we can't modify the string we're not allowed to that's you know part of this so what we're gonna be doing is we're going to like I just did in the example we're gonna add a letter to a split we're gonna say okay here's our first float we're gonna add a letter and then we're gonna have to go to find the last occurrence of that letter at least and what we want is as many possible parts so the you know most possible parts that we would want to do is if you know the all of the letters were different right for example if it was a b c d e f g h i j k if that was our input string we would split it into a bunch of groups we would do you know a is 1 then B is 1 then C is 1 but the problem with these is we can only have the letter occur in one particular group and if we split and we just did a is 1 its own group we'd have a in another group right we'd have 2 so you have to make sure that you go all the way up to the last occurrence and that's basically the whole idea here that's the problem we're gonna be doing constant space in this problem - the constant space in this problem - the constant space in this problem - the output array doesn't output array the output array doesn't count for space so first thing we're just gonna do is we're gonna say okay if s if our input string is null or if the length is null we're just gonna return null pretty standard in all of these problems just making sure we got some valid input we will initialize our output array this is not count as any space because that's we otherwise we wouldn't be able to return anything so this is still constant space is just how we're returning our output so this is what we're returning at the end the output array of the lengths of the splits right what we're gonna do here's the trick here's the whole problem we're gonna keep a map to the last indices of each character so we're gonna make a new enter a of size 26 because we're dealing with lowercase letters here and these are going to be indexes 0 representing a 25 representing Z and we are going to go through each letter and we're gonna mark down in the array at the particular index of the letter so if a is 0 we're gonna put the last end index we see a at so when we get to here so maybe this is index you know whatever it is I mean it's probably like 8 or something 0 1 2 3 4 5 6 7 8 we would wow those good guests but we would put a as the last index that we saw a act and then we could check in this array to find the last index of each letter so what we're gonna do we're just gonna loop through this array and to do this it's pretty simple actually we just do last indices of I STR at I minus a so this gets the current character we're looking at so for example a it would do a minus a to convert it to a number and that would be 0 right so we would look up zero in this array and what we would set it to is I so when we loop through it I would be 0 at first we see a at 0 so we'd give I we'd give it a value of 0 we see a again it index 3 0 1 or 2 we see in at index 2 we do okay last indices of a of index 0 then we set it to 2 we see it again at index 3 4 5 6 then we do a go to a z' index we 3 4 5 6 then we do a go to a z' index we 3 4 5 6 then we do a go to a z' index we make the value 6 until we get to the end and the last index so this array will contain the last index we see each letter at and we could access the last index of each letter just by referencing the position of that letter in the alphabet so 0 for a would get 8 back and you know for B we'd reference 1 aunt last indices of 1 and we'd get the last index of B so we just fill up an array of the last index we see these letters that which is going to be super helpful for us all we have to do now is we have to make we're splitting this into substring so we're just gonna make a starting variable and an ending variable to keep track of our substrings and we'll move them whenever we break a partition off we will add the length of it to our output array and then we'll adjust our starting and ending boundaries so that we can move on to the next substring it's that simple it's really not that difficult so we're just gonna be looping through the string once again that's don't length I plus and we're going to say and is equal to math max of n and last indices of STR at I minus a so and is the end of our substring of our current partition and we're updating it to the max of the current end in the last index of the current letter so when we see a we say end is zero and we see a and we're like okay end is max of the current end which could have just been then the character we're at and the last index of a which is eight because it is at minimum it has to get to the last index of any letter that's in our substring so we make the end automatically go to the last index of any character we're adding to our substring what if now once we get to that current position while we loop through the string so if I is equal to end we have now reached the because this will end will get updated over and over again until our substring is as long as it needs to be to have the last character of each character that's part of the substring so when we see in this case a it's really a really nice one because the first character we add is the odd you know it includes all of the characters we're gonna add in between but for D for example the last character of D goes to here but we also have an e in here so you know it'll add and we'll adjust to go to the end here but then we see an e and end will adjust again because it'll say okay last index of e so we have to make the end even go longer but once we get to the end once our loop gets up to this character and where our index of that we're looping through is equal to the end that means we've officially found a partition that is valid all of the characters in between it will not be in other partitions and we can add this to our output array we can add the length to our output array which output array dot add all we have to do is end minus start plus 1 which end and start are just the boundaries of our current partition substring and we add one just because we want the length of it not index wise so we just add that now we just have to adjust our starting boundary and starting boundary will be n plus 1 because we would we're gonna move on to a new partition whenever we're done adding the length of the current partition into our output array and that is the whole problem let me know if you guys have any questions hopefully this runs here s is equal to no bad operon type for binary operator if s is null or s dot length so is equal to 0 my bad guys wouldn't be one of my tutorials if do you know I didn't mess up what it so variable last indices this is in death I spelled it right here let's just spelled it wrong there let's make sure it's spelled right sorry I messed up a few times there you go so that is oh of N in constant space because we don't count what we're returning there's other ways to do it with linear space that are worse but I'm not gonna I didn't show you that because I feel like this is easy enough to grasp and this is the best possible solution so let me know what you guys think let me know if you have any questions I think I explained it pretty well but yeah just hit me up I can answer whatever I usually if you look through my videos I respond to the comments when people have questions so let me know I appreciate you guys for watching once again and anyone that supports me and see you in the next one bye
Partition Labels
special-binary-string
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
String,Recursion
Hard
678
1,281
hi everybody this is Steve here and I do leave code problems to go through data structures and algorithms to help people prepare for coding interviews to ace through all of the cony and system design questions today we're going through a legal problem 1281 subtract the product and sum of digits of an integer before we died me just do me a favor and hit that like button and that's going to help along with the YouTube algorithm and don't forget to subscribe to my channel and tap that little Bell notification so that each time when I publish a new video you'll get a notification instantly alright with that said let's take a look at that at this question this problem first appeared last night during the weekly contest it's the very first question of last night's contest so it's basically a Walmart question if you know the technique of okay let's take a look at that in this question first the question is asking given an integer number in return the difference between the product of its digits and the sum of its digits well what will like one example is give enough say example one will give it this number two three four right the output is 15 how do we get to fifteen we first calculate the product of every single digit of this number two times three times four we'd get 24 and then we calculate the sum of every single digit 2 Plus 3 plus 4 we get 9 so 24 subtract minus 9 is going to give us 15 that's how we get to 15 this number very Super Street voila I don't think there's any other problems could be even easier if you know the technique of how to extract every single digit if a given number so basic you will used this is a common technique I recommend any one of you guys if you new to this channel or if you just started programming or if you just started preparing for Kony interviews this is a basic technique which is to use a wire or you can use a phone basically uses a loop to and then use modular and integer division to get every single digit of a given number so we just start coding run away and there is no fancy algorithms or complex combination of data structures in this problem so we're just doing a run away so in sum well use two variables one is to hold the Sun as we are calculating we're waiting through every single digit and then another variable called a product this one will initialize it to me--one because any initialize it to me--one because any initialize it to me--one because any number multiplied by zero we cannot initialize to zero because any number multiplied by zero is going to be a zero which is minimis and then we'll have a while loop and while n is greater than zero while n doesn't equal to zero we'll just continue again every single digit so the algorithm is what just go through quickly go through a couple examples so that people can understand what's this technically I had referred to many times so say this N equals two three four how do we get like every single digit we'll use in modular tips right so in this case is going to be two three four modular ten it's going to give us four right so we get that the very right of the digit on the very right side and then after that what do we can use this two integer division by ten still so in this case is going to be two three four 234 integer division by ten it's going last twenty three right so next number it becomes when we go back into this wine loop the next number is becoming 23 so each time we can just a continue doing this so we just were just a can't one digit off one at a time one end time so next time it's becoming I just continue like this next time it's going to become like two and then next time is going to become zero so once we hit zero well Justin we're just freaking out of this while loop that's it lastly I would invest that technique very simple okay let's go back to the code we'll use another variable to we're just quite digit now how do we get the digit as I said we can just use modular this modular operator so digit in modular him some so we'll do calculate sum is just a digit two plus and then product will be multiplication well multiply the product and by best digit and then here what do integer division from this in so it's going to be him like this division first and then in the end what just to return product - son that's it that's the product - son that's it that's the product - son that's it that's the entire code I wrote kind of and were grossly just you how people understand a main time algorithm this should be like another way to make it simpler but I don't think it can be further simplified it's basically a big you could trim a few lines to combine a few lines into one line but me I'm where them is like this long as you can submit all right this seven 100% in both in terms of time this seven 100% in both in terms of time this seven 100% in both in terms of time complexity and space complexity lesson missing I don't know how accurate that is but anyway this is the algorithm to solve this problem the takeaway from this problem is basically you need you understand I'll memorize this technique if an Astra during an interview and this is a very common one just in and very helpful and anyone to extract every single digit of a given number that's it for this problem don't forget to hit the like button and subscribe to my channel I'll see you guys in the next tutorial
Subtract the Product and Sum of Digits of an Integer
can-make-palindrome-from-substring
Given an integer number `n`, return the difference between the product of its digits and the sum of its digits. **Example 1:** **Input:** n = 234 **Output:** 15 **Explanation:** Product of digits = 2 \* 3 \* 4 = 24 Sum of digits = 2 + 3 + 4 = 9 Result = 24 - 9 = 15 **Example 2:** **Input:** n = 4421 **Output:** 21 **Explanation:** Product of digits = 4 \* 4 \* 2 \* 1 = 32 Sum of digits = 4 + 4 + 2 + 1 = 11 Result = 32 - 11 = 21 **Constraints:** * `1 <= n <= 10^5`
Since we can rearrange the substring, all we care about is the frequency of each character in that substring. How to find the character frequencies efficiently ? As a preprocess, calculate the accumulate frequency of all characters for all prefixes of the string. How to check if a substring can be changed to a palindrome given its characters frequency ? Count the number of odd frequencies, there can be at most one odd frequency in a palindrome.
Hash Table,String,Bit Manipulation,Prefix Sum
Medium
2165
796
hi welcome to everyone my name is kundan Kumar today we are going to see one important question on lead code related to a string see first of all we will try to understand what is question so copied so we have given two a string C s and gold we have given two string and we need to check goal is that means this string is rotation of this string whether it is rotated that means we need to return true whether it is not rated rotated that means we need to return false this is the question so let's see how rotation happening we have given one string that is a b c d e and in first rotation what will be in first rotation this string from here to here b c d come first b c d e will come first and a will come last like this and second rotation c d e a and will sorry C D E A and B after second rotation we got this string and this string is same that means this string is rotation of this string okay this string is rotation of this string in that case we need to return true otherwise we need to return false so what will be the approach to solve this question so we are going to see we have given one string that is a b c d e right so what will be the approach to solve this question we will twice this string we will twice the first string so after twisting it will be like that A B C D E and A B C D E like this so in depth after twice we will check next another thing that is goal is available or not in the testing see guys here is C D E A and B this is available that means this string is rotation of this SG it will the uh approach to solve this question this is very easy to solve this question so now see implementation of this question so guys one important conclusion related to this question is if both a string heads different length that means both are not rotation of rotation to each other so what we will see if this string length and this string length is not equal that means we will return false so if s dot length does not cost to go dot length gold or length in that case we will return false okay now what we'll do we'll create one string and twice for testing s t r i and j string Str equal to S Plus s that means we are going to twice the s so after twisting it will Air it will store in Str variables okay and then what we will do we will check in that in the testing goal is available or not in that string second string is available or not what that means a goal is available or not then we will return to checking availability we have one method that is contents uh by using contents we can check whether it is available or not so what we will do HDR dot contents will pass the goal and it a contents method returning a Boolean value that is true or false that means if in Str goal is available means it's true if your goal is not available means it falls so it is very easy so let's see to run so guys we have successfully done this implementation and now we'll submit it so successfully guys uh we solve this question this approach this is very opposed to solve this question a bit hundred percent so guys I hope you understand well and please like this video And subscribe my channel because we will solve more question related to data structure and algorithm in future so we will meet in next video thank you guys
Rotate String
reaching-points
Given two strings `s` and `goal`, return `true` _if and only if_ `s` _can become_ `goal` _after some number of **shifts** on_ `s`. A **shift** on `s` consists of moving the leftmost character of `s` to the rightmost position. * For example, if `s = "abcde "`, then it will be `"bcdea "` after one shift. **Example 1:** **Input:** s = "abcde", goal = "cdeab" **Output:** true **Example 2:** **Input:** s = "abcde", goal = "abced" **Output:** false **Constraints:** * `1 <= s.length, goal.length <= 100` * `s` and `goal` consist of lowercase English letters.
null
Math
Hard
null
373
hey what's up guys on solving 373 find the k pairs with small list numbers okay so the idea is that you're given a raise uh number two and a sorted uh sending order and adjk and if i pair uv which consists one element from first array and one uh element from second array that will return k pairs okay end up with the smallest song so basically uh you see in this case you have nine pairs but you only need the first three of them so one two one four one six so it's three five seven okay for this one you have nine pairs but you only need the first one okay so uh the blue force will be unsquared will be the length of these timestamps at least about maybe 10 to a 10 right so 10 to 10 is so large that you cannot do with these algorithms all right but notice that the k at most take 1000 right so which means that uh you know in the worst situation right in the worst situation for the numbs one you only need you at mostly k numbers and therefore numser you have mostly k numbers so actually uh you totally need k square and you just do sort it right so your algorithm will be around k squared and log k squared and hopefully you can see this is k squared okay and your case 10 to the three right so this is possible right i mean like ten to the six or ten to seven computational are still possible okay so all you need to do is just take the minimum lens nums okay and take the pair and they just do a sword and uh and they take the first scale thing this is not the best right but the definitely can solve it i will see you guys next video
Find K Pairs with Smallest Sums
find-k-pairs-with-smallest-sums
You are given two integer arrays `nums1` and `nums2` sorted in **ascending order** and an integer `k`. Define a pair `(u, v)` which consists of one element from the first array and one element from the second array. Return _the_ `k` _pairs_ `(u1, v1), (u2, v2), ..., (uk, vk)` _with the smallest sums_. **Example 1:** **Input:** nums1 = \[1,7,11\], nums2 = \[2,4,6\], k = 3 **Output:** \[\[1,2\],\[1,4\],\[1,6\]\] **Explanation:** The first 3 pairs are returned from the sequence: \[1,2\],\[1,4\],\[1,6\],\[7,2\],\[7,4\],\[11,2\],\[7,6\],\[11,4\],\[11,6\] **Example 2:** **Input:** nums1 = \[1,1,2\], nums2 = \[1,2,3\], k = 2 **Output:** \[\[1,1\],\[1,1\]\] **Explanation:** The first 2 pairs are returned from the sequence: \[1,1\],\[1,1\],\[1,2\],\[2,1\],\[1,2\],\[2,2\],\[1,3\],\[1,3\],\[2,3\] **Example 3:** **Input:** nums1 = \[1,2\], nums2 = \[3\], k = 3 **Output:** \[\[1,3\],\[2,3\]\] **Explanation:** All possible pairs are returned from the sequence: \[1,3\],\[2,3\] **Constraints:** * `1 <= nums1.length, nums2.length <= 105` * `-109 <= nums1[i], nums2[i] <= 109` * `nums1` and `nums2` both are sorted in **ascending order**. * `1 <= k <= 104`
null
Array,Heap (Priority Queue)
Medium
378,719,2150
1,496
so the first one is pathfinding so this one given that n is only up to ten to the fourth which is ten thousand you can actually put everything in the hash table right for and because every movement is in an integer point you just have to keep track of it so if you don't know if you move X plus one if you go sub you 2x minus one and so forth and then just put everything in a hash table and then at the very end if you see the same point more than once then you return true if you don't then you could be done for us at the way and there so yeah so that's the cube one this is all N because for each node you execute you look at it once there's open space because you put in a hash table this is assuming the hash tables of one insertion and stuff like that and lookup which you could debate however you like another thing to note is that and actually I know that I said that X is plus one and X is minus one for north and south respectively but actually doesn't matter as long as you're consistent because you can think of it as that if you cut it a little bit backwards then you just flip the it's a mirror image way so I'm one of the two direction so it doesn't actually matter so you can definitely get it correct in this way so that's Q one
Path Crossing
lucky-numbers-in-a-matrix
Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`. Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise. **Example 1:** **Input:** path = "NES " **Output:** false **Explanation:** Notice that the path doesn't cross any point more than once. **Example 2:** **Input:** path = "NESWW " **Output:** true **Explanation:** Notice that the path visits the origin twice. **Constraints:** * `1 <= path.length <= 104` * `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`.
Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria.
Array,Matrix
Easy
null
230
hey what's up youtube it's bobby g your number one and favorite leaked influencer today we are doing a problem called kate's smallest element in a binary search tree if you're working on graph reversals it's a good problem to start with um before i get into the video feel free to drop us up if i get a thousand subs by next monday i'll shave my head so a little bit of an incentive uh but here's the prompt given the root of a binaries or tree and energy k return the k one index smallest element in the tree so example one we have a binary tree uh with three at the root node one left and two right and then four right at the three um and just to clarify what a binary surgery is uh each node is for example i think it's easier to illustrate so three is the root of this like binary search three everything left of this root node is going to be less than three and everything um right of it is greater than uh that's just generally how it works so three if we go left to three you see one is less than three and then we look at one we look at this is also like a mini binary search tree so this is like a sub tree and so anything right of this one will be greater than one so in this example it's two and that's basically the tldr what a vst is and right now we are trying to find the smallest element in the tree what you could do is just do any sort of graph reversal um brute force and then sort it and then get that first element uh or like you can get to that index element um but that's not the most optimal way um we're gonna go through a we're going to go through dfs in an iterative fashion and that's how we're going to get to our solution today um and then also to clarify uh in this example 314 null 2 and when we look at the smallest it means like this is the first small so it's not going to give us zero so that's the little off by one here um so when we look through this binary search three we're gonna see three uh and then we're gonna go to one and then one is the smallest element in this tree and that's the value that we're going to be returning and so how we're going to do an iterative dfs if you haven't done this before it's done with a stack and in this stack we're going to have tree nodes um and that's we're going to instantiate so far um and then the next step like i said when defining a finisher tree if you go left you're always going to get a smaller value and so kind of we want to use the stack to keep track of what the current um minimum that we've seen so far like we just want to find the most minimum value right now the way we can do that is iterate through the root node and keep going left and once we hit a null then we know the note prior to the null is the smallest value in the binary search tree so this is how we're going to do it as well root does not equal null we're gonna do stacked up push root and then root equals root.left root and then root equals root.left root and then root equals root.left um so kind of how this is gonna work we're gonna see three is not null so we're going to add that to the stack and then we're going to go um root.left and then we're going to go um root.left and then we're going to go um root.left so then we get to this one node um it's not null added to the stack and how stacks work it's just going to build it's just going to put right on top of the previous node that we just put into it and then it's going to go left one more time but that's going to be null so it's not going to push anything and then now that we have now we have a stack of one and three one being at the top and that's the smallest value in the binary search stream and so uh this first example is pretty easy because if k equals one we're just going to return the top of the stack but ideally with this inner dfs is we're going to want to always put we're always going to want to have the next smallest value at the top of the stack and how we're going to do this is while the stack is not empty we are going to take the top of the stack uh it's just the top note equals stacked up pop and then since i said um it's like kind of half by one here we're not giving like the friendly the zero smallest it's the first smallest so if k equals one then we know the stack has the top the minimum value already at the top of it so what we can just do is return top node dump them out uh but a lot of times we're not going to be given that case so um let's say we're given two in this example we're gonna have to keep um iterating through or keep doing this dfs to find this uh second smallest value and how we're going to do this is now we want to find the next um the next most value so we've seen 1 and 3 but we want to get to this 2. so what we can do is get to the right node of what we just popped off and then we're going to do the same step what we did earlier so this like iterative go left as much as possible and find the minimum and that's like guaranteeing a minimum at the top of our stack every time i think this is easier written code actually so how we're going to write this is write node equals top node.right equals top node.right equals top node.right and so while this right node does not equal null then we want to keep adding it to the stack so stack dot push because keep in mind the stack is just going to be holding our minimum most value at the top of it so we're going to put a stacked up push right node and then this is the same step kind of basically just copying code from line 24 to 27. we want to keep going left as much as possible because we want the minimum most value so right node equals right number top left in this case um when we get to this red node equals top node.right so we're going to have top node.right so we're going to have top node.right so we're going to have two so two gets added onto the stack and then one has been popped off so now two is the smallest element in this bst and then there's no nodes below it like left or right of it so it's not going to go through i guess like too much iteration and then basically now we have the next smallest element already at the top of the stack and then the last thing we have to do is keep in mind that k we have to keep updating k so rather than creating a new variable we can just modify the input parameter so we can just do k minus so if it's the second smallest and it wasn't the first we could just decrement it by one and keep doing that until we get to the value that we need i think it also mentions that this will always return a valid uh this is always a valid case so let's just return negative one here because it'll never reach here without logic um but that is entirely it this is kind of like how to do um iterative dfs and typically like there's multiple ways to do dfs and most of these problems that you'll get or you'll find on the code it's just like manipulating graph reversals so like doing you know bfs in a different manner or doing dfs where we're trying to find the smallest value in the bsc so we have to like keep we care about what's being implemented or what's being put in the stack but that's generally how to do it i'm going to submit it because you know how i roll and that's how we do it so 100 run time even though that's super inaccurate but this is an oven time complexity because we could be getting like let's say the largest let's say the method asks for the largest element in the stack and it's like the 10th smallest we're going to still have to iterate through the entirety of the or traverse in the entirety of the bst and then space is also oven because we're storing these nodes in the stack but that's essentially it if you have any questions or comments people i think we've gotten two questions before which is super huge feel free to ask below i hope you liked the video and keep grinding cheers
Kth Smallest Element in a BST
kth-smallest-element-in-a-bst
Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_. **Example 1:** **Input:** root = \[3,1,4,null,2\], k = 1 **Output:** 1 **Example 2:** **Input:** root = \[5,3,6,2,4,null,null,1\], k = 3 **Output:** 3 **Constraints:** * The number of nodes in the tree is `n`. * `1 <= k <= n <= 104` * `0 <= Node.val <= 104` **Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST).
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
94,671
1,029
hey everybody this is Larry this is the third day of the June decoy daily challenge let's get right to it hit the like button hit the subscribe button let me know what you think two cities scheduling there are two and people and company is planning generally the cost of flying i've person to city a is cause of i-20 and the cause of why i person of i-20 and the cause of why i person of i-20 and the cause of why i person this city peers it was a five support we thought the minimum cost to fly every person to a city such that exactly and people arrived at each city okay hmm so my first instinct to be honest is dynamic programming this is a sort of a knapsack basically you know that an person has to be in a and n person have to be in b and then you just kind of do you know the algorithm dear it's that and i think and my dog process right now is whether I can do better right and let's say I do want to do it with dynamic programming in this case W n is equal to 100 or yes and it's equal to 100 each causes less than a thousand so in theory a can be up to 50,000 or so for half to a can be up to 50,000 or so for half to a can be up to 50,000 or so for half of it and B can also be up to 50,000 and of it and B can also be up to 50,000 and of it and B can also be up to 50,000 and we can do some implicit things so that yeah and so that's my initial thought process now I'm just trying to think whether I is there a greedy album can I do something a little bit better mmm-hmm because so greedy albums are mmm-hmm because so greedy albums are mmm-hmm because so greedy albums are always tricky with these things for me it's particularly for me to use it's way worse for me to read is a problem to another non greedy problem and but here I don't remember that one so I'm just thinking for it a little bit but yeah maybe like maybe let's just do that way so the tricky thing on this problem as well in terms of trying to figure it out is also so a naive way of doing the dynamic programming might be just half the state of N and then the cost the total cost of a and then the total cost of B but of course in that case as we mentioned the total cost of a could be one hundred thousand and a hundred thousand square is not going to be cut it's not going to be fast enough so we have to do a little bit smarter and maybe the answer is just keep track of a and in this case we have because they have different cause that would be a little bit that might be a little bit tricky what is I don't know after I have taught my head I think one thing that we may be able to do greedy about is just instead of dynamic programming I think there's a greedy in which like each person we greedily so for each person we calculate what's the cost of so instead of calculate instead of having two numbers to calculate you know there's a cost of city a and a course of City beer which is kind of a messy concept but what we can do is represent each number as kind of the absolute we can keep track of what's the cost of putting this in a right and we could come with entire array that way what I mean by that is say that's given here in a way it's like renormalizing that's how I would think about it but instead of saying oh this is 10 but B is 20 what we can do is say okay the cause of this - to put it in a would be 10 - to put it in a would be 10 - to put it in a would be 10 well sorry would be negative 10 - the well sorry would be negative 10 - the well sorry would be negative 10 - the entire system because you have to put the person in a or b right and then in same similarity or for the second and here's causes 350 this is 10 and so forth so given that I think we can now calculate the cost of putting n people in a that's the total cost and then we just have to I mean I still a little bit hand maybe because I'm it's still a little bit hem little bit murky in my head so I think from that we should be able to use the sum of the flow of everything to figure out essentially how much the total cost should be okay so let's just say okay let's just say Delta costs just go to X minus y oh sorry a cost - because to X minus y oh sorry a cost - because to X minus y oh sorry a cost - because for a cost comma because and costs so this is just an elevator and that's just converted to a list to be sure and this is why I was it messes my intending and just test you could put Delta but this is basically for comprehension this way Java I mean sorry - e but basically what it's saying sorry - e but basically what it's saying sorry - e but basically what it's saying is that for each a B and because and cost which is each of these items we just take the doubt two of them and now we figure out and there might be a couple of things that I'm playing around with respect to really because greedy's are always a little tricky so then the next thing that I might think about is does it make sense to be greedy about the minimal cost for a or is that the minimal cost be all that but we do want the total cost for it so in that sense maybe what we actually want is not just a delta of a cost B I mean and that's what this away tells us but we want to start with the biggest difference that there is right so in this case 350 is really expensive so we definitely want to why you be first and for these greedy problems to be honest it's really hard for me to prove mathematically is a little bit tricky to prove correct without a reduction to an existing greedy bomb that I know or some property that I've just been playing around for a long time of experience but I think for here at least intuitively it makes sense even though you can say that about a lot of greedy pawns and that gets in each one of us so yeah but ok so let's actually try again I just want to illustrate that's how these are the dog process that you may think that I'm maybe wasting your time a little bit and maybe you're right and I apologize but this is actually my dog process for greedy problems this is me playing around a little bit with okay like how do I we conceptualize this problem in a way that allows me to look at it from different angles right and some of these angles are going to be a little bit not useful directly but some of these angles are allow me to be like okay well now that I wish allies to tell the cost like this well actually does it make sense I mean like initially maybe make sense to have ones negative ones only first but 350 we probably for that item it really makes sense to be put in B first and other stuff way so okay so that's kind of my idea around constructing this greedy album but of course just implementation point and implementation point you would have to just practice a lot but so sometimes my code might not come out as great the first time but let's try again so now let's just try again because in costs so now of course you go to just store a list I should even look at this but you know it's what we said it was Chris you know so that maybe we do something like I guess they could be equal but it doesn't really matter there you go and it gets soda in the back anyway because you want to sort or it's my idea would be to sort by the absolute value and if they decode then it really doesn't matter at that point way so they don't be all the way in the back cuz that's literally the lowest value you can go if you sort by the max of do the max of doing which record okay if any cost is equal to greater that then we just a pen a car or negative well so we do want to sort by minimum so but actually that's keep the same thing that we did before and then we'll just change the sorting function so that it matches more with what we because you want your code - understood - match your want your code - understood - match your want your code - understood - match your idea as closely as possible sometimes you have hacks for competitive programming but in real life you definition like cream cone but I just do a constant because and then just put it in and I was just going to say let's just put a character doesn't really matter but we also probably actually won to put in to a cos P cost just for bookkeeping so this part is not is necessarily basis for bookkeeping I think it should be okay and it else is the same thing really but it would be so actually we could play refactor distant and let's do because that's just to press a secret to a it just is the cased and we just had to be that's just equal to a and then now we can just do this right I think we might have to do some maths around and I guess it doesn't really matter because I could and what I was thinking was that I might have to do some guarding again we make sure that only n is an A and n is and B but I think it doesn't really matter in the sense that at the end agreed you have to force to just put your things wherever it goes wait so it doesn't really matter okay and now we can maybe start the degree as we implement it as we say so I start across the state and we go to sum up this cost let's just return the cost but actually I forgot a step oh I didn't forget it but let's go back and make sure we tend to step and which is we want to sort this and we do want in Python we could sort it by a key and that's said the key is equal to let you say put on element we want to sort by the negative oh sorry no the absolute value of this zero me wait and then actually that and then the negative version of that so that the larger negative numbers are in the before you could also have done just record after the value and then reverse it but yeah I'm just gonna do this as a shorthand make sure you get an interview of make sure you am able to articulate that cool so that now let's just go food it down to cost right for so now we actually don't even care about the doctor cost anymore so that just put it in on the score but a cause because oh just quote I quote best so let's just do sign in Delta cost and I just call this side don't be afraid to refactor your code because sometimes it just helps to readability and anyway it's fine okay so let's say this is a case that's let's also keep track of number of a's and numbers in number of bees you could do it in a couple of number of ways but i what i just wanted to make this a little bit this is just the way I'm going to it I guess it's my point and you could do it you know play about their implementation do whatever you feel like and makes come to post sense to you don't get int and then start to you know don't want dad don't worry about like being perfect in the beginning because you're not going to be okay so now let's just say if side is equal to a and a is less than two we have an N I guess we're not giving in so let's just say n is your copper length of course so that and a times 2 is less than n and what this is just basically saying and if n is greater than n 80 times two so well I mean that's obvious if I meant and over 2 is greater than and a kind of lovely basically is just saying that if half of the numbers on and a then that's we'll put it on a because if any has too many numbers that means we went over flow so we have to put some one big even if it cost more so then now we just do cause we're you can put this in a let's increment and a and then else this cost is equal to because and then MP you know as you can see we don't actually use this but we'll just keep in there for symmetry and possibly debugging so let's one this real quick oh no 2nd test cases ooh 650 that's not great oh I think I've got the sides wrong because if a class has take a 10 because then we want to take the big side right that's kind of maybe obvious but I just can't decide so I was instead we got the maximum answer and I think probably if degreed works so that now let's submit it well are there any edge cases that I want to consider why is this just cannot be 1 if you have cost and length this is even but I guess they were just a little bit lazy in the constraints that's okay we don't have to consider the other think that I would also something that I don't do enough one stream is to consider the overflow case and what I mean by that is int over following 32-bit ends to 64-bit in so following 32-bit ends to 64-bit in so following 32-bit ends to 64-bit in so that you have to do it in better calculation the reason why I don't do it is because in Python you don't have to but definitely in your language I would instead of thinking about it and in this case the biggest return result would be a hundred times a thousand so it's a hundred thousand which is less than you know two billion or so doubt that's way okay so those are the things that I would think about in terms of test cases but they don't apply here so I'm just gonna do another quick one in this case it should be if I look at the engine first what should it be right well it's either a is in ten plus two hundred or dirty plus 20 so it's 550 okay that looks okay that's emitted real quick Oh as quick as ooh wrong answer and that's why greedy solutions are dangerous okay oh okay so now let's take a look at why this may be the case I thought that would work actually the roundness okay hmm so the tricky things sometimes that I would say is that you may get an answer that you don't know how debug because this is just like you look at this and you're like well I mean okay at least we know what the expected answers but how do we match our current answer to the expected answer right and our algorithm and so forth and it's kind of tricky the way that I want I would say in general on how I think about it is it's trying to come up with an obvious smaller case that is wrong right so yeah so okay so we put B first so we click on 18 we put this in a No but yeah but it helps to visualize and it's go through the example a little bit the case at your wall just so that you can get a feel for things in this case we want 118 first and then we do 259 which is fair and okay but this is the least doubt to clear them back I think my question here is that so there are a couple of things with greedy way and debugging the first thing I would say about my observing an sir is that it is better than the expected answer and that means that there is something fundamentally just wrong about my algorithm in general right because usually with greedy algorithms when you're wrong usually you it's wrong in the other side meaning that your answer is not good enough because you're greedy was wrong but because our answer is lower than expected answer that means that it's possibly to implementation as well and that the greedy algorithm is it well it's not proven yet but it's more likely that your implementation as well because well some invariant is not true so yeah okay so I think III was really bad on one of the variants in wary ads and that's my fault I was shouldn't try to merge a couple of edge cases together and I did that a little bit hastily but I think that was a but that allowed me the opportunity to explain how to debug this particular bad case for greedy so I think that's it perfect maybe for you maybe if not then you should fast for it but what happened is that in this case we do not check that be that NB is less than and or half that MP is not less than half of n so in this case in this example you noticed that here's a BBB B so it was in this case it was still adding a B or adding a number to be an even probably in this case so that's why we got a better at coming for a better answer than we deserve so let's change that so else if side is equal to B and I just do it the dumb way because I think you could probably phrase this a little bit better I think now they're trying to figure out how to write this in a way that is clear without being a lot of redundancy but let's actually get it right first and then we'll think about to be tendency later I think that's what I would say so that's just to dis and yeah and then similarly just what we choose now yeah sometimes that shows you that given if your cohen quote good i don't know if you consider very good but good enough anyway you still can't make these steps because you're a little bit too fast and you didn't really examine your answer and well you reassemble your code because you like oh yeah this is that true that goes the other one because it's forced way but then sometimes because of that you don't think about the contrapositive case of well if this is not true or if this is not true this time automatically implied this and the answer must no wait and that was without doing an edge case that i was missing somebody in the educates the very basic case actually now it's just a little bit lazy and in the typing end yet and there you go so that's submitted again hopefully this is good tasha also i shep retested two example cases but I just forgot because I was a little bit watching it on the video that's okay but you get my point this is except quipped on the backs then but uh oh yeah so that's pretty much how I solve this problem so what is the algorithm well the album is going to be dominated by the sorting so is n log and space well the way that we did it was by reconstructing a new array that we saw it but if you really wanted to you can actually have we win this in a way that doesn't require extra space because the Audis like I did this side thing just to kind of make and if statement easier and even then I still messed up so that's not the point but and here you can just literally put it in the L so you do not need to O of an extra space but my algorithm or my implementation is over an extra space but you could do there's no of one space of n log n running time and you could prove that both of those things are relatively good yeah I mean this is a way basic sorting problem the greedy part I always find it little tricky so I don't know how I how you know credibly I'm saying it but before an interview this is also reasonable difficulty the trickier thing about interview question on greedy that I always find on the other side is that it's just because someone is right it's hard to tell whether they're right because they know the answer and understand the answer and be able to prove that is greedy versus they just guess and it was right we're in other type of problems is easier bandwidth but that's just like more of a lousy thing I think and like I have a like I don't know I mean I would like to get more information as possible but that's just me all right so yeah that's a it's a pretty good problem pretty interesting problem I mean I got it I made a silly mistake but it's a good thing that you practice and get those Mississippi mistakes out of the way so that next time you're like oh yeah I did this recently so let me see if nothing else you might not necessary get it white perfectly really fast the next time but the next time you do it you're like okay wait last time I did something similar let me slow down let me think through the edge cases maybe think for the if statements let me think food a logical conclusion so that I could be more sure that I'm right this time right and this is something that I do given now for example I know like knowing yourself and knowing your weaknesses like I'm a little bit weak on sliding windows because if they're off by once on which pointer and so forth way so nowadays I would slow down be like okay Larry what is the left pointer what is the right point and that's how I think about it but yeah but overall and companion programming you know these fun I mean things are like constructive eat greedy they come up all the time so you really have to just do it and sometimes you just guess a greedy and I'll be right which is why it's a little bit but that's how I feel about this pause so yeah that's all I have hope that was helpful because I even though I did not solve this immediately per se I hope that the debugging and stuff will you know show no insight about debugging in general I think debugging is one of the most important skill as a software engineer in either case and you know getting involved you know fine but you're able to see my dog process and be able to debug the code and you know less than a couple of minutes you know something that I'm proud of and happy with as well as in this case in this problem with a lot of other videos and a lot of other streams apply just gonna see hey this is how you solve this problem but you know and maybe even they do like oh yeah this is this problem is greedy because of X Y and C then you're like okay it's like how do you learn you know I want to focus on how to show you my dog process in a way such that you'd like okay now this is how to like not to say that you should think exactly the way I think but just like attacking Department having strategies to take a pause and be like okay I'm wrong here why am I walk how can I fix this how can I make things better right that's how I would think about these problems and I hope that this video helps in that regard if you liked it hit the like fun hit the subscribe and share with your friends share with your family and I will see y'all tomorrow bye
Two City Scheduling
vertical-order-traversal-of-a-binary-tree
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`. Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city. **Example 1:** **Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\] **Output:** 110 **Explanation:** The first person goes to city A for a cost of 10. The second person goes to city A for a cost of 30. The third person goes to city B for a cost of 50. The fourth person goes to city B for a cost of 20. The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. **Example 2:** **Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\] **Output:** 1859 **Example 3:** **Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\] **Output:** 3086 **Constraints:** * `2 * n == costs.length` * `2 <= costs.length <= 100` * `costs.length` is even. * `1 <= aCosti, bCosti <= 1000`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Hard
null
232
welcome back today we have this problem it's called deployment IQ using stacks implemented the first in first out queue using only two stacks they implement the queue should support the functionality it should be like push Peak pop and empty and when push pushed the element the pope removes Peak return the element at the front of the queue empty returns true if the queue is empty or not so first of all that we are implementing a queue using Stacks we're implementing a first in first out Q using sticks let's just start in into creating this one so we have first this is a data structure problem and I will say that lately this type of interviews questions become more and more famous so just be attention it's pretty easy pretty straightforward you find there is nothing it's so hard but when you go to the interview and you find that you have to fill four methods it becomes quite scary but it's not nothing to scary at all so we have the we will just have this dot data will be our array that we store in it in that and that's it we don't need more and we have the push it will be pretty straightforward so this dot data dot push it will be X all of the hot I will I can't see it hard but all of the things that we try because this will be in the pop so I will see in the pop I will say um return we should return the first element because it's a first interest out so uh I would say that this dot data dot shift so we'll have the first element however if we don't have elements at all this will give us uh um errors so I'm saying I wanna make sure that first we have Lin this dot Lin foreign otherwise we return null and the peak it will be return uh I'll use this because I will need it the return it's the peak what the peak do it turns the element at the front of the queue removes the element from the front of the cube okay so pop removes from the front and right now because it's a shift to remove from the front the P gets returned the element I guess the peak is the same oh no but we don't need to make shift we could shift it to modify and edit it zero and I will see last one it's uh return true if the queue is empty and I would say um return this data dot length and it's a pretty easy press forward and the trick that when you see like four methods maybe some people will just be afraid of the question and this was me included actually because one of the previous interviews that I have done like one and a half months ago I had a similar problem like that it wasn't easy it was a medium problem but the code wasn't hard at all but when you see a lot of functions that you have to build in the same time maybe you it's some sort of trick that you find yourself you are thinking about the four or the five um uh methods in the same time the key solution for this specific uh problems is that you think about these problems one by one if you do one by one I guess you can solve it otherwise it's really hard to solve it because you can just twist your time because it's all about time because you only have one hour or like maybe 45 minutes maximum so um that's it for today's video I hope my solution was quite good if you like my content if you like my Solutions feel free to uh to subscribe to my channel and hit notification Bell so you will never miss a video and give me a thumbs up if you don't like my uh my Approach um comment uh just feel free to make a comment and tell me what exactly you didn't like so I will make sure that I'm improving myself and I'm improving the quality of my content uh each time and if you find you have a better approach that my Approach feel free to share this approach with us so we will learn from it so that's it for this video and um see you in future problems
Implement Queue using Stacks
implement-queue-using-stacks
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`). Implement the `MyQueue` class: * `void push(int x)` Pushes element x to the back of the queue. * `int pop()` Removes the element from the front of the queue and returns it. * `int peek()` Returns the element at the front of the queue. * `boolean empty()` Returns `true` if the queue is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid. * Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. **Example 1:** **Input** \[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 1, 1, false\] **Explanation** MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: \[1\] myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is \[2\] myQueue.empty(); // return false **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`. * All the calls to `pop` and `peek` are valid. **Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
null
Stack,Design,Queue
Easy
225
1,713
hey everybody this is larry this is me going over a q4 of the reason by uh the leeco weekly contest minimum operations to make a subsequence so this one i think there are a couple of ways to think about it uh i've i think the two main solutions that i've seen um and variations within those two things um so i'm gonna go over at a high level really quickly um you know if you have trouble with it i mean i'm gonna give you keywords to kind of other problems to work on so that you do have trouble with it then um then you know uh um then those are just things that you can do so that uh yeah if you have trouble with it you can work on those problems and then you can come back to it and it will make a lot more sense um so yeah so the first thing to notice is that n is very big right so maybe the naive dynamic programming solution is going to be n squared the longest common subsequence the key thing to note is that target it contains no duplicate and that is the key of figuring out um how to solve this problem uh for a lot of people yeah and the two ways to do it i'm gonna uh go over the other way that i didn't do it first um which is transforming this problem into an l i s problem and lis is longest increasing subsequence there's a there's an n log n solution that's a little bit tricky to understand for beginners so if you're having trouble with that definitely work on other uh longest increasing subsequence problem but the idea is that okay so let's say you have you know this input or maybe even this input um you know let's say you have these two inputs uh the idea is that just changing uh okay here we map this to you know zero one two three four five and here we change all the numbers to basically what we map them to um and or not if they're not existent right so this would be one uh of yeah this would be one seven would be say negative one six will be zero uh two will be five three will be four eight will be two six will be zero again and one will be three right um so then given that it becomes uh a longest increasing subsequence problem on this array and the number of uh numbers that you have to insert is just the longest increasing subsequence or n minus uh the number of longest increase or yeah the ends of the longest increasing subsequence because basically what you're saying is that from this array um make this bigger uh from the target array we want to go from left to right and we're going to skip some numbers so essentially we want the longer you know that um and because they're unique these numbers it's not gonna um because they're unique yeah like uh all these numbers are going to be unique with respect to what it's mapping to and because of that um longest increasing subsequence will um mean that you know five just means the fifth element right and then you're trying to go from zero to five using as many elements as possible which is why the longest increasing subsequence uh solution works uh again i'm not gonna go into detail with for that for this problem um i think this is quote unquote straightforward once you make that connection and with the prerequisite that you understand longest increasing subsequence so uh so definitely train on that um the way that i did it is actually using um binary index trade and there's the same thing except for um you can also use uh what's called segment tree um which is probably the better answer to be honest because i think this is a more natural segment tree solution but i don't have a segment tree ready i don't have binary index tree ready either so i had to do it manually um so i find binary index tree easier to write but i also just have to learn segment three so that's just me um but in terms of interface you can you know do them um interchangeably uh so yeah um but yeah so for this problem what i did is okay again i have this thing here to uh map this to the lookup table and then from that it becomes a dynamic program problem of okay you know let's say this is four right um four uh you know the max number of four is that basically we want the smallest number that oh sorry we want the largest number in the same idea um except for now we want longest common subsequence and the longest common subsequence in a way the way that we're doing it takes advantage of the fact that there are no duplicates by saying okay so we start with four is going to be the first element so let's just say this is one because now we have one element that's common um seven doesn't do anything say six also zero so we have one element that's common two what does two mean right um so two we look up we see that the lookup is five that means that we want the smallest value of things that appear from here right and actually let's remap this so for this we want to say that the shortest uh let's see uh the max number of elements that um that has that includes four or six in the prefix is one um and six this is also one right um and then zero right and then two the idea is that okay two we look at five we want the max of these numbers because the max is equal to um given the prefix the number of uh characters that we matched in a maximal way right and here the answer is one so then here matching the two will give us a two answer meaning that the longest common subsequence has a length of two and then three in a similar way we go okay what is the longest common subsequence of all the numbers to the left of this which is still you know one so then now the longest subsequence that ends at three will be two um eight same thing so then this is two uh six again well this is still one this is so one well now to the left of this there's um this wait did i get this one yeah um one to the left of this is two so that means that the you know now adding one two uh and eight for example because eight what eight represents is that um you know there's a sequence that ends at eight that um that has two common characters right um and if you add how did that happen and if you add one to any of these previous sequence um then you're able to get that number as well so basically that is the longest common sequence uh solution that i got um and once you get the longest common sequence um and you get the max of this all these numbers um then the answer is just n minus the longest common because then you have to insert the numbers that are not in it and that's basically what i did and you can um you know going back to what we said uh all we keeps on doing is occurring the prefix for the min right so here for example we when we saw the two we query the prefix for all these numbers and getting the min if you do this in a naive way then it's going to be n squared because it can be like an you know zero one two three four five six and you know you look at every number every time it's gonna be n square but if you have a data structure like uh a segment tree or binary index tree then you're able to get that prefix and log n time and that's pretty much it um and that's what i did um i have um a binary index tree as i said um i do this thing where when i set it um i go up the tree and i set the max uh and again when i get it i go down the tree and i set the max um i set up the lookup table as we set to get the prefix um to kind of you know get how many elements are smaller than that and we only use this for and we can ignore elements that are not the original or not in the target array so we basically just did what we said here um this should be straightforward it took me a long time for this because um i kind of mixed up the signs i did the minimum during the contest because i was thinking um okay but then i was optimizing a harder function um that wasn't true but now you know this is good um yeah so the complexity of this for each element we you know have a lookup table and then we uh we also have a segment tree um but for each element we do uh two queries which takes log n of type like 10 log n times each so this is going to be analog n um and in terms of space of course it's going to be linear space uh because of the lookup table under segment tree um yeah that's all i have for this problem i took a long time during the contest because i was just stuck on cute three but otherwise i actually thought this was pretty straightforward and actually i like this problem a lot um i wish i did q3 in a quicker way so that i could focus on this and i think i would have gotten it quicker but uh but yeah let me know what you think um and you could watch me solve it live next i don't think i'm gonna solve this but okay yeah like well fifteen piece off this was i don't know that this is so much better but okay um subsequence of oil um usually this is just dp but obviously this is some greedy thing now um let's see might still be dp actually but this in the more subtle way i really wish i got the first two without uh the two wrong answer submissions so i think that may be good enough for a high score but uh i'm gonna drop quite a bit unless i get one somehow to do this unique dynasty thing you foreign this is two what does that mean the prefix is such that you too many this is like a segment tree thing too you now it's definitely a segment tree i don't think you could do a like i'm trying to think where i can use is it second thing it's meant such that okay you to i don't think i have just pre-written i don't think i have just pre-written i don't think i have just pre-written maybe i should pre-write it next time okay i don't know about it actually i need this you so used to writing i don't know why i changed it for this form this is kind of what i want but not really should be that plus to index it's kind of like not good i want that delta so this should be is the difference in index in the prefix so what's the men of oil wow i mean maybe i just don't know this one wow a lot of people got this one though so it is going to be a sad day for larry um put them in here is i optimize too much so what i want is something like and like someone like that actually yeah but i'm trying to reduce this function um you huh i just don't have the energy today maybe i should have set up i'm not grinding right um this is the function because it's going to be n square obviously so how do i optimize this tp i thought i could do something like this but i was wrong because you don't the reason why this is wrong is because you don't add a constant for all the numbers and i don't know how to optimize this and this one i just have legitimate have all by one issue and we have this recurrence for dynamic programming uh that's already a little bit better than the naive but um you i think i'm doing the wrong thing i can do the inverse of this probably so then we just take the max oh my come on how did i have the same type of choice something like this well it's close huh so i was really close but i think i forgot to think about it hey everybody uh yeah happy new year thanks for watching let me know what you think about this problem i had a rough contest but sometimes it happens uh so you know uh don't feel so bad if it you know happens to you either but i for me you need to be more consistent let me know what you think about this problem and whatever uh i will see you next later bye
Minimum Operations to Make a Subsequence
dot-product-of-two-sparse-vectors
You are given an array `target` that consists of **distinct** integers and another integer array `arr` that **can** have duplicates. In one operation, you can insert any integer at any position in `arr`. For example, if `arr = [1,4,1,2]`, you can add `3` in the middle and make it `[1,4,3,1,2]`. Note that you can insert the integer at the very beginning or end of the array. Return _the **minimum** number of operations needed to make_ `target` _a **subsequence** of_ `arr`_._ A **subsequence** of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, `[2,7,4]` is a subsequence of `[4,2,3,7,2,1,4]` (the underlined elements), while `[2,4,2]` is not. **Example 1:** **Input:** target = \[5,1,3\], `arr` = \[9,4,2,3,4\] **Output:** 2 **Explanation:** You can add 5 and 1 in such a way that makes `arr` = \[5,9,4,1,2,3,4\], then target will be a subsequence of `arr`. **Example 2:** **Input:** target = \[6,4,8,1,3,2\], `arr` = \[4,7,6,2,3,8,6,1\] **Output:** 3 **Constraints:** * `1 <= target.length, arr.length <= 105` * `1 <= target[i], arr[i] <= 109` * `target` contains no duplicates.
Because the vector is sparse, use a data structure that stores the index and value where the element is nonzero.
Array,Hash Table,Two Pointers,Design
Medium
null
1,877
hello everybody so in this video we will be looking at the lead code problem one eight seven minimize maximum pair sum in array so the problem statement says that the pair sum pair a b is equal to a plus b so that is uh if we have a pair of a and b and so their sum will be a plus b that is pretty common and the maximum pair sum is the largest pair sum of list of pairs so for example if we are given a list of pairs like one five two three four so the maximum pair sum will be four that is equal to eight as one five is six and two three is five so what we are given is that we are given an array nums of even length so that we can pair up all the elements all the n by two elements so we can pair up in such a way that each element of nums is exactly in one pair okay so we cannot repeat a number in another pair and the maximum pair sum is minimized and we have to return the maximum pair sum so the problem statement is quite large and i would say not that self-explanatory so let me just explain self-explanatory so let me just explain self-explanatory so let me just explain you this with some example so this is our test case number two from the example so if we index them zero one two three four five so what the problem is saying that we have to return the minimized maximum pair sum what is that supposed to mean so first of all let us just pair the elements of this array so if i pair the elements of this array i can pair this 3 with any of this element i can pair this three with five i can pair this three with four with two with four with six so that is how so if we have to return minimized maximum person what is that what does that mean that if i pair these elements so that if i pair 3 5 4 2 and 4 6 these are my pairs so the maximum sum of this pair should be minimized like here i have the sum as 410 here it is 8 and here it is also 8 but can i minimize the maximum some more that is what we have to do so i think i can what if i have a pair of 6 2 i have another pair of 3 5 and i have another pair of 4 this will give me 8 and this will give me eight here in this example we get a maximum pair sum of ten and now here we are getting maximum pair sum of eight so it is a minimized maximum pair sum that is the maximum sum of this list of pair is minimized for this array so this is what we have to do for this question so when i'll explain you uh more you will get to know what i am saying so the example was 3 5 4 2 4 6 with index 0 1 2 3 4 and 5 this was our array initially so what we can do the first approach that comes to my mind was like what i can do is i can just sort the array something like this three two three four and five and six okay and i can just i have to make the pair and i have to maximize the sum so i can just pair these two and it will give me 11 but that is wrong as there can be other pairs with which the sum is maximum but it should be minimized like it is 11 at max but it is minimum 8 at minimum it is 8 so we have to find this 8 not this 11 so it will be wrong so what we will do instead of taking these two biggest elements we will sort the array we will just sort the array and we will just consider these two elements it will give me six comma two this one will give me a pair of three comma five and this one will give me a pair of four comma four if i take another example so let me just take the another test case uh it was three five two three so if i take that three five two three test case okay so if i sort this so it will be two three five and now i pair this so two and five will give me a spare sum of seven and this will give me a trade sum of six so in the end my answer will be seven the maximum paired sum and as we can see our output is seven the steps we need to follow to solve this problem is first of all we need to sort the array sort array after that we will take two pointers uh we can also do this using one pointer something like taking i and n minus i minus one it will also give us like something i have something like this 0 1 2 3 2 4 3 this is my i and my n is 4 so for i is 0 my this value will be n minus 0 minus 1 which will be equal to 3 when my i goes here my this value will be n minus 1 which will be equal to 2 which is here and my i will always go by n by 2. we can also do this so we can do this using one pointer and we can also do this uh using single pointer in single pointer uh sorry before that before single pointer so before going into single pointer i have explained a little bit about single pointer now let me just tell you about the double pointed thing so suppose this is our array again 0 1 2 3 and 3 2 4 3 so it is double pointed is so simple i can everybody can do this so we will take one pointer here and one pointer here we will just add these two this will give me a first we will sort it so two three four one pointer here and one pointer we will add this four and two will give me eight my sum is eight and my maximum will be max of sum and maximum so now after first iteration my maximum is eight now what i did i plus i go here and j go here now my sum is six but my maximum still stays eight and i have done and this is the two pointer approach now if i go for the single pointer approach as i explained earlier my i will be here but my i will go up to n by 2 that is 4 by 2 is equal to 2 so somewhere around here or i can say n by 2 minus 1 still here so for 0 i will make the pair with and minus i minus 1 that is n minus 0 minus 1 that is 3 these two are paired for the next one with two these two are created i'll find the sum and return the maximum so now i'll just code this real quick with the two pointer approach and as i have to use one less variable so first of all i'll just sort the vector so number nums dot and so i have sorted the vector and i need two variables to store the current sum as well as to store the maximum which will i initialize to int min now i'll take and i is equal to zero and end of n is equal to num slot size divided by 2 after that minus 1 while uh i is less than equal to n what i'll do i'll mix my sum equals to numbers of i plus numbers of i'll do something like this and in size equals to n divided by 2 minus 1 because i need an in the end for this calculation and minus i minus 1 and maximum equals to max of sum maximum and after that i plus and then i'll just return max now let me just submit okay i forgot the semicolon and i'll just put a bracket here so that okay now let us run the code again so as you can see uh the test category now let me just submit the code so as you can see the code is submitted thank you for watching the video and please do hit the subscribe button if you enjoyed the video and thank you for watching
Minimize Maximum Pair Sum in Array
find-followers-count
The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs. * For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`. Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that: * Each element of `nums` is in **exactly one** pair, and * The **maximum pair sum** is **minimized**. Return _the minimized **maximum pair sum** after optimally pairing up the elements_. **Example 1:** **Input:** nums = \[3,5,2,3\] **Output:** 7 **Explanation:** The elements can be paired up into pairs (3,3) and (5,2). The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7. **Example 2:** **Input:** nums = \[3,5,4,2,4,6\] **Output:** 8 **Explanation:** The elements can be paired up into pairs (3,5), (4,4), and (6,2). The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. **Constraints:** * `n == nums.length` * `2 <= n <= 105` * `n` is **even**. * `1 <= nums[i] <= 105`
null
Database
Easy
null
111
foreign hey everybody this is Larry this is day 10 for the week of daily challenge uh yeah hit the like button subscribe button join me on Discord let me know what you think about today's forum and yeah I've been uh I have a that huge backlog of drone videos I'm going to show you this one uh you know take a few seconds to kind of guess where it is and leave in the comments and you know uh I'll mention it at the end of the video in case you have a little fun of this side game that I'm doing up a little bit uh but it is you know it is very pretty isn't it anyway all right today's forum is 111 minimum depth of binary tree so this is seems like it's going to be I mean it is a easy after all and it is a very um I'll say it's essentially a requirement of your interviewing uh and also competitive I guess uh so hopefully and if you see this and you know you're like ah this is too easy for me well what you should do then is to get a timer out I don't know this time is premium only there's actually a timer that I have in my corner uh I don't know if you could see it I guess it's actually him by my face so but anyway you know just to see and kind of um maybe take a note somewhere how long you took you know see if um you know I let's see I think like if you want to really improve on the easy thing so that you can have time for the harder things um especially in the contest then I would try to get this within five to ten minutes right um yeah that's all I would say about that one and see if you can push yourself you know and yeah uh especially I mean on an interview um I actually think this is too easy for an interview but there is some parts of it that maybe uh some interview some company I don't know if this still happens that much but some companies do a coding portion that consists of like two or three problems where they give you a warm-up one and this will be the you a warm-up one and this will be the you a warm-up one and this will be the warm-up one and the more and the warm-up one and the more and the warm-up one and the more and the faster that you finish stuff like this then the faster that you're able to you know work under actual hard one that you may struggle a little bit with or something like this right you get the idea all right let's take a look what is it minimum depth the shortest path to the new as well uh minimum depth is number of the shortest path okay I mean I feel like that's yeah I mean it's fine it's just a sort of a weird question in the sense that I don't know maybe it's usually a maximum but okay fine right uh so you can do this in a couple of ways the usual is breakfast search at that first search uh I'm gonna do it with breakfast search because it allows you to do early termination so let's get to it and what I mean by that is because as soon as you see a leaf oops as soon as you see a leaf you can um you can return right so that's why maybe that's a little bit better in this particular case but it's the overall complexity is going to be the same so yeah uh so no tab as you can type love and then yeah if no dot left and no dot right it's none then we can terminate because this is the leave and then we return depth otherwise we peel up the node enough so Q dot a pen no dot left um that plus one and of course it's not and you do the same for you know that right maybe you could even write into a loop if you're really uh you know what do you wanna I'm going to cut down on some stuff right and then at the very end I guess that's it this should never happen so maybe we're doing a search Force and that's it all right let's give a submit huh oh because that's the old note is that the input yep okay fine these things are always a little bit um I mean I guess it's my fault it definitely is but it's just like it's a is a tree with zero notes uh a tree I don't know I guess so yeah that time I finished it but today I guess I just didn't look at the uh the thing because I was like this is linear I mean as you can see even the uh the even Larry uh me uh gets it wrong sometimes so don't get too arrogant don't get too cocky make sure you know take your time and uh well speed it up and all this stuff uh that's what I have with this one let me know what you think and in case you're wondering the drum clip is from the uh The Cliffs of more unless I uploaded the wrong one in Ireland so yeah uh that do I have for today let me know what you think stay good stay healthy to get mental health I'll see y'all later take care bye
Minimum Depth of Binary Tree
minimum-depth-of-binary-tree
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. **Note:** A leaf is a node with no children. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** 2 **Example 2:** **Input:** root = \[2,null,3,null,4,null,5,null,6\] **Output:** 5 **Constraints:** * The number of nodes in the tree is in the range `[0, 105]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
102,104
1,535
hey everybody this is Larry this is day six of the Leal daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's F and the explanation and all that stuff I'm here in Sakura Juma uh and island off cargo Juma uh 15 minute fery right away uh and yeah I'm here in Japan I'm just enjoying the mountain and hope you enjoyed this background and also um yeah and also maybe let me Focus that just for a second uh and also the video and maybe I'll do a drun [Laughter] now hey everybody this is Larry uh oh wait I waited the intro I forget uh but I think I said the wrong day again uh it should be day five of the Leo daily challenge and not day six I can't count and I'm in a different time zone so that's my excuse uh everything's a little bit off and I'm not wait is it day five oh yeah it is day five right yeah okay I don't know my time zone is a little bit off everything's a little bit weird I don't know when things uh are anymore uh cuz I think in New York is just a different day but like the 6th comes out on the 5ifth so I think I just did the math weird but in any case uh yeah still hit the like button hit the Subscribe button let me know if you like these intros uh I'm still trying to figure out things myself so yeah anyway today's problem is 1535 find the winner of an away game all right let's see away this thing in the K will we okay the first two okay the larger we wins and remains at zero the smaller iner moves to the end game wins ends when okay so the naive thing to obviously do is to uh simulate it right uh meaning just to run it out and of course given that n is 10 to the 5ifth uh or maybe even more importantly maybe they're both important K is 10 to the nth you may take forever right and then you can watch other Larry in FR as you like I suppose um no but let's see well the thing is that one obvious thing maybe is that K doesn't matter that much in a way right and what I mean by that is that if um if K is more than n then you have to beat everybody and you beat everybody you're going to always beat everybody right being that's the max element I guess if that's the max element that'll be your max element anyway so what so that means that your essentially kept by n and then the second thing to notice is that um every number only has to try once right because after then once or twice maybe CU after then it should deterministic because then now everything should be fit in order and then no matter how many times you do it's going to happen well no that I'm wrong right actually I mean I thought that was the case because that's the case as like you know Things fall into place in a lot of these type of problems not this one necessarily but in this particular problem I think what happens is that well like I was saying you're eventually going to find the biggest number right I mean there's only one they're always going to be a biggest number uh especially since they're distinct that's what I was looking for just now um because they're distinct numbers distinct integers one of them will obviously be the biggest and we have the biggest number as we said before it'll be all the other numbers anyway so I think you can just simulate it once by going through the loop twice in case that um like you know like if the in a simar casee if your biggest number is the last number then you have to do it twice or something like that so I think that should be good if you have two you know if you R it twice I'm trying to think whether you need it three times but I don't think so um as long as you do that so yeah let's try I had to play around that so end is you your length of array oh and for those who stay to the end I also have an outro if nowadays um just playing around with that as well so watch the end of the video is what I mean or not I mean that's up to you but uh but you know but just playing around with stuff as I'm uh oh as I mentioned in the intro I am still in kagoshima uh just enjoying I don't know yeting a lot really but all right so okay so we set it to end if K is uh more than n and then we just want it twice m how do I want to run it tce maybe I'm just lazy okay fine so have four I in range of 2 * n right so then four I in range of 2 * n right so then four I in range of 2 * n right so then now uh so current is equal to let just say1 right and then streak is equal to zero and then now x isal h i uh if x is or if current is greater I guess there's no EOD to Great X then streak increment by one if streak uh oh yeah I was going to see like which one if they're multiple Ty workers but I guess in this case it's just the first one that wins so if stre is 0 K we return current right otherwise uh oh and I guess this is an else uh K consecutive round okay then uh I guess then the new number wins one round and current is equal to X spell current right and otherwise return1 but we'll just assert Force as well so that if our assumption is wrong then yeah expected five why 2 uh Kos you go to two H maybe I mean you know maybe I have an off by one but I get the second one's right okay fine um this should be n my us one because it cannot beat itself so I mean maybe there's an HK somewhere but it's not relating to test one but I just realized that um H what do I mean man my coding is so bad these days for some reason uh all right I mean the idea is right but all right current is negative one so the first one it should be two streus one oh H okay I see because I count this as beating the negative-1 to count this as beating the negative-1 to count this as beating the negative-1 to Sentinel value how did I fix that H okay fine I think we just okay fine uh I thought I could maybe use a good Sentinel value but I was wrong I suppose uh and also I fixed it but then I fixed it incorrectly okay cuz you didn't win anything yet all right there you go let's give it a ready yeah let's give us some oh no oh I knew that H that's why I voted this way but then I just kind of messed up whoops ah silly mistakes again uh I woulded dis way knowing that I was going to mod what did I do last time okay yeah last time I was thinking about doing out of this as well um but just a lot of silly mistakes anyway uh but yeah well it's the complexity right well this at least the complexity better than last time but it's still sad which is that it's sad that I got a wrong matter uh this is obviously linear time because you we do linear times to and constant space because well we just count to space right uh yeah that's what I have for today I think yeah um I think all the observations I already pointed out I don't think there's any Focus here but I think the idea is that you know uh just thinking through it one at a time one step at a time try to figure out how to like get the timing down right otherwise it's going if you do it sloly it's at ver well just going to be ofk which is very big but maybe even nend Square you're not super careful for whatever reasons but yeah and you can still get wrong answers for silly reasons as you saw there I was trying to do it with Conant space instead of doubling the way which I usually do and I still double the way but I just I don't know why sloppy Larry uh but yeah that's all I have for today uh you could watch me do the intro or outro now thanks for watching hit the like button hit the Subscribe button join me on disc let me know what you think about today's farm and this video and all these intros and outros and stuff uh huh okay bed light what I'm going to do uh yeah the ice cream for today is just thing same as yesterday's ice cream except for it's maybe one they other favorite um yeah let's give it a spin can you see all right let's give it let's give a oh little fat one behind me running see it whatever you have to take my word for it a brain freeze actually it was very good it's either coffee favorite or camoo favorite or something like this um super recommended anyway uh that's all I have for today I'll see you later and um oh brain freeze stay good stay healthy to good mental health I'll see yall later and take care bye-bye
Find the Winner of an Array Game
build-array-where-you-can-find-the-maximum-exactly-k-comparisons
Given an integer array `arr` of **distinct** integers and an integer `k`. A game will be played between the first two elements of the array (i.e. `arr[0]` and `arr[1]`). In each round of the game, we compare `arr[0]` with `arr[1]`, the larger integer wins and remains at position `0`, and the smaller integer moves to the end of the array. The game ends when an integer wins `k` consecutive rounds. Return _the integer which will win the game_. It is **guaranteed** that there will be a winner of the game. **Example 1:** **Input:** arr = \[2,1,3,5,4,6,7\], k = 2 **Output:** 5 **Explanation:** Let's see the rounds of the game: Round | arr | winner | win\_count 1 | \[2,1,3,5,4,6,7\] | 2 | 1 2 | \[2,3,5,4,6,7,1\] | 3 | 1 3 | \[3,5,4,6,7,1,2\] | 5 | 1 4 | \[5,4,6,7,1,2,3\] | 5 | 2 So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games. **Example 2:** **Input:** arr = \[3,2,1\], k = 10 **Output:** 3 **Explanation:** 3 will win the first 10 rounds consecutively. **Constraints:** * `2 <= arr.length <= 105` * `1 <= arr[i] <= 106` * `arr` contains **distinct** integers. * `1 <= k <= 109`
Use dynamic programming approach. Build dp table where dp[a][b][c] is the number of ways you can start building the array starting from index a where the search_cost = c and the maximum used integer was b. Recursively, solve the small sub-problems first. Optimize your answer by stopping the search if you exceeded k changes.
Dynamic Programming
Hard
null
442
hello everyone welcome to quartus camp we are sixth day of october lead code challenge and the problem we are going to cover in this video is find all duplicates in an array so the input given here is an integer array nums which said to be having duplicate numbers that is each integer appear once or twice and we have to return again an integer array that has integers that appears twice in the given input array so the thing is we have to solve this in we go of n time and constant space so let's understand this problem with an example here is a given example in the problem statement and clearly when we look at the numbers three and two are the repeated integers in the given array in general the first intuitive solution would be having a hash map that keep track of the integers and its frequencies so 3 occurs twice and 2 occurs twice and it goes on and record all the numbers ended frequencies and then we reiterate to find which are the numbers that is more than once or repeated twice would be added to our result set and finally a result would be 2 comma 3 or 3 comma 2 so but here adding the number would take big o of n time complexity and big o of n space complexity so though it is kind of an optimal solution the problem statement require us to solve this in big o of one time that is constant space complexity so how do we do it so the only way to find the duplicates in constant space is perform the operations in place without having an extra memory so how do we do it there is a certain important statement given the problem is the values in the given integer array will be in the range 1 to n so which means if the size of the array is 8 then the values are from 1 to 9. so since there is a match between the index and the values that is if the index is from 0 comma n minus 1 the values will be from 1 comma n so in this case each position will be mapped with its corresponding value if the array is sorted by using these technique we are going to find the duplicates in place this is not something new we are doing for this problem we have already used this for a few of our problems in our channel already we are just going to repeat the same idea in doing this so what are we going to do is we are going to pick each number and negate the value in that position in its corresponding position to negative value so as we update all the values to negative values the values which are positive towards the end will be the duplicate values so let's see how are we going to do it so the first value is 4 force corresponding position will be 3 why because our indexes are from 0 to n minus 1 and values are from 1 to n so force corresponding position will be 3 so we are going to update the value at position 3 to negative so it becomes minus 7 so the logic is simple we are going to update the value at the corresponding position to negative so the second number is three its corresponding position is two so we are updating the value at position two to negative so the third number is minus two so since we have to we have the positions only in positive value we cannot tape take the negative value so every time we are going to take the absolute of the value present in the array to make the process easier so here absolute of 2 is minus 2 is 2 and the corresponding position is 1 so we are going to update the value at position 1 to minus so this becomes minus 3 so the next number is minus 7 or the absolute is 7 so the corresponding position is 6 we are updating the value to minus 3. so the next value is eight its corresponding position is seven we are going to update the value at seven two minus one so the next value is two its corresponding position is one so when you go back to one to look at what is the value is already negative which means we have already found its corresponding number in the array and made it to a negative value so since this number is negative we are updating it to positive and update the value to the result 2 because at the position 2 or the index which is corresponding to 2 have value already minus 3 which means we already found a 2 and updated to negative so again the second duplicate number which is in the array is 3 the corresponding position to 3 is 2 and the value is already negative so in this case we have already found a 3 and updated the value 2 negative which means the second three is a duplicate three so we are going to update that to our result table and then the final number in the array is minus one which is corresponding position is zero when you go back to zero the number is positive so we did not find a one already in the array and we are updating it to negative so far the values are done we are now we have now found two comma three are the duplicate values in the array since the values have been already updated to negative while we are checking for the second time so hope you're understanding the solution this is gonna take big o of n time complexity as we are going to iterate the array only once and constant space as we are going to update the values in the same given input hope you understood the concept let's go to the code now so yes let's get started with the code so the first thing note is the return type is in the form of list so we are going to declare a result list so let us iterate it and update the positions to negative so here we check if the number is already less than 0 which means the position is a duplicate so we are going to update our result list with that number if not we are going to update its value to -1 so yes that's it finally we'll return the result list yeah this is it let's run and try yes so let's submit yes our solution is accepted and today's question has been stalled and runs in five milliseconds so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
Find All Duplicates in an Array
find-all-duplicates-in-an-array
Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_. You must write an algorithm that runs in `O(n)` time and uses only constant extra space. **Example 1:** **Input:** nums = \[4,3,2,7,8,2,3,1\] **Output:** \[2,3\] **Example 2:** **Input:** nums = \[1,1,2\] **Output:** \[1\] **Example 3:** **Input:** nums = \[1\] **Output:** \[\] **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `1 <= nums[i] <= n` * Each element in `nums` appears **once** or **twice**.
null
Array,Hash Table
Medium
448
1,758
hey everyone today we are solving lead code problem number 1758 minimum changes to make alternating binary string in this problem we are given a string s which is consisting only characters 0o and one and in one operation you can change any 0 to one or vice versa okay after that uh it is saying that string is called alternating if no to adjacent character equal okay 0 1 0 is alternating by listing and 010 is not alternating because we have two Z together and after all this all of this we have to return the minimum number of operation needed to convert as alternating okay so in our program statement we are given a string s which is consisting only character 0 or one let's say we are having 0 011 as our string and we have to perform some operation over this string and what are those operation we can convert any 0 to one or any one to zero so this is considered as one operation and we have to perform minimum number of operation so that this binary string is alternating it means no two zero are together or no two ones are together okay now have a look on my on our first example 0 1 0 if we have to convert this string to alternating string what we can do is we can if we convert this 0 to one it will become alternating 0 1 and in this conversion we required One open option and uh if we have to convert this one Z to alternating it is already alternating so zero number of operation will be required so for 1 one 1 if we have to make it alternating it can be done as 1 0 it means converting this 1 to Z this one to Z with two operation it will become one 1 0 and also we can do it like this converting first 1 to 0 and then one third one to 0 then one even in this case we are requiring two operation so we can return any one of these two strings okay and let's have a look over a bigger example 1 0 1 okay if we have to convert this string to alternating string so we can have two possibilities only either it is start starting with 1 and having 0 1 0 alternatively or it is starting with 0 then 1 0 1 like this because it is already given in our problem that uh the string B string is alternating no two 0 are together not two one are together okay so to convert this string to alternating string we are having two possibilities either we start with zero so first one we have zero then one 0 1 0 either we convert it to this string or we can convert it to this string 1 0 1 so to convert this given string to this first string firstly we had to change this one and then this character after that zero will remain same one is same then converted with this one to 0o this 0 to one and this one to zero it means we required five operation and to convert this string to a string which is starting with one so we required only two operation converting this 0o to one converting this one to zero so I think it is clear to us that we have to convert our given string to any alternating string with either which is either starting with zero or starting with one so the first approach is clear to us that we are going to prepare these two string these two alternating string and comparing these two string with our given string and checking like which are all the elements or indexes mismatching those will be the number of operations that is start Z and start one alternatively what we can do is we can start over our given string and check for each element so in case of string starting with zero at uh 0 1 2 3 4 5 6 at 0 2 4 6 so for all the even positions we are having zero and for all the odd position we are having one and in case of one for all the even position we are having one and for all the or position we are having zero okay so we can use this conditions to formulate our answer so let's say we are having a string one zero index one index and for zero index if it is even position for zero string if it is even position we are going to set zero if it is OD position we are going to set one let's say our start string is starting with zero in that case for zero position we will check if I mod 2 equal to 0 it means it is a even position if it is a even position and if I character is equal to 1 it means we are going to convert that 1 to zero because our zero string is this ultimately then start zero Plus+ ultimately then start zero Plus+ ultimately then start zero Plus+ and what is our one string that is equal to 1 Z so for zero position if we are having element equal to one it means for our zero string we need one operation for our one string we don't need any operation so for even position if s of I equal to 1 our start zero will be incremented else means If instead of one we are having zero here in that case our start zero is not requiring any operation in the lse case we will be incrementing start 1 ++ this will require one operation from ++ this will require one operation from ++ this will require one operation from 0 to one okay now let's see for the old index for or index means the S part of this we have are having OD index if at OD index if s of I equal to 1 it means we don't require any operation to convert to zero string we require one operation to convert to one string so start of one ++ ++ ++ else start of 0 Plus+ else means we are else start of 0 Plus+ else means we are else start of 0 Plus+ else means we are having zero here if we have zero here then we will convert for this for start zero we will require one operation for start one we don't require any operation okay so these condition we can use to for to form our answer but there is one special observation here to convert the string to start zero string zero one string zero string we required five operation and to convert that string to one string we required complement of those five operation like uh total string is seven and we required five operation to convert that to zero string and to convert that to one string we require difference of that 7 - 5 which is equal difference of that 7 - 5 which is equal difference of that 7 - 5 which is equal to 2 so it means that our start zero operation that is Operation required to convert that string to string which is starting from zero and start one operation is equal to n is the length of our string that we already know so if we know only the start zero we can directly know the start one and ultimately we have to return minimum of start zero and start one so start 1 is equal to n minus start 0 so in our conclusion for zero string at even index we require zero and at OD index we require one let's say we have string of character two 0 is our even index one is our OD index so for zero index if we have one if I modulo 2al to = to if I modulo 2al to = to if I modulo 2al to = to 1 let's say if I equal to 2 Modo let's say if I mod 2 equal to 0 that is at even position if character is equal to equal position if character is equal to 1 it means we are going to require start zero operation okay now we are at Old position and if at Old position we are getting zero in that case we are going to require start zero operation so we will perform these thing for i = 0 to n and ultimately we are for i = 0 to n and ultimately we are for i = 0 to n and ultimately we are going to return minimum of start zero and n - start of start zero and n - start of start zero and n - start 0 okay now let's quickly code this problem here we have decided that we will convert our string to this form 01 form so first of all let's capture the length and store two variables int start 0 equal to 0 and start one we don't require we will check for each character I equal to z i less than n i ++ for even position let's say from ++ for even position let's say from ++ for even position let's say from 0 to 4 if I modulo 2 equal to 0 we have even position on even position we require zero so if we encounter one we are going to convert that one to zero if s do care at I equal to 1 we are going to utilize one operation now we are at OD position from OD position if we encoun C 0 we are going to convert that 0 to 1 s do character at I equal to 0 start 0 Plus+ ultimately we have to 0 start 0 Plus+ ultimately we have to 0 start 0 Plus+ ultimately we have to return the minimum number of operation math.min start zero operation math.min start zero operation math.min start zero operation required to convert that string to zero starting string or to convert that string to one starting string we can just reduce these number of operation from n minus start zero Let's test over sample test cases on the sample test cases it is running fine now submitting the problem submited successfully hope you understood the problem thank you guys and if you are having any doubt you can comment down below I will be happy to help bye-bye
Minimum Changes To Make Alternating Binary String
distribute-repeating-integers
You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not. Return _the **minimum** number of operations needed to make_ `s` _alternating_. **Example 1:** **Input:** s = "0100 " **Output:** 1 **Explanation:** If you change the last character to '1', s will be "0101 ", which is alternating. **Example 2:** **Input:** s = "10 " **Output:** 0 **Explanation:** s is already alternating. **Example 3:** **Input:** s = "1111 " **Output:** 2 **Explanation:** You need two operations to reach "0101 " or "1010 ". **Constraints:** * `1 <= s.length <= 104` * `s[i]` is either `'0'` or `'1'`.
Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to be assigned to this number.
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Hard
null
5
hey guys Oh welcome back to the channel Sarah I just want to start off by saying this is gonna be a very unusual media as compared to the previous ones and that's because I broke the mobile phone that I was using to write illustrations and so I'm gonna be doing it on a piece of paper until I fix that or I get a new device so I met a pole and Instagram for people who watch the videos and then we're okay would be writing it on a piece of paper for now until I get it fixed so from now until then nothing really much is gonna change it's just that I'm gonna be writing illustrations and a piece of paper now so please let me know in the comments if you have other alternatives and I'll be happy to check them out so let's solve leak code five the longest palindromic substring so what exactly is a palindromic substring sir a polygenic substring is a string of characters that could be written the same forward and backward so an example of that would be level ana racecar all of those are Palance because when you read level when you write it down from the very first character L it reads L e ve L and when you go back it's the same L e VL same with a DES that's a and a going back it's a and a racecar RAC ECA or RA CEC a R so this is what a palindromic string means so this question gives you a string and you should find the longest palindromic substring in that string so how are we going to do that well to find the longest palindromic substring all you have to do is figure out the pivots it's all about pivots so what do I mean by figuring out peanuts so let's take a look at the string level it's L e ve L but if you take a close look at the character in the center that's V all the characters to the left of V and to the right of V or the same so character E is equal to e character L is equal to L so to find the longest palindrome all you have to do is simulate whether or not every character is a pivot and then spread out to find the other characters in that particular palindrome until one of those characters break the pattern I'll keep in mind that we have to do other things do you find the pivots and one of the first things we have to keep in mind is the length of the challenger's and so we specifically have to keep in mind even length Palin ships and odd length challenges so an example of an even length challengin would be an ax and that's a and an a an odd length palindrome would be level le ve o l e v e l so when you took a look at these two pal agents they have different spirits sir for the pound room for an even length palindrome its pivoted between the two center characters and that is right here so it's pivoted between the first and the second end but when you took a look at the odd length ballinger it's pivoted exactly at a center character and that's V so when we have a substring we don't know whether it's an even length or it's an odd length religion so we have to simulate both of these cases so let's say we have a poem we have a string what could that be let's say risk or level and that's our AC I hope you can see this race car level and then we should find the longest palindrome in this string obviously the answer is gonna be race car and so how do we find it right so we're gonna eat a rate through the string and then we simulate whether there's a palindrome starting between two characters or those polygem starting at a certain character so we test for even length palindromes and we test for auto lengths trousers so let's start with odd length problems so we have a pointer hair at our remember a length L engines or pivoted exactly at a character so we say for example what if there is an odd length L engine pivoted RR and then we send our as a pivot to a helper function a helper method and then we spread out to find characters to the left of our in to the right of our that may potentially be all equal to each other so then we look at a and then we look to the left of our and there is no character there and we're like ok this is not a palin trip because a and an empty string are not equal to each other so then we take a look at another case we take a look at an even case that's pivoted right here and then we look at our and a so is R equal to a no R is not equal to a so then we say ok what if the pallagen is pivoted at a and then we look at R and C or they equal no they're not equal and then we do the same thing what is the what if but pounder is pivoted between a and C we look at a and C or they equal no they are not equal and we do the same thing until we get to e so now that where it be we're gonna ask ourselves the same question what if the pallagen is pivoted at E and then we spread out we compare e oh sorry Oh compare C and the C to the right the C to the left and the C to the right and then are they equal yes they're equal so we're going to keep track of a countervail variable so we increment the counter to be let's say two and then plus one and that's the Center variable that's a pivot we might not have to keep track of that but as the algorithm speaks to us that's exactly what we're gonna do so then we spread out again and compare a and a are they equal yes they are equal and we spread out and compare R and R or are they equal yes they are equal and then we spread out and compare pal and an empty string or are they equal no they're not equal so now we know that this string right here of length 1 2 3 4 5 6 7 eels apology okay and then we continue doing the same thing and then we get to see let's say what if there's a palindrome starting at C and then we compare e and a before we get to see we have to check for a polygem that's be fitted between e and c is there a palindrome pivoted between en c or how do we know that well we have to check is e equal to c you know they're not equal to each other and then we do the same thing until we get to V keep in mind that whenever we find a palindrome we have to compare its length with the current longest palindrome that we have if at any point any one of our palindromes is longer than the previous one then we replace the value of the current polymer the current longest palindrome to the one that we find to be longer in length and then we get to let's say we're at V and then we check for E and E or they equal yes they're equal and then we check for L and L are they equal yes they're equal and then we check empty string and art are they equal no they're not equal so now we know we have a palindrome of length five and then we compare the palindrome race car and then the polygon level which one is longer than the other um race car is definitely longer then a bit level so then we set the current longest to be race car and then we're done we just return race car so that's exactly what we're gonna do we're gonna dive right into the code and I promise you I really promise you it's gonna be so easier to understand as we go through the code let me know in the comments if you would like me to clarify some things and I'd love to help you out but um yeah let's dive right into the code okay so let's write some card so as we said in the illustration we have to loop through the string and simulate checking for event and earth length palindromes but before we do that we want to check for an edge case where we actually have characters in the string so we want to make sure that the length of the string is greater than zero before looping through the string so I'm just gonna say you the string and then we're going to do that in a for loop for int I is equal to now we're going to start from 1 and then I is less than s the length and then we increment I and then here we're gonna check for even length knowledge herbs and odd length relatives as we mentioned in the illustration we're gonna have a separate helper function that's gonna help us do that so I'm just going to define that as a public aunt as an inter a and the reason why we're doing that is because we want to return two values that are going to represent the start of the palindromic string the index of the start character and the index of the end character so we could be able to pull that character out of the entire string instead of storing a whole string we could just store it start index and its end index and it could just substring that at the end of the algorithm I guess so our public aunts we call it get polishin puppet from and this is gonna take in a string s and it's gonna take an elect index and it's gonna take in right index and then we're gonna make sure that the left index and the right index are we can bounce of the strings and we're gonna say a while left is greater than or equal to zero and rights is less than a stop length and then we could spread out right we could check first of all we have to check if the character at the S cut car C character it's left should be equal to the character right so the left character is equal to the right character and what we could do is we could spread out and the mins left - - going left that way right mins left - - going left that way right mins left - - going left that way right plus otherwise if we do not get this condition else we break out of this loop and then when we break out of this group we return the left and right and this is that we have found um that's gonna be right here after this return new int and that's gonna take in left us 1 and right so why are we doing left this one so now we're only gonna break out of this loop when the left character is not equal to the right character it means that the actual power gym doesn't start from the current left character that we are at it means that the actual polygem starts one character before at the current character because that was the only character that was valid the current character that the left pointer is pointing to is invalid so we have to add 1 to the left character to the left index and then that's it and then the right character would be okay because when we do a substring I think it excludes the right rightmost character so that should be fine so we're done here all we have to do now is to declare an int array for odd and then this would be get pallagen and then we pass in the string s what else do we have to pass in for odd length halogens they're pivoted at it but it actually at an actual character right so the leftmost character would be I minus 1 and sorry I minus 1 and the rightmost character would be I plus 1 so now the pivot would be I so for the Palin jump you fanatic I figure that I this is it and for a palindrome not pivoted at I this for even length palindrome that's even and that would be gets and then we pass an S instead of I minus 1 now we want to set the pivot between I and I plus 1 that's the pivot that's where other people it's gonna be I'm sorry between I minus 1 and I so we pass an I minus 1 and then the reckless character would be I so for Bellingham pivoted between it's an I minus 1 and I so now that we have those two results what we have to do is to compare the length of these two and determine which one is longer than the other so how do we compare the length of those two I'm just gonna declare an integer called odd line that's the odd length and this is going to be the integer add index one of our that's the rightmost character - the index of the rightmost character - the index of the rightmost character - the index of zero and this would be the length of the odd string and then we do the same thing for even line between even one - for even line between even one - for even line between even one - even zero so now that we have these we have to determine which one is longer and the other so um let's we might have to declare another variable Holyk and longest is equal to sir if this is gonna be an integer array longest and what we could do is we could say we could compute the difference between the odd length and the even length and depending on which one is longer we assign that to this longest variable so that could be something in the ranks of we could do an e phix pression so we could say odd there's greater than odd length greater than even length Adlon greater than or even then if this is the case and then we return alt for this otherwise we return even and then that's it outlined greater than even when written odd otherwise return even okay so now that we have the longest substring what we have to do is we have to compare it with the current longest that we have but remember we did not declare the correct longest that we have so in that case I'm going to declare on a strength called Chi longest car longest and that would be equal to the first character on character at i sorry strength value of e the value as the character at I and then yeah now we can compare the length of our Chi longest Bellinger and the longest palindrome that we've seen so far and that would be so if current longest the length longest length is greater than the length of this longest bellingham here and that would be longest of 1 minus 1 goes to 0 when this of 1 minus longus of 0 and then we set current longest to be the current Lanka otherwise we set it to be this substring I feel like this could be an AIF expression so we could just set current longest is equal to this guy right here curl longest greater than longest if this is the case and then we could return mmm longest otherwise we're gonna return ask that substring it's a strangelet substring certain index that would be longest of one sorry longest of 0 and longest of one so now that we have this the end of everything all we have to do now is to return our current longest and we're done so here we return current locusts and here alse if the string is less than or equal to zero characters what we can do is we could just return the exact same string that we were given because that would be the longest palindrome in that thing keep in mind that an empty string and itself is a pallagen so that's that I'm just quickly going to go through for Eris and see whether we can run this so this should be 0 instead of i/o coal it was accepted I feel like of i/o coal it was accepted I feel like of i/o coal it was accepted I feel like these guys could be in one line so instead of um odd line - even line all instead of um odd line - even line all instead of um odd line - even line all we could do is we could copy this and replace it with this and then we could copy even Len and replace it with this and then we could get rid of this get shorter lines of card and run and it was accepted and I'm going to submit this yay it's faster than 69% of the yay it's faster than 69% of the yay it's faster than 69% of the submissions work ever not bad and this one's okay with space I guess it's not as bad as our previous questions that we've solved in this channel so now for a time and space complexity of this algorithm let's look at exactly what we were doing so what exactly did we do we iterated through the string and one loop that's an O of end time and then we also called this function here that had to eat right through the string again it had to eat right through this ring this time with the wild look sir I'm gonna say it's o of N squared time just because we're doing an O of an operation inside of an O of an operation and depending on the length of the string like this on this loop get pallagen this guy right here it could go up to the entire length of the string guys depending on whether or not it's a pallagen so say for example you were given a pail engine level and you pass in V as the pivot you're gonna go through the entire length before breaking out of this loop so that's another event operation so I'm going to say time complexity is all of n we don't have a phone to write that down so does that say time is equal to o squared how could I do N squared I'm just gonna do this and where space complexity we're not storing anything space complexity is o of 1 if we would have stored the current longest drink every time oh I think we are yeah we are storing the current longest ring and this what would be the maximum length of this would be O of n since space complexity is not olive-oil don't quote me on that olive-oil don't quote me on that olive-oil don't quote me on that it's all of now if you wanted to make the space complexity if you wanted to make it all of one space instead of low-end space or of one space instead of low-end space or of one space instead of low-end space or you could do is you could keep track of only the indices of this substring instead of keeping track of the entire current longer substring that we've we failed to do that here but in the future take that as a challenge and then do it but this algorithm can be a very easily optimized in space to be over one space so that's it for this video guys I hope you find this video informative and if you like this type of content please consider subscribing to the channel and share it around the community also comment down below let me know if you think there are ways we could have made this algorithm work better and if there are other ways to solve this question let me know in the comments down below and smash the like button for the YouTube algorithm and I'll see you in the next video
Longest Palindromic Substring
longest-palindromic-substring
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`. **Example 1:** **Input:** s = "babad " **Output:** "bab " **Explanation:** "aba " is also a valid answer. **Example 2:** **Input:** s = "cbbd " **Output:** "bb " **Constraints:** * `1 <= s.length <= 1000` * `s` consist of only digits and English letters.
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
String,Dynamic Programming
Medium
214,266,336,516,647
1,463
hey everyone welcome back today we are going to solve problem number 1463 Cherry pickup 2 first we will see the explanation of the problem statement in the logic on the code now let's dive into the solution so in this problem we are given a grid and two Bots right and the bot one will be at the top left corner and Bot two will be in the top right corner in the grid so each cell has the number of cherries and the values in each cell represents the number of cherries so there are certain conditions so what we have to do here is that we need to use these two Bots to pick the maximum number of cherries in the grid right to pick these cherries there are certain conditions so the Bots can move in a way where the first bot can move to the right and second bot can move to the left simultaneously right another condition is that the bot one can move to the right and where we can keep the bot two constant without moving right next we can move both the bots on the right direction so whenever we move these Bots we can pick the cherries and if the Bots are in the same cell only one bot can pick that particular cell's cherries right so whenever the bot pick the cherries from the cell that particular cell becomes empty right so we just need to sum all the picked cherries and we need to find the maximum number of cherries collected by two bots so now we will see how we are going to do this so to solve this problem we are going to use DFS approach right so here we have calculated the rows and Columns of the grid so here we have two rows and three columns so initially we are going to pass rc1 so here rc1 represents the column of the robot one right then rc2 represents the column of the robot 2 so initially here the robot one will be at the zero index zero column so we are going to pass zero here and for the rc2 the robot two column will be the last column right so here we have two right so we are going to pass two here which is nothing but column minus 1 is going to be 2 so we are going to pass this one for the rc2 right and this particular row will be helpful to keep track whether both the Bots reach the bottom row or not right when we reach the bottom row we have to return back so initially this also will be zero so now we need to calculate the cherries that both the Bots can collect right at the starting stage so first we need to check whether both the Bots are on the same cell if this particular condition is true we just have to add the cells value only once right we just keeping that as my current Cherry value right else if both the Bots are in different cell we just have to add both the cells value and that will be the current cherries collector right so as of right now both the Bots are in different cell so cherries will be five here so we can keep cherries as five so the five comes from the bot one is at on the top left so 3 plus the B two is on the top right corner which has two so it is becoming five here right so here we are going to have two Loops the first Loop is for the first bot and second Loop is for the second bot right so the two Loops are going to range from rc1 -1 to rc1 + 2 so going to range from rc1 -1 to rc1 + 2 so going to range from rc1 -1 to rc1 + 2 so here rc1 is 0 And1 will be -1 and rc1 + here rc1 is 0 And1 will be -1 and rc1 + here rc1 is 0 And1 will be -1 and rc1 + 2 right so here we're going to have two here then we are going to have rc2 -1 so here then we are going to have rc2 -1 so here then we are going to have rc2 -1 so rc2 is 2 so -1 will be 1 and rc2 + 2 rc2 is 2 so -1 will be 1 and rc2 + 2 rc2 is 2 so -1 will be 1 and rc2 + 2 will be 4 so what these arranges are so by doing this we are considering the cells for each bot current position cell left cell and right cell right so here if it is1 we are going to come out of the loop right so this is not going to work1 is out of bound right so then it will be zero so it will start from zero then it will be one so by this we are also avoiding the last cell since the last cell will be already calculated using the bot tool similarly you can consider it for the second Loop so then if we are not out of bound of the grid we will take maximum between the Maxi so here Max c will be our final output where we going to keep track of the maximum cherries collector so we'll take maximum between Maxi and we will apply DFS so we are going DFS right we have to reach the bottom row then we have to come back and calculate right so then we are moving to the next row so here nc1 and nc2 represents the column values that we are going to get from the loops right so when we reach the end we will be adding the maximum and the current Cherry value and we will return right so we have to do this for all these stages that's how the logic is now we will see the code so before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future also check out my previous videos and keep supporting guys so initially we are calculating the rows and columns from the grid right so here we have the DFS function where we are going to pass the row rc1 and rc2 So within that we have the if condition so if we reach the bottom row we have to return zero right then we are going to calculate the cherries that are collected so if the both the Bots are in the same cell we will be just adding the current cell value else we will be adding the cell values of both where the Bots are located right then we are initializing Maxi as zero then we are writing the two Loops where we are going to iterate for both the Bots right so then we have the if condition to check whether the Bots are going out of range then we are going to take the maximum between the Maxi and the DFS functions return value right then finally we need to add the Maxi and the cherries and we have to return that so that particular value will come to this a DFS function which is within the maximum function right then finally we need to return the answer that's all the code is now we will run the code as you guys see it's pretty much efficient thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future not to check out my previous videos keep supporting happy learning cheers guys
Cherry Pickup II
the-k-weakest-rows-in-a-matrix
You are given a `rows x cols` matrix `grid` representing a field of cherries where `grid[i][j]` represents the number of cherries that you can collect from the `(i, j)` cell. You have two robots that can collect cherries for you: * **Robot #1** is located at the **top-left corner** `(0, 0)`, and * **Robot #2** is located at the **top-right corner** `(0, cols - 1)`. Return _the maximum number of cherries collection using both robots by following the rules below_: * From a cell `(i, j)`, robots can move to cell `(i + 1, j - 1)`, `(i + 1, j)`, or `(i + 1, j + 1)`. * When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell. * When both robots stay in the same cell, only one takes the cherries. * Both robots cannot move outside of the grid at any moment. * Both robots should reach the bottom row in `grid`. **Example 1:** **Input:** grid = \[\[3,1,1\],\[2,5,1\],\[1,5,5\],\[2,1,1\]\] **Output:** 24 **Explanation:** Path of robot #1 and #2 are described in color green and blue respectively. Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12. Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12. Total of cherries: 12 + 12 = 24. **Example 2:** **Input:** grid = \[\[1,0,0,0,0,0,1\],\[2,0,0,0,0,3,0\],\[2,0,9,0,0,0,0\],\[0,3,0,5,4,0,0\],\[1,0,2,3,0,0,6\]\] **Output:** 28 **Explanation:** Path of robot #1 and #2 are described in color green and blue respectively. Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17. Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11. Total of cherries: 17 + 11 = 28. **Constraints:** * `rows == grid.length` * `cols == grid[i].length` * `2 <= rows, cols <= 70` * `0 <= grid[i][j] <= 100`
Sort the matrix row indexes by the number of soldiers and then row indexes.
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
Easy
null
442
Hello volume is going to appear are very famous question find duplicates in the great so before solving the question we will see the problem once what we have to do in this then our personality problems are 432 with 89 and in this we have to point dry fruits like spa But if we see, here it has happened twice, so one topic was our yoga and one more was ours but it was done here also and one is given before the last index, you will have top athletes here, two and three were basic. It is given in a way that we have to find dominated and in the option given that any one of these teachers will play it once again then I and that means there will not be any elements of fear. The second example is that each one Friends, the depleted one will remain open and if there is no one in the last one, then we will return the one who is empty, so understand that it is on my God that 12 or this one can be got from Diwali Sambhal. Aphoto, I have the elements. Four left side and three grains are 2018 and three are 25 and favorite ok then find, leaving this question aside you can solve it, first see we have a method in which we can start the frequency of the element and whatever. The frequency of the element will be more than one, it will be voted but I will be a little bit hard to activate but we will take it in a good way, first of all we will start these elements and start developing the funny land into an interesting hotel, then after folding it will be something like this It will be seen, I will do it, sit one, we have two, that is twice, we have come out, okay done, our one is done, this is twice, we have been sad, tan and this is three, twice, I have exactly them - 83 and I have exactly them - 83 and I have exactly them - 83 and one more. 304 A 506 So put this green chilli four five and six So the doctor and we can see that the elements which are now duplicated in our stomach elements and inside our are by name heaven that fifth season so that can three If we can see it, then it means from common sense that we have one, O Dayawan, if we set the alarms from suit cricket, then we will be able to find similar elements and duplicate elements, then all we have to do is make a call, the American President will set the foot. From Gya to Gya, we will remain with post element and Tubelight element and mix that every time we will check that if any element is equal to its next one, if it is equal then we will understand that yes, this is a duplicate element, then name those elements in the same way. We will keep checking Means the basic idea is that first of all we have to fold the face and after softening all we have to do is any element to its next element any element to that in this case to that is equal to cement. If it is then it means that duplicate elements have good place for elements can be easily stored inside any person and if the government turns Bigg Boss, then this is what we should always do first in the court case and not in the country. After we do it in this way, time complexity is there and okay so all this is cold, I will give the link of the code and the problem in the description box below, from there we can mix it, so according to the court, first of all we are, first of all we have to give our That but by crushing it you start this remedy function should not be Kumar name start festival, this line is supporting it from the starting element till the last element of your weakness basically, that means our if given like this four days two If one, two or three passes are there then now this unsupported shirt is being used to fasten it. What will happen with this formula is that our Jio SIM element center is a duplicate element, Bhopal. Welcome, otherwise we will share ours, we will make a waste, we can also make ours but we We are making paste by making them criminal and cover them a little, so we can ask something to correct the elements and if we are reminder for Titanic, we will have to weigh the memorial, the code is there and saida, you have used inverter here and see its weight while sitting in it. We will have to use it because the return time is the better intention of this so we have made a batter and this which means the result in this we will start our unwanted element then initially all mp3 will have come if hmm if there are no duplicates in any case. We will have to return that blank, so Salim had declared it lower, not like this etc. Sir, so we cover, our name has become soft, meaning it has come in this photo, now what do I have to do, I have to like the syrup element, you will do it. What is happening with this is that we are checking what is the name white element, is the IS element equal to its next element, so in this case one and we have run this on the route from this zero to i - through the bank itself. - Speaks is zero to i - through the bank itself. - Speaks is zero to i - through the bank itself. - Speaks is its revision like we will turn on the airplane mode. Overall this is so we are checking this one. If we have this sentence then it is a question then like we will call it Index of Voting this is the contest. We will check the next one. Correct. And if we run its glass element Farooq then it will do its next World Cup tea but we do n't have lovely element now so we are doing this look by only adding I-One element, this look by only adding I-One element, this look by only adding I-One element, so we called it I- so we called it I- so we called it I- One limit is run and we are checking whether any element is equal to its next one or because after softening then its digester will be destroyed if any will be a difficult element so if yes then it is such that element is equal to its next one. By this we will make this result better in India, we will make that element happy, we will put the means in it, how will it work, this one result of ours is better, in this we will ask him, at this time, the stand big flower and the two operations that are done. We are going to do them, we will do that, meaning after this, there will be two in the beginning, so we will put two here, after that, this 313 will also come, we will soon like this page, what is the element, if you go equal to garlic, then I 320 If you do something, then as soon as the limit is reached, within the better. Okay, keep doing this and in the end, if you return this result, then I will write it down quickly, first of all, we are going to support it by folding it. Hey Ko. Or the waiter can say, after that, he called for folding, the delegates elements will now come close to each other, so what we have to do is that you are creating the result batter in which we are going to start this duplicate element of ours, this is what we have done one Formed from where to where from zero to tan - Formed from where to where from zero to tan - Formed from where to where from zero to tan - 151 - become because what we have to do for hydration so 151 - become because what we have to do for hydration so 151 - become because what we have to do for hydration so if we have if so if we have reached here then we can do its coming that but if the class element is contra voucher we cannot do And we will add in the last that we will do something with the result of checking, store it and friends, we will close the result in and we can complete it on time, then the time must have been set that we are running only one more form. Where was whatever is going on from things to MS Word, then it may be because of this that this time is complex and off, inside this, it is difficult for this video. Like the video, subscribe to the channel and share it with friends. Thank you.
Find All Duplicates in an Array
find-all-duplicates-in-an-array
Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_. You must write an algorithm that runs in `O(n)` time and uses only constant extra space. **Example 1:** **Input:** nums = \[4,3,2,7,8,2,3,1\] **Output:** \[2,3\] **Example 2:** **Input:** nums = \[1,1,2\] **Output:** \[1\] **Example 3:** **Input:** nums = \[1\] **Output:** \[\] **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `1 <= nums[i] <= n` * Each element in `nums` appears **once** or **twice**.
null
Array,Hash Table
Medium
448
24
welcome back to algojs today's question is Elite code 24 swap nodes in pairs so given a linked list swap every two adjacent nodes and return its head you must solve the problem without modifying the values in the list nodes only the nodes themselves may be changed so in example one we have converted this linked list so we have one two we've swapped those values two to one three to four has also been swapped to four to three and then we need to return the head so we need to return this value here so the question itself is pretty intuitive as to what it's asking the solution however is a bit more tricky with most linked this if we're modifying in place we're going to need some kind of dummy node right so we're going to have a dummy which we can just set as -1 have a dummy which we can just set as -1 have a dummy which we can just set as -1 it doesn't really matter what value we set it as but we need this value as a kind of reference to return dummy dot next towards the end so when we've completely modified this we need to return dummy.next which will be the head return dummy.next which will be the head return dummy.next which will be the head but also initialize this as previous and we're going to point this to our head so this is head.next this is head.next this is head.next so in order to reassign these and to flip the two values one and two we need to alter this Arrow this arrow and this Arrow right here and then we'll move along to the next sequence of nodes to do the exact same thing so how we're going to go about doing that well as you can see in the answer 2 is pointing to one so firstly we need to reassign our previous value to equal this value this has now been removed it's now been changed then we need to reassign head.next to this value here we've reassigned that value now so we can remove this array now there's an issue here we've reassigned head.next reassigned head.next reassigned head.next this is no longer head.next okay this is no longer head.next okay this is no longer head.next okay head.next is now here head.next is now here head.next is now here so we've broken that but we still need to change this Arrow to go back to one so rather than changing head.next so rather than changing head.next so rather than changing head.next to this next value we need to create some references so let's call this pointer1 and let's call this pointer two so now pointer1.next goes to p2.next and so now pointer1.next goes to p2.next and so now pointer1.next goes to p2.next and we still have head.next at this node now we still have head.next at this node now we still have head.next at this node now we can update head.next to equal head we can update head.next to equal head we can update head.next to equal head so head.next points to head so head.next points to head so head.next points to head and we have removed this Arrow right here so that's the first step we declare some values so prev dummy head P1 P2 head.x we swap those values head P1 P2 head.x we swap those values head P1 P2 head.x we swap those values so now we have Point into four so as you can see we're getting closer to the solution but now we need to reassign the values because at the moment dummy is here private's still here head dot next mp2 are here head and P1 are here so this is the next step to reassign these values now the next part of this link list that we need to adapt is from here across so the previous value here needs to be updated to this value here so previous becomes P1 and we need to update the head to equal this value here so head is going to be P1 dot next now we can remove these values and we can reassign them so head.next is going can reassign them so head.next is going can reassign them so head.next is going to be here P2 is going to be here P1 is going to be here and now we can repeat the process so previous dot next is reassigned to P2 so we've swapped that value so we've removed this pointer 4 is pointing to null so the end of the link list so now P1 dot next points to p2.next so we can remove this points to p2.next so we can remove this points to p2.next so we can remove this and then P2 dot next is going to point to P1 and we can remove this and as you can see all the link list nodes are now pointing to a value it's new value so we can write these out so now that we've swapped the values we have this we need to reassign these variables so previous needs to be the previous value of the next sequence of nodes that we are going to swap so previous becomes head then becomes p1.next then becomes p1.next then becomes p1.next and then we can reassign head.next P1 and then we can reassign head.next P1 and then we can reassign head.next P1 and P2 and as you can see head is at null head.next will be at null so we can exit head.next will be at null so we can exit head.next will be at null so we can exit this Loop and then we need to return dummy dot next because this is going to be the head of this link list so that's basic understanding of how we're going to go about solving this linked list time complexity for this one is going to be of n where n is the values of the nodes within the linked list and space is going to be of one because we are mutating the linked list itself so let's start off by creating those variables so dummy is going to be equal to new list node minus one we're getting this node from up here and we're giving it a value of -1 this and we're giving it a value of -1 this and we're giving it a value of -1 this is an arbitrary value it could be 10 it could be 20. it doesn't really matter then dummy dot next needs to point ahead and we need to set previous to equal dummy right so we're going to be updating previous here we're going to leave dummy pointing to the head so that we can reference it at the end so while head and head.next head and head.next head and head.next are available so they're not equal to null we can carry out this Loop so we need to declare P1 which is going to be equal to head P2 which is going to be equal to head.next which is going to be equal to head.next which is going to be equal to head.next then we need to swap these values so prev.next is going to be equal to P2 P1 prev.next is going to be equal to P2 P1 prev.next is going to be equal to P2 P1 dot next is going to be p2.next dot next is going to be p2.next dot next is going to be p2.next and p2.next and p2.next and p2.next is going to be equal to P1 then we need to reassign previous and head so previous is going to equal P1 and head is going to equal p1.next and head is going to equal p1.next and head is going to equal p1.next and then what we need to return is dummy.next dummy.next dummy.next so now we created at the start we need to return its next value let's give this a run submit it and there you go
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) **Example 1:** **Input:** head = \[1,2,3,4\] **Output:** \[2,1,4,3\] **Example 2:** **Input:** head = \[\] **Output:** \[\] **Example 3:** **Input:** head = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the list is in the range `[0, 100]`. * `0 <= Node.val <= 100`
null
Linked List,Recursion
Medium
25,528
337
and today we're gonna working on it question number 337 house robert part three uh the thief has found himself a new place for his theory again okay and there is only one entrance to this area called route besides the route each house has one and only one apparent house after a tour the thief the smart thief realized that all the houses in this place form a binary tree interesting it will automatically contact the police and the police if two directly linked houses were broken into on the same night so basically what we need to do is like we need to now return the maximum amount of money the thief can drop without alerting the police so we cannot actually uh directly we cannot have uh and when looking for the greatest sum or the maximum sum uh we cannot have uh two nodes uh in the answer uh which are directly connected so three two is not possible three is not possible so it's going to be one layer and the next layer so because the two well it could have been like uh if you're looking at the root three it could have been that if the one is not there on the right most leaf it could be still be like we could still have used the right node of three which is again three and the left node uh of the right node of two which is three so we can have uh the consecutive level but they should not be connected together so for this one uh the way we're gonna be doing it is like we're gonna have uh we're gonna call uh we're gonna basically divide it into a sub problem okay so we're gonna divide it into a sub problem and then now we're gonna divide into a sub problem uh for that we're gonna uh we're gonna so every our helper function is basically gonna send us like two elements so we're gonna call it result and now for the uh in the result array we're going to call this robbing sub problem uh with the root and in the end now we're going to be returning whichever so this uh this rob sub is going to be returning two elements so we're gonna be finally and then we're gonna be returning the maximum value uh between that rest0 and result one okay now then we're gonna have let's define this as a problem it is returning uh rob sub and then node uh root so basically the way we're gonna be calculating it is like if it is if you have reached uh again we're gonna be recursively calling this function and if you have reached the null node the root is become equal to null we're going to be returning to empty elements like two elements with the value zero so we're gonna be returning return uh new and two okay both of them are zeros so that okay so that's the first thing then in order to calculate uh we're gonna have a left uh result uh when sending the left child to this rob sub root dot left similarly we're gonna have a right now write result then sending the root dot right uh and then we're gonna initialize our uh result we're gonna have new end with two elements in it okay now the way we're going to be calculating these two elements every single time is it's going to be result 0 is going to be the it's going to be the sum of the maximum of the math.max math.max math.max of left of zero and left of one plus math.max math.max math.max of right zero and right one that is one thing and the other one is going to be result one which is going to be equal to the root uh dot value uh plus on the left of zero and uh and remember the left uh the zeros and them uh they are already put in the zero one so all you need to do is to get the zeroth one when you are adding the root value so that would be right of zero they are already being put in the first element uh in order to calculate the maximum between the left and the uh the zeroth and the one uh one so the zeroth element in the first element uh it's always already being pushed to the uh the zeroth element so all we have to do is to left of zero and the right of zero and then we're going to be returning that result okay rig hd looking good and it passed all the test cases
House Robber III
house-robber-iii
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`. Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**. Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_. **Example 1:** **Input:** root = \[3,2,3,null,3,null,1\] **Output:** 7 **Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. **Example 2:** **Input:** root = \[3,4,5,1,3,null,1\] **Output:** 9 **Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 104`
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Medium
198,213
380
hello everyone Aaron here and welcome back to lead code today we are doing the insert delete get random order one problem very catchy implement the randomized set class such that randomized set initializes the randomized set object makes sense insert the value returns a Boolean this inserts the item Val into the set if it's not present return true if the item was not present and thus must have been inserted or false otherwise remove the value from the set if it's present returns true if the item was present false otherwise get random returns a random element from the current set of elements it's guaranteed that at least one element exists when this method is called each element must have the same probability of being returned you must implement the functions of a class such that each function Works in average order one time complexity okay let me just uh okay so my immediate thinking is we have to be time efficient we don't have to be space efficient we can be pretty wasteful here um how can we do this well okay almost all of this is very similar to a python set so self dot items is a set insert something into the set um if Val in self items return false self.items.well the current true remove um if Val in self.items self dot items um if Val in self.items self dot items um if Val in self.items self dot items dot remove Val return true return false that leaves getting a random element how do we want to do this so in Python you can't just index a set um it's simply not a thing you can do that's because they have no order as such you can't well in recent python though I don't think you can index into a set I'm actually slightly interested now in fact let's try it I was gonna say you can't index into a set um uh but maybe you can so random.range is a python function so random.range is a python function so random.range is a python function that just gives you something between zero and this number minus one so the same as a regular range gives you between 0 and N minus one this gives you a regular range gives you all of them this one gives you a random one of them can you index into a set I don't think you can so the reason I'm suddenly unsure random has now attribute range uh maybe that's an a different version of python maybe we need to do randint well zero and Lan items minus one so range may have been added later okay set object is not subscriptable right so the reason I was unsure was because traditionally python sets are unordered you don't know what order the elements are going to be in the set that slightly changed in more recent versions of python in that they're guaranteed to produce the same order that they're added so that maybe think maybe you can index them but no you can't so I'm thinking self.indexable items self.indexable items self.indexable items can be a list um now the remove actually we need to be more clever maybe we don't make this a set um we make this Glam self.indexable items and then it's going to be index itself Dot items for value um we'll deal with the rest of that later and then Dell self-disons value remove it from Dell self-disons value remove it from Dell self-disons value remove it from the dictionary so now we generate a random index into this and that will effectively remove our uh no sorry this does a we'll come back to this so This generates a random index into the indexable items lists are indexable so we know that's fine um the problem is we don't remove the element up here what we could do is self dot indexable items dot pop index so now that works the problem is this is order n so how can we make sure to get rid of this maybe this isn't what we want maybe we actually want another dictionary Let's do an index is this so basically what I'm trying to do here is I'm trying to make an array that I can delete from quickly and one way to think about that is it's a dictionary from integers to values a list is a basically a dictionary from integers to values um with the special property that the keys are always consecutive now this effectively removes that property so that I could have for example zero two as the keys in my dictionary uh is my in my indexable items dictionary but I think that's kind of okay because I just want random to choose or is it random the choice could be choice I can never remember which way it is yes I did remain choice so the reason I always get confused is because there's itatools.choose I think it is something itatools.choose I think it is something itatools.choose I think it is something like that Keys object is not subscriptable all right I don't want to turn the keys into a list because that's going to take order and time what I was hoping to do was basically just randomly pick one of the keys so if python sets were random as in randomly ordered ah now it doesn't meet the guarantees of this okay let's quickly fix this just with a list but this isn't right this transformation here costs order end time so our random choice is order m uh this Len up here is not ordering it's order one because arrays must store their length the lists must store their length if it was a linked list that would be ordering hmm why am I not getting here because there are other options we could go back to storing this as a list and rather than removing elements fill them with say a null or a none sorry um and then one option is to just re-roll one option is to just re-roll one option is to just re-roll our random index until we land on something that's not order uh not none but that can well that's entirely unanalyzable um there's really no good way to give a Bound for that what we could do instead is do a roll then slide so if we have say zero filled one is none and two is filled we could if we rolled a one we could just slide onto the two but that destroys the same probability requirement and it also makes it potentially order n um and the reason it destroys the same probability I've been is effectively now you've got zero has a one and three chance of being pecked and two now has a two and three chance of being picked because if you pick a one you implicitly choose the two so we can't do that slide technique um can I it only save an average of oh one time complexity so which of these can I sabotage every nth call for example um I don't know I'm a bit stuck here how can I do this better given a key well we can do the unanalyzable way I equals num while I'm not in self.indexable items while I'm not in self.indexable items while I'm not in self.indexable items I is equal to Rand no I don't actually know oh this is actually wrong in really subtle ways um so that's actually quite bad I think what I want to do is go back to this and but rather than do this I just wanted to our nun tombstone let's go back to random that's random Lan self.indexable items Lan self.indexable items Lan self.indexable items uh from zero to the length minus one well self to indexable items I is none keep trying now the danger here of course is that this just gets stuck in an infinite Loop and in fact it will get worse as time goes on because as you remove more items we end up with more and more nuts so what we can do keep track of some vacant indices if self dot vacant indices if there's a vacant index we want to do self vacant industry in the seed pop so I can take a random element from a set that's fine so what this does it says if there's something that we've marked as none um self dot index able items.pend none so if there's some space we have previously turned into a none we all set that um then fill it otherwise make space on the end and fill that so down here what we want to do is do self dot vacant indices.pend uh no dot add index so mark this as a free spot so now this should work we are less likely okay we can still end up in a bad state in that if we add a whole lot of items then remove a whole lot of items we can end up with most of it being nuns um is that likely and I'll probably test that um what we should do we should probably check that if the number of vacant indices exceeds the number of items we should probably just re-index everything that's obviously very expensive and we'll take order in time but it shouldn't happen very often you would have to have done a whole lot of insert and a whole lot of removes to end up in this situation in fact you'd have to have done order n of them approximately so it's order end work but we're only going to do it one every order and times um if Lan self Dot bacon indices is greater than or equal to Lan self the items self dot compact right what we want to do is effectively for how do I want to do this what I want to do is I want to take the items I want to take their values no the keys in fact because we're storing them in the Keys um items is equal to self dot items dot keys in fact I want to turn this into a list specifically for index I item in numerate items um oh and I want to purge self. vacant indices gets reset to a set self dot indexable items it's going to turn out to Len item and in fact that's going to be items and self dot items is going to be um item index for index item in enumerate self dot indexable items I think that works so the complexity of this is this takes order end time this is instant this is order end time so that's order n overall but we're only going to do it when the number of vacant indices exceeds the number of items remaining so this order and work is only going to happen after we've done at least well for that to be true we have to removed at least half the number of elements we've added so that's water n as well and what that means is that this never drops below 50 percent um well sorry um the odds of generating an index that's bad is never more than 50 percent so we should expect to generate a good index fairly quickly I'm not sure I can do any better than that it's this probabilistic argument I do not like but I really don't know how to do better foreign because if I call compact every time we call get random that's order and work every time that's too often so this condition here is what keeps us fairly cheap well asymptotically cheap uh what the heck let's submit it we'll find out if we get hammered in the tests for being too slow we were not too slow how tight it was I don't know um it may have loose enough barrels that you can get away with non-order end that you can get away with non-order end that you can get away with non-order end Solutions it's the big debate it's really quite tricky to know what to call this and I can't remember how to do analysis of probabilistic algorithms properly we can consider this as a um binary distribution effectively because it's a fixed probability it never Falls below a half sorry it never Rises the odds of being bad never rise above half yeah the odds of you getting a long string of bad roles here is very low one minus P to the k for some k I'm happy with that anyway I could stand here and stare at this and not make any progress on this particular analysis for a very long time so let's not do that let's leave it here and go it seems to be good enough to pass the tests um anyway that's gonna be it for me do remember to like comment subscribe all this good stuff in particular if you know how to do this analysis or you have a better way of getting around this selection problem if it didn't have to be uniform I know how I do it if it didn't have to be um uh Auto order one I'd know how to do it but it's that combination of things that's really stunned me here so do let me know in the comments if you know how to do it that's it from me I will see you next time bye foreign
Insert Delete GetRandom O(1)
insert-delete-getrandom-o1
Implement the `RandomizedSet` class: * `RandomizedSet()` Initializes the `RandomizedSet` object. * `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. * `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. * `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. You must implement the functions of the class such that each function works in **average** `O(1)` time complexity. **Example 1:** **Input** \[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\] \[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\] **Output** \[null, true, false, true, 2, true, false, 2\] **Explanation** RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. **Constraints:** * `-231 <= val <= 231 - 1` * At most `2 *` `105` calls 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
Medium
381
1,604
hello guys so here we are again to the second question of the cont of the week we contest 36 and let me thank you to the um user that told me about obs studio i am now using it so you don't need to see that movavi trial watermark so this question a word using same key card three or more times in a one hour period this is a big title for uh with code question probably the biggest bit code title and what this means is that we the simulation in here is a company as many workers each worker has a unique name and the worker uh enters and enters the office multiple times a day and when we have a worker that um he passes the card three times or more in one hour uh we have to avert that user so this is the general goal of the question a word people that uses the key cards more than three times in one hour so there are a few uh things that we need to pay attention one of them is that we are using the 34 24 hours time format so we go from zero to twenty three fifty nine uh the next thing that is important to notice is that uh as they say in here um as they say in here uh when we go from one day to another it is not considered to be in the same hour okay so um a client that enters at this time and another that enters at this time this is not equivalent to the same hour okay because as they say uh in here it this is equivalent only to a single day so if you have data from one user that is from midnight and uh from uh 23 or 11 pm they are spread by multiple hours okay so uh this is what it means this note and the other very important note is to see that 10 and 11 are within one hour period okay so uh that's the valuable things that you should keep in your mind in the time to create this solution in terms of approaches uh there are a couple of approaches that could be took in here i decided for one of them and it probably wasn't the most efficient when i was thinking in this solution i thought in just doing something very manual and comparing the intervals for each user and see if they are in one hour period and do something very manual or to use an algorithm and i decided to take the algorithm path although it wasn't like the most efficient but i knew it would work so the strategy that i used for this exercise was to use sweep line algorithm okay so i will try to explain you uh what i mean with that so imagine you have a user that enters at 10 and then at 10 15 and then at 10 21. imagine this scenario the three point algorithm what it does is to mark uh 10 okay now i would mark the x spiral of this hour and the x spiral would be um eleven and one okay and i mark 11 and one with minus one then the next interval is 10 15. what i would do i would mark 10 15 with one and i would mark 11 16 with minus one and then 10 21 i mark with one and i put 11 22. i hope this is still caught on the screen um so that's it okay i will drag this just in case so you got the picture right we mark the start of the interval in we mark the end of the interval and as per the requirement uh starting from 10 11 still is inside the hour period so after doing this job for the user x we will do a commutative sum between all the minutes between and we will have we will be able to see if at any moment the user uh has had reached the limit of three or more so uh the next step would be 10 in one we put another one 10 and 2 10 and 3 10 and 4 10 and 11 10 in um 12 you know so uh until 10 and 15 we always add one entry only okay uh but this is a cumulative sum and all these values in between have zeros you know so when we get to um 10 15 which was uh one of the starting points of which was one of the times in which the user entered we will accommodate and it will become two okay so within one hour we add 10 and 10 15 okay two entries now we continue with this and we will see more uh ones like 16 17 18 19 20 and sorry this is not one but will be two okay will be two and this is our commutative sum until 10 20 and in 10 21 we had another entry so we accumulate we sum and we found something that we need to avert okay so this would continue uh with three okay but we stopped the iteration here but this would continue and here at 11 and 1 minute we are freed from this our period expires so we subtract minus one and we get two and from now on we get only twos and when we get to eleven um sixteen uh this one is also not um in the same uh doesn't count anymore for the hour so it becomes one from here on and again at 11 22 this one doesn't count anymore so from there on zero okay so this is the main logic for solving this problem doing sweepline algorithm and there are a couple of challenges more because this is um a string right and um i used a an array okay i use an array to represent these for each user okay every time i process a user i create this array and i will populate it with the entry times okay and then i will accumulate but i need a sort of mapping that will tell me um the where to put 10 hours where to put 10 and a half where to put 20 10 and 21 and the way i used it is to do hour times 60 plus minutes okay and using this formula i can map to this array and this array contains all minutes of the day okay so in the first position you have midnight okay the next position uh is equivalent to midnight and one minute and so forth okay so there are 104 well not one uh 1000 for 1440 entries so from here uh so there are these this number of interest that to you need to process okay um and it's about it then you do that check to see if at any given point you get to tree and then you pass if you find a user that has three or more words you add it to a list and then in the end you sort the list and return the result is as simple as this so from here let's see how the code looks like so this is the solution okay that i used um and it starts with defining a nash map which will have each worker name and the entry times okay so the first step is to map the names and the entry times then the second step is is for each user we will create that array which all the minutes of the day and we will see the time we will mark the time in the given array uh for each user so we uh parse the time for an array that as minutes and hours then from here we get the array position by doing the math that we talk later before then we increase the starting time and then we are going to find what is uh the end time okay and this is for the first rule if the end time is uh in the next day we continue we will not mark it but if the end well this is our specifics like um if you have a situation like this one 9 59 we need to mark an hour later plus one minute and we have to do the correct time or the usual logic is to increment hour by one and increment the time with the minutes by one and you get this and this is only one minute after so we this is not um one hour later plus one minute uh we need to do something more which is to increment one hour more okay this is what is written in here so we the it starts in here and ends in here and it is free uh it is it no longer counts after which is in here okay so it's what you can find here so you find this in position and then you uh decrement the end okay uh just like i told you here you have uh the starting position that you mark with one and the end position which is one hour minute uh you mark it with minus one so that you can accumulate and have the current in each minute and past this time uh it is zero again hope this uh has been uh clear enough uh and for all the other cases there is no special treatment okay uh so this is why we increase the hour uh two times okay because it's from nine to ten and from ten to eleven uh and the minutes is zero and here is just the normal case and we increase our by one and we increase minutes by one okay one hour and one minute more so yeah that's it then um after we do uh this marking what we need to do commoditive sum and that's what we do here and if we find the sum which is equal or greater than three we add this uh worker to the list and we break the forward there is no need to continue uh and would in then we do this for all the members uh and in the end you sort the list and we will you return it okay so get time is as simple as splitting the string and return an array and that's about it about my solution okay uh hope you have enjoyed uh let's run it is slow and i know we ca beca why it is slow okay i know why it is slow but it is an approach and it could be improved but it was what i was able to come up with the pressure of the moment
Alert Using Same Key-Card Three or More Times in a One Hour Period
least-number-of-unique-integers-after-k-removals
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period. You are given a list of strings `keyName` and `keyTime` where `[keyName[i], keyTime[i]]` corresponds to a person's name and the time when their key-card was used **in a** **single day**. Access times are given in the **24-hour time format "HH:MM "**, such as `"23:51 "` and `"09:49 "`. Return a _list of unique worker names who received an alert for frequent keycard use_. Sort the names in **ascending order alphabetically**. Notice that `"10:00 "` - `"11:00 "` is considered to be within a one-hour period, while `"22:51 "` - `"23:52 "` is not considered to be within a one-hour period. **Example 1:** **Input:** keyName = \[ "daniel ", "daniel ", "daniel ", "luis ", "luis ", "luis ", "luis "\], keyTime = \[ "10:00 ", "10:40 ", "11:00 ", "09:00 ", "11:00 ", "13:00 ", "15:00 "\] **Output:** \[ "daniel "\] **Explanation:** "daniel " used the keycard 3 times in a one-hour period ( "10:00 ", "10:40 ", "11:00 "). **Example 2:** **Input:** keyName = \[ "alice ", "alice ", "alice ", "bob ", "bob ", "bob ", "bob "\], keyTime = \[ "12:01 ", "12:00 ", "18:00 ", "21:00 ", "21:20 ", "21:30 ", "23:00 "\] **Output:** \[ "bob "\] **Explanation:** "bob " used the keycard 3 times in a one-hour period ( "21:00 ", "21:20 ", "21:30 "). **Constraints:** * `1 <= keyName.length, keyTime.length <= 105` * `keyName.length == keyTime.length` * `keyTime[i]` is in the format **"HH:MM "**. * `[keyName[i], keyTime[i]]` is **unique**. * `1 <= keyName[i].length <= 10` * `keyName[i] contains only lowercase English letters.`
Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.
Array,Hash Table,Greedy,Sorting,Counting
Medium
null
130
hello everyone so let's talk about surround region so in this question i'm going to solve this question by union fine so unifying is actually a quick way to do that because um they are beneficial of doing this when you're trying to find a null that you should with um someone else before like they will take you out of one for time complexity or not right and it's just basically like you have to assign a number of the note to yourself right so you will have a note and for each note you are going to point at yourself and when union right you can actually union a no to b no right if ano and b no do not have the same parent or same green parent then you assign uh one note to the other so um for note 2 right no to a point at no one so no one uh so no one become the parent of the note2 so they uh this is how it is and fine is actually to check um which one is my top uh top and uh top uh green pattern it should be like this right so which one is the top note i connect i have a connection with this is how you actually do you can actually return yourself right you can actually return to yourself or you can still keep going up right and for it's connected it's going to check it all these two no connect with the same note on the top above right if yes you're gonna return true if not you're gonna return false so how do i solve the uh so this question by union fine is i convert every cell to a node and i'm going to uh assign for each note to uh to a note where it is supposed to be a no which is not going to flip if the note is going to be flipped it's going to be x if the note is not going to flip it's going to be circle this is how it is right you can watch my that first search video and that first video it will be easy for sure but i'm going to practice a union point so let's start getting so if so i'm going to check the board if then border length is equal to 0 then i'm going to return and also i'm going to assign row and colon to my tolerance and dual value so i'm going to say union point i'm going to declare the value if you put the new union fine so how many nodes is going to be rows time columns right but i want to add one when i want to add one is because i want to know um i want to create another node that is going to be a node that is represent circle okay so i'm going to say dummy would be the rose time column this is going to be a number and since the value for each note is going to be zero one two something right so start from zero and dummy will be the last integer on this board right so this is unique for sure i'm gonna try verse in i equal to zero sorry i equal to 0 at less than rows i plus or in j equal to 0 j less than column j plus all right so i'm going to say if 4 i j is equal to o and do something else i'm doing another things so if 4 is equal to all right and i'm going to check the border first if the border is equal to circle so i j is equal to o okay but i also have to check the border if i equal to zero or j equal to zero or i is equal to rho minus one or j equal to columns minus one okay if this is going to be true right this is going to be true in the border if the border is going to be a circle and i'm going to assign to a dummy so union so uf.union and the value for union so uf.union and the value for union so uf.union and the value for these cells i'm going to assign i'm going to create another function which will give you um no and i in j oh where's my mouth in inj i'm gonna return um i times colon plus j this will represent my um your uh your number for each cells which is you know okay so you union so i'm going to union your note which is i and j right so no i j with the dummy so this is going to be a value of cells that is going to be a circle if the cell is circle already right when you flip the ball right it's going to be a circle again and that would be it for i and j okay and i don't have to do the else for this case but what happen if the cells is equal to circle but it is not in the boundary of i equals zero j equals zero i plural minus one j equal to rho minus one i will definitely need to know if the cells if this cell is connected with the boulder so if this cell is connected with the border top left or bottom or right if this cell is connected with a border i need to know i have to connect with it because this cell is circle right imagine this cell is circled so i need to know if this cell is circled i need to connect with the border and all those cell has to come up with a border so um if border i minus one j equal to o go to o i do something right and i can use else but i want to just making sure if i plus one j is equal to o i do something if bold so you can see this will be j plus one and another one j minus one right t minus one is equal to o you do something else so how do you actually union with the border so you're going to say uf.union going to say uf.union going to say uf.union and you are going to say your current cells sorry your current cells you're going to union you're going to find the final note which is i minus 1 comma j i'm going to union with it because there is a border right if i put 1 i minus 0 this is border right so you're going to unit so send idea you have that union no i j this is going to be comma and uh comma node and then you're going to say no i plus shift and j so this will be exactly similar and no i j simple no i j plus one and uf union no i j comma no i j minus y okay that will represent um the connection between the cells with the border so when you assign everything um on your board right you can convert every single cell to the node and you can every single node choose something else right then you can actually going to check so i'm going to try verse again so if uf is connect if this is connect if the single cell is connect ij with a dummy because i really know i really assigned to domi if this is if this cell is on me if it's not islamic it's going to be circle right so for i j is assigned to circle else or i j remain x this is how it is right and i hope you understand and let's just run it to see if i have everyone now okay i do so i made a mistake i j k okay rules tony collins okay spelling wrong let's just see again oh my god so many um okay so i need this column and yes sorry so i'm going to assign my rows and column for global variable and this two variable will just uh going to be initial over here and they just run again it should be plus yes and you should be okay so let's talk about time and space and for every single cells you have to traverse once right so that would be out of m times n so that would be time complexity and for every single space capacity uh for space complexity you have to store every single node to in the union plane right so that would be all of m times n and time and space complexity are the same so that would be the solution and this question is pretty standard both for practicing the union point and if you're not comfortable with you have to spend time on it just making sure you know what is the union class and just making sure you know how to connect with the uh the null with another and that will be the solution and if you have any comma just comment below if you have any questions just please let me know and if you like the video please press the like and subscribe if you want it alright peace out
Surrounded Regions
surrounded-regions
Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`. A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region. **Example 1:** **Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "X "\]\] **Output:** \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "X ", "X "\]\] **Explanation:** Notice that an 'O' should not be flipped if: - It is on the border, or - It is adjacent to an 'O' that should not be flipped. The bottom 'O' is on the border, so it is not flipped. The other three 'O' form a surrounded region, so they are flipped. **Example 2:** **Input:** board = \[\[ "X "\]\] **Output:** \[\[ "X "\]\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 200` * `board[i][j]` is `'X'` or `'O'`.
null
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
200,286
127
hey everyone in this video we are going to solve the word ladder question on lead code so we are given a begin word and an adword and a list of words uh working as a dictionary and we need to return the number of words in the shortest transformation sequence to convert this begin word to the N word and the condition is that every adjacent pair in that sequence should have a difference of a single character only so for example in the first example we have begin word as head and word as Cog and we have this particular word list and what we start with hit then we go to hot because hit and hot only have a single character difference we only need it to replace this I with O then from hot we go to dot because again A Single Character difference we replace H with d and if we keep doing so we reach the end Cog and we need to return the length of the words present in that transformation sequence so this is the question let's say how we can do it so we have our begin word our end word and a list of words and we are given a rule that the difference between the adjacent post must be of a single character only so our first difficulty that or the first challenge that we see is how can we determine that the difference between two words is of a single character only so let's say if we pick the first word from the list hot what are the possible scenarios or what are the possible patterns it can be converted to so we have three possibilities first one we replace the first character with something I represent the replaced uh character with star and keep the other two as it is another possibility is for a one character difference that we only need to replace the second character only and keep the other two as it is similarly for the last one we keep the first two as it is and replace the last character with something if you pick another word which is Dot and try to do the same thing for this as well it also has three possibilities so first one is replace the first character so hot to place the second character or replace the third character now if you see that we have two similarities here so this one and this one they both are the same so using this method we can create kind of an adjacency list and in that agency list it will be a value of key value pairs so in which key will be a pattern and value will be the array of words that this pattern may match to so for example in case of this pattern star o t up to now we have found two characters which can match this pattern one is hot another one is Dot so we know that these two words have a single character difference between them so doing so we can create a decency list of all the words which have only one character difference between them and our final adjacency list will look something like this so let me increase the width yeah as we see that this particular pattern uh star OT have these three following words in it hot Dot and lot so we mean so we can know that all of these three characters have a single character difference between them we replace the first one for them we replace the edge t or L and we can get the other adjacent port and now once we have created this adjacency list it becomes now a graph problem so what we can do we can just simply run a BFS to found the shortest path to go from our begin word to our n-word from our begin word to our n-word from our begin word to our n-word from this adjacency list let's try this in a trial run so to run BFS on our adjacency list we'll need three things first a queue next uh visited array or a visited site whichever works for you I'll be using a set so it will be let's call it visited next we'll have our output variable let's call it result initially its value will be 1 since we are beginning from our begin with since we are starting from our begin word so we'll add this big invert to the queue and to the visited set as well so we'll add hit cool now we'll start the BFS so first we'll uh remove the element from our queue we'll use dot shift method in JavaScript for this it will pop remove the element from a queue and return as the element so a word will become it is the first word so now we'll do the same thing what we did while creating this adjacency list we'll replace the uh characters one by one with an aspiration or a star and check all the adjacent elements present in the decency list and add all that words to back to our queue and once we reached the final n word will return the count which will return the count present in a result variable let's see how so for this headword first what is the option we replace the first alphabet with an asterisk and keep the other two as it is okay so is there any uh pattern or any key matching to this particular pattern star ID yes there is this one is matching and it contains a word hit in it but it is already present in a visited array so will not do anything next what is the other pattern we replace the second word Edge as fish T so is there a key present with this pattern yes there is it contains two word hot and hit it is already present in the visited array and hot is not so we'll add heart to our queue next what is the third pattern we can replace the third character so it will become h i as fish so we see is there any matching pattern for this h i s h yes there is it contains the word hit in it we have already visited it so we'll not do anything so uh this first word is completed and the value of result is 1 because we have just used the first word up to now next we'll pick the another word from our Cube because our queue is not empty yet well the word will become hot and we'll update the value of our result or the count of our sequence to 2 because now we are using the second word from our word list so for what we'll do the same thing what are the possibilities what are the possible patterns first one is to replace the first character it will become star o and t we'll check star OT is present in our attention list yes it is it what are the words present in it's hot Dot and Lord heart we have already covered and also once we uh pop this element from our queue we'll add it to the decency list as well okay so for what uh for Star Roti we have three words hot Dot and lot what is already present in our visited uh set so will not do anything Dot and lot are not visited yet so we'll add them to a queue so we'll add Dot and lot to a queue cool what is the next pattern we can replace the second character it will become star HD so we have already covered it as is history hot and hit both are visited so will not do anything what is the next one we keep h o and as pressure is there any key matching to this pattern yes there is it's hot we have already visited this word so will not do anything okay we have covered the second word next we pick the third word from our queue which is dot so our word will become Dot and will update the value of a result to 3 because now we are at the third word that we are using so similarly we add this one to the visited array to the visited set now for DOT what are the possible patterns we can get we have star OT we have already visited it so we'll not do anything next is D star B so is there any words present in it yes star uh yes a key is present with this particular pattern star D star T it contains a word dot in it but it is already present in the visited array so we won't do anything next is d o star so is there a key present in it with d star with d o yes there is it contains Dot and top dot we have already covered dog we have not so we add dog to our queue cool so we covered the third word now as well now the word will pick the next word because our queue is not empty yet we pick lot l o t we pop this from a queue add it to the visited array or the visited site I'll keep saying it array and we see what are the possible patterns for lot we have three options OT already covered then L has fish t so LST is there or anyone present in it yes it is it contains single word lot in it we have already visited so we won't do anything next l o star is there a word present in it is there a pattern yes there is it contains two words in it lot and log lot we have already visited log we have not so we add log to our Cube so our third word is also completed now we pick the next word from a queue which is dog we pop it from our queue add it to the visited set update the value of result it will become 4 what are the possible patterns for this one star o g so what are the uh so is there a key present with that so is there a key presented their distance list with this particular pattern stretch OG so sod yes we have Dog Log and Cog dog we have visited log sent in the queue Cog we have not measured it so we add fog as well to a queue cool what is the other pattern we have D has stretch G so is there a word is there a key matching this pattern d as to G yes there is it's talk it is already present in the visited area so you won't do anything next one d o asterisk we have already covered it d o asterisk dot endog both are covered both are already visited so you won't do anything this one is also covered next we pick the other word from our queue which is log we check uh what are the possible so first we add it to the basicated set so we add log into it and we add result and we update the value of result from 4 to 5. okay now we check what are the possible patterns so we have asterisk OG ster OG already covered Dog Log clock already covered then we have a l asterisk G yes there is it contains log and lot and log we already covered it present in a visited array so it won't do anything okay next we have the final word Cog in it does it match to our and uh does it match with our end word yes it does so we result this final value which is 5 as an output the time complexity for this one will be o of n dot m Square where n is the length of the number of words we have total and M is the uh length of a single word which is 3 in this case so this is the drawing explanation let's see how we can do it in code so let's just first handle the h k so what if the uh N word is not present in the word list in that case it is not possible to create that sequence if there's no such sequence exist in that case we just return 0 so for that we'll write if not of wordlist Dot includes and word will just return 0 as an answer if otherwise we need to create another CC list first so we'll create a I'll name the variable as a DJ list it will be a map next let's declare a variable for our length so we'll call it m we'll call it end word dot length since all the words begin word N word or the words in the word list will be of equal length so it doesn't matter next we'll check again if begin word is not present in our list then we add it to the word list so if not of word list dot includes back inward then we just simply add it so word list dot push begin word now we create the additional list we'll use a for Loop for it so for let word of word list we pick all the words from the word list one by one next we create another for Loop so let I equal 0 I is less than M since all the words will have equal length I plus next we create a pattern so const pattern it will be replacing one by one uh each character with an asterisk and uh keeping the rest of the word as it is so word Dot substring will it will be from C2 to I then we add an aspect to it then word Dot substring the rest of the word so I Plus 1. so now we check if the if this pattern is not present in the adjacency list so let's call it pattern so if uh not of adj list dot has pattern so if it doesn't con if the pattern doesn't exist uh as of now we just push an empty array to it so a DJ list dot set for this particular pattern as key and the value will be an empty array next we just insert the word as a value to this particular key so adj list dot get pattern dot push the word okay so now once we got our adjacency list we need to run a BFS on this graph so for that we'll need few things we'll need a visited set so visited equal to new set we'll add begin word to our visited set initially so we'll add begin word we'll need a queue as well so Q equals to an array with the a big invert in it and a result variable containing the number of words in the sequence initially it will be one now let's run the BFS so while there is something present in our queue so while Q dot length we first create the size of our queue so we get the size of a queue so const length equals to Q dot length now we run a for Loop until this length becomes 0 so it will start from I for let I equals to 0 I is less than Len and I plus nine plus now we do the same thing first look now first we pick the word comma Q so word will be equal to Q dot shift it will remove the first value or remove the first element from our queue and it deletes it as well comma queue now we check if it is equal to the N word so if word is equal to the end word that means we just return the result the count which we were calculating up to now else if it doesn't then we need to get all the possible patterns all the possible words from our adjacency list and push them to our queue so for let J equals 0 J is less than m J plus same thing what we did while creating the distance release we'll create a pattern first so word Dot substring from 0 to J sorry 0 to J then add in abstract to it then word Dot substring the remaining part of the word which will be J Plus 1. now we get all the possible values from our adjacency list so const Neighbors equals to dependencies in adjacency list dot get that particular pattern now we Loop through all of this pattern all of these words one by one that were matching this pattern so for neighbor any neighbor of Neighbors if it is already not visited so if not of visited dot has neighbor if it is already not visited something is wrong neighbor oh let me use let here yep so if it is already not visited then first we add it to the visited set so visited dot add enable and we push it to the queue as well so Q dot push neighbor and outside this for Loop will update the value of our result by 1. and if at any point this word matches with the N word we return the count if no such word is found then at the end we'll just return 0 stating that no such sequence exits so this is the code if you run this while Q equals to begin with oh I misspell it so b-e-g-i-n misspell it so b-e-g-i-n misspell it so b-e-g-i-n okay let's run it again it's working let's submit it cool so that was it for this video thank you for watching
Word Ladder
word-ladder
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that: * Every adjacent pair of words differs by a single letter. * Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`. * `sk == endWord` Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _the **number of words** in the **shortest transformation sequence** from_ `beginWord` _to_ `endWord`_, or_ `0` _if no such sequence exists._ **Example 1:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\] **Output:** 5 **Explanation:** One shortest transformation sequence is "hit " -> "hot " -> "dot " -> "dog " -> cog ", which is 5 words long. **Example 2:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\] **Output:** 0 **Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence. **Constraints:** * `1 <= beginWord.length <= 10` * `endWord.length == beginWord.length` * `1 <= wordList.length <= 5000` * `wordList[i].length == beginWord.length` * `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters. * `beginWord != endWord` * All the words in `wordList` are **unique**.
null
Hash Table,String,Breadth-First Search
Hard
126,433
236
hello and welcome back to the cracking thing youtube channel today we're going to be solving lead code problem 236 lowest common ancestor of a binary tree let's read the question given a binary tree find the lowest common ancestor lca of two nodes in the tree according to the definition of an lca on wikipedia the lowest common ancestor is defined between two nodes p and q as the lowest node in t that has both p and q as descendants where we allow a node to be a descendant of itself so let's look at an example if we're given that p equals five and q equals one so this node here and this node here then we would want to return three why is that because obviously this is the first node where they converge um when going up the tree so this is the lowest common ancestor in the tree okay but what about the example where we have um p equals five and q equals four so this is here and here we wanna return five because if we think about it if we go up from four we're actually going to reach the five and since 5 is allowed to be an lca of itself right based on the definition from the problem this is actually the lowest common ancestor so that's why we return 5 in that case but what about this case where p equals two and q equals seven well again because we allow a node to be an lca of itself um you know the seven and the two meet here at the two so that's why we're going to return two so this problem is relatively simple in that there's only three cases that can occur and we've actually just gone over them with these examples in the first case the two nodes will be on opposite sides of the tree and what we want to do is we want to find the first node where they converge um where you know they would meet so the first node we're going to its left and it's right we would be able to access both the nodes so that's the case when p equals five and q equals one the second case is where p is um you know sorry q is a descendant of p which means that p is actually our um lca here and then the other case is going to be where p is actually a descendant of q and then q is going to be the lca so that's going to be this case 3. so essentially those are our three cases and act solving this problem is quite simple what we want to do is we want to do a depth first search through our tree and we're going to start at the root and we're going to check okay um you know can we reach the uh p or q from this node right uh and what we're gonna do is check whether or not the current node equals to p or q if it does then we can return that node to the parent so let's do this example so we're pq and you know we start at the three does three equal to either p or q no so that means that we go into the left subtree and we go to the right subtree so we'll go to the left first and we're at this five does five equal to p or q it does so that means that we can return um you know five to this node here and then we stop there because we found a node so either one you know q will be found on the other side of the tree or it's a descendant of five which is fine because we would just return five so we don't have to explore the rest of the tree because we know that either it's going to be down here or it's going to be on the other side of the tree since p and q are guaranteed to exist in the tree we know this is true so if it's a if 5 is actually the lca then we can just return it that's fine if it's not then 3 will receive a non-null node from both 3 will receive a non-null node from both 3 will receive a non-null node from both sides in which case we know that it is the lca so we said that we're going to cut the processing here because we've already found p then we go into the right subtree and we say okay does this node 1 equal to either you know p or q which it does because it's q so we would return one here and when we receive a non-null node from and when we receive a non-null node from and when we receive a non-null node from both the left and the right we know that we found an lca so we can simply you know pass up our current node so we would return three here in this example but let's look at this example here where you know q is actually in the subtree of five what's gonna happen so again we start here at this three and we're gonna say okay does this equal to either p or q right is it five or four it's not so we need to go into both the left and the right subtrees so we're gonna go into the left subtree and we're not this five and we're gonna say okay does the five equal to 5 or 4 it does so that means that we can return 5 here and that means we can stop searching for the rest of the tree because remember either 4 then q that we're looking for is going to be in this sub tree here or it's going to be on the other side so now we can go into the right subtree and we end up at this one here and does one equal to oh sorry yeah does one equal to four it doesn't so we're going to try to explore the left subtree so we go into the left and we go to the zero and does it equal to five or four it doesn't so we try to go into its left subtree and its right subtree but those don't exist so we just simply bounce back to the zero at this point we haven't found any you know we haven't found p or q in this node or its children so we would simply return none here and now we try the right subtree of one again does eight equal to either five or four it does not so that means that we need to go into its children so we try the left subtree obviously that is null we go into the right subtree that's null so that means that we haven't found five or four in the left or right subtree nor does this node equal to five or four so that means from here we return none and that means that from one we haven't found it in its left subtree or its right subtree and obviously one doesn't equal to five or four so from here we return none now we fully explored three's left subtree and right subtree which means that we check okay did we receive a non-null node from both left and right non-null node from both left and right non-null node from both left and right we didn't but we did receive a non-null we didn't but we did receive a non-null we didn't but we did receive a non-null from the left which means that the lca must be this node here so we're simply going to return up the tree this five and if we had more nodes we would keep going and either we would get to a point where a current node receives a non-null where a current node receives a non-null where a current node receives a non-null from its left and it's right in which case that is the lca or we'll just pass up the tree and it has to be the case that the non-null node we kept returning that the non-null node we kept returning that the non-null node we kept returning is the lca because that means that the node um the other node was a in the subtree of the other node of you know the node that we did find so if that makes sense right the reason we don't have to explore everything is because either it's you know 5 or it's in the other side of the tree and that's essentially the algorithm we want to use for this so hopefully it's not too confusing once we go into the code editor it's just a few lines of code to solve this problem so hopefully it clarifies things a bit if not kind of go back and let's walk through all three of the examples again and hopefully it makes a bit more sense so i'll see you back in the code editor and we'll write out the code for this we're in the code editor let's write the code the first thing that we want to do is actually check whether or not our tree was given to us because if we don't have a root then there's nothing for us to search for p and q we should just return none so if not root we can simply return none i think actually for this problem uh we are guaranteed to have those nodes but it doesn't hurt to do this a lot of the times you will get tree questions where the route can be null so just working with your interviewer identifying that base case just shows that you're thinking about the edge cases and you know how to handle it so even though we don't technically need it for this problem i guess it's just good habit to have for any sort of tree based question okay moving on what we want to do is we want to say okay if the root equals to either p or the root equals to q then remember then we can return that node um to the next level so we can simply say return route and what we're going to do is if we haven't returned at this point then we need to go into you know the trees left and right subtrees so we're going to call our lowest common ancestor function recursively so we're going to say left equals to self.lowest equals to self.lowest equals to self.lowest common ancestor and we're going to call into the left subtree right root dot left and we're going to pass in pq and now again we're searching for p and q in the left subtree and we're going to do the same thing for the right subtree so we're going to say self.lowest common we're going to say self.lowest common we're going to say self.lowest common ancestor and we're going to pass root.right p eq and we're going to pass root.right p eq and we're going to pass root.right p eq and now what we need to do is we have left and right and remember if left and right are both non-null then that means that the non-null then that means that the non-null then that means that the current node that we're at this root has to be the lowest common ancestor if both are non-null right like for if both are non-null right like for if both are non-null right like for example you know we're looking for five and one here so five would return non-null and one would return non-null non-null and one would return non-null non-null and one would return non-null right it would return five and one respectively that means that three is the lowest common ancestor um when we receive only one non-null then when we receive only one non-null then when we receive only one non-null then we wanna return just the non-null one to we wanna return just the non-null one to we wanna return just the non-null one to the next level in hopes that we will find a point where both sides return non-null or we will just keep going non-null or we will just keep going non-null or we will just keep going forward with the one that was you know defined and that will actually be the lca in the case that you know the other node that we're searching for is actually in the child of um the node that we're returning so either they're going to be on different sides of the tree in which case they're going to converge at a point so one node will receive non-null point so one node will receive non-null point so one node will receive non-null from both its left and it's right or you know one node is uh a child of the other one so that being said um remember we're gonna say if left and right so if they're both defined non-null then what we want to do is just non-null then what we want to do is just non-null then what we want to do is just return the node that we're at and otherwise we just want to return the one that's defined so we're going to say l or r so the not the one that isn't null we're going to return to the next level and if they're both null then obviously it will just return none and we'll keep doing that recursively so let's submit this and verify that it works and it does so what is the runtime complexity of this algorithm well the runtime complexity is going to be based on the size of the tree and it's going to be of n solution because in the worst case um we would need to go all the way through the tree so if you think of a tree that's like an inverted v you know we would have to go all the way down to the left to find p and then all the way down on the other side to find q and then we have to recurse all the way up back to the root of the tree to figure out what the lca is so in that worst case it would be big o of n and what about the space complexity well technically it's you know big o of one because we're not um defining any extra data structures here we're you know we're not even allocating any extra space um but we are doing a recursive solution so we do have to account for the fact that if our interviewer wants us to count the recursive stack frames then we have to account for that so we're going to say big o of one if not counting um recursive stack frames other otherwise it's going to be you know big o of n to account for the um the recursion so that's going to be your time and space complexity and this is going to be how you solve the problem again it's super simple it's just a few lines of code and it's you know relatively straightforward especially once you've seen it you can kind of work your way through why it works um it's really not that bad of a question so that being said if you enjoyed this video please leave a like comment subscribe if there's any other videos you'd like me to make please let me know in the comments section below i'd be happy to help you guys out you just have to tell me what you want to see and i will get that out for you otherwise have a nice day and happy coding bye
Lowest Common Ancestor of a Binary Tree
lowest-common-ancestor-of-a-binary-tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)." **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1 **Output:** 3 **Explanation:** The LCA of nodes 5 and 1 is 3. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4 **Output:** 5 **Explanation:** The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. **Example 3:** **Input:** root = \[1,2\], p = 1, q = 2 **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 105]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` * `p` and `q` will exist in the tree.
null
Tree,Depth-First Search,Binary Tree
Medium
235,1190,1354,1780,1790,1816,2217
1,589
hey guys today we're going to solve lead call number 1589 maximum sum obtained of any permutation so we create an array of integers and an array of requests that is the range sum between a start and then end index and we need to return the maximum total sum of all requests among all permutations of nums and also the answer needs to be modulo 10 to the ninth power plus seven so the way we're going to do this is we're going to count how many elements are requested how many times okay so here i just have pasted in all of the code that i wrote during the contest so this is our module which we're going to use when we return the result later on so i'm using a change in request array this is actually applicable to a lot of problems so this is storing plus one if the requests that are asking for the current index is incrementing by one and so for example if we have a certain request that starts at a certain index we're going to have to increment the change in request at that index and if our current request is ending at a certain index then we want like the first element that is not considered in this request needs to be decremented the change in request of the first element that is not considered in this current request needs to be decremented okay so what this allows us to do is now we can loop through every change in request index and keep track of the current amount requested and essentially just add the value at that index and that will say how much that current index is requested right because we are storing the change and we increment and decrement the amount requested when there is a change so what that means is that at every step we are having the amount requested updated and so that's the amount of requests that are requesting that position in our array okay so another thing that we need is to count how many elements in our array are requested how many times so for example we could say there are five elements in our array that are requested ten times and there are four elements in our array that are requested eleven times and so on okay and now we also need to keep track of the maximum requested so that we're later on going to be able to use this to loop through all of the requested frequencies and yeah we this is how we do it in this solution i know there's other ways to do it so here we do what i was saying before so since we have a change in request array what we can do is we can loop through all of its positions and add the current value to the amount requested and so this is going to allow us to keep track of how many requests are asking for the current positions in which we are and so now that we have the current amount requested we can update the count we know that the count of the current amount requested needs to be incremented because we have one more position in which this is how much is requested so this is the common way of implementing the count and this is just keeping track of the maximum i want to request it so now what we want to do the key insight for this is the positions that have the most requests those we want to fill them with the greatest numbers in our nums array so we're going to do that by sorting our nums array and now at the end of these nums array we have the biggest numbers right so we're going to have a sum that we're going to have to return and now what we're going to do is we're going to say okay so the current request is the max request so for example if there's one position in our array which is requested 10 times that's our starting value here and then we're going to go down to zero and so what we're going to do here is we're going to say how many positions in our array are being requested that much so for example if this was 10 how many positions in our array are being requested a total of 10 times and we can look that up in our account map right that's the reason for which we have this count map and now what we say is okay we take all of those positions and while there is well we haven't consumed all of them you see like for every iteration we consume one position that is being requested this much times right and so for every position we add to the sum the current largest element that we haven't yet used in our nums and we multiply it by the current request so for example if we have three positions that are requested a total of 10 times we're going to pick the three largest numbers from our nums array because we have sorted it and we're going to multiply those values by 10 and add them to the sum and yeah this is just uh keeping track of the requirement here so yeah that's it at the end we can just return the sum i'm going to submit to show you that it works and this is actually an o of n log n solution because the most expensive thing that we're doing here is just sorting the array so it's surprisingly efficient and the space complexity is o of n because we are storing another array with change in request and also the count but the largest space complexity is here so that's it from me thank you for watching and bye
Maximum Sum Obtained of Any Permutation
maximum-sum-obtained-of-any-permutation
We have an array of integers, `nums`, and an array of `requests` where `requests[i] = [starti, endi]`. The `ith` request asks for the sum of `nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]`. Both `starti` and `endi` are _0-indexed_. Return _the maximum total sum of all requests **among all permutations** of_ `nums`. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** nums = \[1,2,3,4,5\], requests = \[\[1,3\],\[0,1\]\] **Output:** 19 **Explanation:** One permutation of nums is \[2,1,3,4,5\] with the following result: requests\[0\] -> nums\[1\] + nums\[2\] + nums\[3\] = 1 + 3 + 4 = 8 requests\[1\] -> nums\[0\] + nums\[1\] = 2 + 1 = 3 Total sum: 8 + 3 = 11. A permutation with a higher total sum is \[3,5,4,2,1\] with the following result: requests\[0\] -> nums\[1\] + nums\[2\] + nums\[3\] = 5 + 4 + 2 = 11 requests\[1\] -> nums\[0\] + nums\[1\] = 3 + 5 = 8 Total sum: 11 + 8 = 19, which is the best that you can do. **Example 2:** **Input:** nums = \[1,2,3,4,5,6\], requests = \[\[0,1\]\] **Output:** 11 **Explanation:** A permutation with the max total sum is \[6,5,4,3,2,1\] with request sums \[11\]. **Example 3:** **Input:** nums = \[1,2,3,4,5,10\], requests = \[\[0,2\],\[1,3\],\[1,1\]\] **Output:** 47 **Explanation:** A permutation with the max total sum is \[4,10,5,3,2,1\] with request sums \[19,18,10\]. **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `0 <= nums[i] <= 105` * `1 <= requests.length <= 105` * `requests[i].length == 2` * `0 <= starti <= endi < n`
null
null
Medium
null
1,970
hello guys so in this video what we will do we will basically discuss this problem from today's late course weekly contest so it's a actually a very good problem and a very basic concept of graph is required in this so first let's go through the problem statement so basically what's given is uh there is one based binary matrix where zero represents land and one represents water so now you are given integers row and column which always basically representing the number of rows and column in the matrix uh now initially on day zero the entire matrix is a length so that means all cells have zero as value okay now however each day a new cell becomes flooded with water now you are given a one based 2d array cell where cells i equal to ric i represent that on the 8th day the cell on the right column and cith column which are basically one list will be covered with water that is changed to one so you want to find the last day that it is possible to walk from the top to bottom by only walking on the land cells you can start from anything on the top row and end at anything in the bottom row you can only travel in the four cardinal directions that is left right up and down okay now you have to return the last day where it is possible to walk from top to the bottom by only working on the landsat okay so you are given this row and column then number of cells so these are uh sell on i yeah today is representing that on if today which said is going to be flooded so here in this example number one initially uh all cells are zero which are land so you can start from any uh cell from top row and you can go on bottom row so on the first day cell number one uh in one based index that is this first cell is going to be flooded so you can still walk through second column on third day cell number two one is going to be flooded you can still walk on the third day cell number one comma two is going to be flooded so on third day there is no cell on the top row uh which is land and from which you can walk to any cell in the bottom row using all land cells so on third day you cannot work so second day was the last day when you could have completed your journey so the answer for this is two okay so let's go through the constraint first which will give us the idea of the time complexity so if you see the number of row into column which are total number of cell is basically 2 into 10 to the power 4. so we have to do it in less than order of n square all right so also it's given that cells are unique okay so what the basic idea basically if at any condition if at any stage on any day you have to check if you can go through any cell on the top to any cell on the bottom then you can do that using either dfs or bfs okay so but that dfs and bfs will take your row into column time complexity which is approximately your uh this is maximum 2 into 10 to the power 4 so your sales dot length is given that it is also row into column time these cells which are representing on which day this cell is going to be filled so if you're going to trade through these cells and on every day you fill one cell with water and then you will check and then on next day if you will keep do like that then you have to in wash case you have to travel all cells and for every cell you have to apply dfs or bfs so this is going to be if i say row into column as n so it is going to be order of n square so we have to do it in less than that so the basic idea is if you see if on some particular day on iftd if you are able to walk from top to bottom on it then you will be able to walk on all day less than i right and if on some particular day you were not able to walk from top to bottom then on any subsequent day on any day from i greater than uh on any day greater than i won't be able to do that so we can basically make use of one research over here so the least day is going to be day one and the last day is going to be row into column so what we can do here we can find the midday and if this is the middle day we can we will fill all cells from 0 to mid and then we'll apply the bfs or dfs so the time complexity would be would reduce to the bfs and dfs will take uh order of n's order of n if we are saying this row into column equal to 1 then it is going to be order of n and this cells uh binary search in our cell array will be log of n so our complexity will reduce to n log n which will work fine okay so now let's go and see how we can code this problem okay so let's code this solution so i will initialize left as one and write as sales dot size okay so initially i'm marking answer our the answer as right and we will iterate while left is less than equal to right we will calculate the mid value and on mid value we will check if it is possible to work from top right to sorry top row to bottom row on this day if it is possible we will mark our answer as n and now we will check for from m plus 1 to right part so we will make our left as m and if it is not possible that means the it is not possible in on any day above m so we will check for the part where right is less than m so from we will check from left to m minus one okay and finally we will written our answer so this can work function will basically check if it is possible to go on a month day okay so in this cam can work function we are getting the day for which we have to check and we are getting these sales which have the cell for each day that is on which day which cell is going to be flooded then this row and column are the basically sizes of our grid okay so we are initializing this grid this 2d vector with size row and column and all numbers as 0 okay now we are checking for day so we will iterate and we will mark from day equal to one to day equal to day so basically from i equal to zero to i day minus one we will mark all cells as one uh basically this is representing that this grid is filled on this day okay so we will initialize one v t type vector while it rating so that while it rating we will mark the cells which we have already encountered as visited so that we don't repeat okay now we will take one variable flag and initialize it with false now we will go to every cell in first row and whichever cell is zero that means we can start our uh journey from that cell we can so either we can make use of bfs or dfs to do that so here i'm going to make use of dss so if that cell is 0 on the first row then i am going to start my dfs in my dfs i am passing this v which is our grid 0 comma j is the cell from which we are going to start and visited is our visited grid okay so if the defense returns true that is we were able to go till the top sorry from top to bottom row then we will mark flag s2 and break the loop and finally we will return the flag value so if we couldn't go from top to bottom then our flag will be false at the end and that will be written okay now let's see how dfs will work so first we will check for the base condition if our index is out of bound or the cell is visited or the grid is uh already filled with water then in that case we will return false otherwise we will check if x is equal to v dot psi minus 1 which is if we have raised in the bottom row in that case we will return true otherwise we will mark that x comma y cell as visited and then we will uh iterate in uh all four directions that is top right bottom and left so from wherever we get uh true we will return true otherwise at the end we will return false okay so the time complexity of this solution is basically n log n uh that is order of row into column log row into column okay now let's test it okay it got accepted well all right that's all for this video thank you for watching
Last Day Where You Can Still Cross
sorting-the-sentence
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`). You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down). Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_. **Example 1:** **Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\] **Output:** 2 **Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 2. **Example 2:** **Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 1 **Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 1. **Example 3:** **Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\] **Output:** 3 **Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 3. **Constraints:** * `2 <= row, col <= 2 * 104` * `4 <= row * col <= 2 * 104` * `cells.length == row * col` * `1 <= ri <= row` * `1 <= ci <= col` * All the values of `cells` are **unique**.
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
String,Sorting
Easy
2168
917
We are going to do the question reverse only letters. See, we will be given a string which will have some letters and some special symbols or it may be some numbers too. The head of the story is that we have to reverse the spring but which We have special symbols like non-English characters, listen carefully, non-English characters, listen carefully, non-English characters, listen carefully, non-English characters have to be kept non-English characters have to be kept non-English characters have to be kept where they are and English ones have to be reversed like you will see here, non-English characters are aaj it is see here, non-English characters are aaj it is see here, non-English characters are aaj it is and Puri. The string has been reversed here, A B C D, now from behind A B C D, here also you will see A B C D A F G H I K, then from here A B C D F G H I K, but these are the special symbols which Is our that today it is hiffin now special symbol can be something like see here van has gone here So those non-English characters do not come in English. So those non-English characters do not come in English. So those non-English characters do not come in English. We will leave it today, we will not change their place, we will change the place of all the others, how will we reverse them, basically, okay, this is a van, so this van is an it is. It will be okay, I is not there after A, so after T is N and G. Okay brother, the story is over. Let's do the question. We will take two pointers because we can see that basically we have to swap one point and one point will arise from here. It will rise from here and we will mix them together, okay and keep tasting, okay, we will take one I, we will keep increasing, this will keep decreasing, and we will keep changing their positions, and I = 0 * A = aaj dot length string I = 0 * A = aaj dot length string I = 0 * A = aaj dot length string s, right? Let's reduce it by one, let's convert it into character 'are' Let's convert it into character 'are' Let's convert it into character 'are' Let's convert it into character 'are' A R = convert it into character 'are' A R = convert it into character 'are' A R = S dot you care Hey, we have to keep swapping things till when I is smaller than K, it's a simple thing, nothing new. It is very big which has to be done and finally we will return it, what is a spring, its string which can be swapped finally, only I can swipe it, so what is the obbviesli string, it is inevitable, okay, so I woke up, I know it will be the same, everything must have been reversed. Accept non English characters, ok, return new string ARR, we can do it like this, ok, we can convert the character AR into string like this, ok brother, listen, now here we have to write the story, how can we do it, let's see one less. I write a small function below here, public bullin, it is valid, okay, we can speak this English, I am in this English, I want to see if any character is an English character, how are you looking, see any character which is there. Neither does it have a desired value. Okay, the value of the ask is immense. 65 to 90 of case characters i.e. A is 65 to 90 of case characters i.e. A is 65 to 90 of case characters i.e. A is capital A 65 capital S is 90 and 122 out of 97 of small characters i.e. 122 out of 97 of small characters i.e. 122 out of 97 of small characters i.e. 97 of small A is 122 small. S Okay, it will be like this i.e. it will be small, 97 i.e. it will be small, 97 i.e. it will be small, 97 will also be small, 98 is okay, now see I am increasing I, first it will go to A, then it will go to B, but swap has to be done only when any element is English. So I will check and correct here first if it is valid, if it is English, if it is an English character, which English character of I is okay, if it is English then only we will do the operation, here it is okay to taste, that is, like A is English. So we will clean it from Di, okay, let's write its code quickly, we have been there since childhood, so how do we answer your question, take a temp, time it equal, you are of I, okay and then you are of I. We will throw it in A is off K is okay and then we will wander in K is this R off Har is okay after this they will do mines why because look A has been swapped with di is okay so this one will be the pointer which will be behind. From A, we will increase it i.e. towards the From A, we will increase it i.e. towards the From A, we will increase it i.e. towards the back i.e. we will make it minus, we will reduce it back i.e. we will make it minus, we will reduce it back i.e. we will make it minus, we will reduce it and the A which is in front i.e. A will and the A which is in front i.e. A will and the A which is in front i.e. A will point to B, okay that is, our I will make it I plus, okay now. Look carefully, now tell me what to do, if such a condition occurs then our code will run. We will swipe away A and hyphen because I am checking only the character placed on the first pointer whether it is English or not. So we will have to check that the last pointer which is 'K' is also pointing to our English pointer which is 'K' is also pointing to our English pointer which is 'K' is also pointing to our English character, okay, if not, if I had taken man, it would have been 1 2 3, okay, so here we will check this is also not there. Okay, then go ahead, this is also not there, then we did it in the afternoon, this is also not done, then we did it once, what does it mean that doing the mines once will not be less, we will have to put a Wiley loop, OK, that is, Wiley calls it English Air Off. Okay, mines, look carefully and here the note will remain till it becomes English, keep doing mines, here, then here, the team has reached, okay, this is how it is happening. If it is coming out of the loop then it will be beautiful, that is, it will be pointing to the di. Now we can taste the A and Di which is happening here, okay yes, it is very nice, we will come out of the loop. We will do it with Brother, we have done wrong brother, we have put I plus inside, we have to do it outside this English, neither is it an outer loop, nor is it an outer loop, okay, let's start, let's run and see where to subtract, what doesn't eat, very good starting. It will be like this, maybe the start length will be mines van and very good brother, all the cases which have been run, let's zoom out and submit, what is the time complexity of this, it is the big boss, okay, big off and the time complexity is and the space. How much is the complexity? Space complexity is also our big fan because we have an LED. Okay, so that much is in this video. You will get the link of the next video here.
Reverse Only Letters
boats-to-save-people
Given a string `s`, reverse the string according to the following rules: * All the characters that are not English letters remain in the same position. * All the English letters (lowercase or uppercase) should be reversed. Return `s` _after reversing it_. **Example 1:** **Input:** s = "ab-cd" **Output:** "dc-ba" **Example 2:** **Input:** s = "a-bC-dEf-ghIj" **Output:** "j-Ih-gfE-dCba" **Example 3:** **Input:** s = "Test1ng-Leet=code-Q!" **Output:** "Qedo1ct-eeLg=ntse-T!" **Constraints:** * `1 <= s.length <= 100` * `s` consists of characters with ASCII values in the range `[33, 122]`. * `s` does not contain `'\ "'` or `'\\'`.
null
Array,Two Pointers,Greedy,Sorting
Medium
null
387
hey yo what's up my little coders let me show you in this tutorial how to solve the lethal question 387 first unique character in a string basically given the string we just need to return the index of the first unique character which we see in this string let's consider this example imagine that's the input string so if we start with the first letter l let's see if it's unique okay it's not unique because here's the second order l so it's not unique let's go to the next letter what are all o else appears twice it's not unique then but if we go to letter v we don't see any other appearances of water v so which means that it's unique and in this case we just need to return the index of the sweater which is two this is basically what we need to do in this task and um how people would usually solve this question probably the majority of people would solve it using the hashmap let me show you what i mean so you have a hash map um the key is just to store the all the alphabetical lowercase characters from the english alphabet and yeah we can assume that all the letters will be lowercase so and the value will be used to just like you know count how many times each character appears in this string so after that you just iterate through the full string you update your hash map you count the how many times the character appears after that you go iterate through the input string again and in case if you see that like the particular character um on which you're pointing at the moment has a counter equal to one in a hash map you just return the character otherwise your term minus one so it's like a decent solution however it doesn't give you the best score it gives you the average score however because on this youtube channel you want to see how to solve the algorithms in the most efficient way so you don't ace your interview after watching these videos i will show you how to write the algorithm which gives you the 100 score but even though this approach is a decent one but anyway let me show you how to do it like in a better way okay let me just quickly write the code and it will be with you in a few seconds and it will explain to you everything okay guys here we go let me just explain to you everything basically we start with declaring the integer result we're going to return it in the end later for now it's equal to the maximum value which integers in java can be we'll come back to it later don't worry so then another one we call it first occurrence index basically we iterate through the whole english alphabet and we will use this variable to basically find at what index each character from the alphabet occurs for the first time inside the input string of course sometimes like some characters from the alphabet will not appear in a string at all but that's fine so after that basically we have a forward and as i mentioned we will iterate through the whole english alphabet only the lowercase letters because again this is our assumption that all the input strings will be lowercase so and yeah this forward we start with the letter a we say that it's equal to c is less or equal than character z so we will go from every single character from a to z all right so the whole alphabet after it again the first accuracy index we calculate at what index as each character occurs for the first time and you're doing it by calling the java function which is called index off this function is very efficient that's the reason why we're using it so the input string dot index of c so index of each character from the alphabet in case if this character doesn't appear in a string at all this variable will become will be equal to minus one because this is how this function this method basically works but if it's not equal to minus one which will mean that okay we found the index that's what the particular character the particular letter from the alphabet on which we are at the moment appears in the input string so if we have this index and this index is also equal to the index which another java building function which is last index of uh gives to us so if these two indexes are the same so the index of the first accuracy and the index of the last occurrence if they are the same it means that we found the unique character and we can update our result value we can't return straight away because you know we're iterating through the alphabet not through the string so if i don't know if would say we found the letter a which is unique in the input string but this letter is somewhere in the very end but after this will go to letter i don't know letter r and it's like in the beginning of the string of course that's the version which we need to return so for now we don't return we just update our result so we're using the mass dot min function and there are two parameters so the first occurrence index of the particular character which we're considering at the moment while we are iterating through all the english alphabet characters and another value of the result so which initially is equal to the integer max volume so we're basically iterating through the whole alphabet and we're updating result and we're just you know taking the minimum of the first accuracy index from all the characters so then in the end there's out and you will store the volume of the basically of the minimum index which is unique which represents the unique character and string so then once you iterate through the whole alphabet you will return the result in the end and that's it but if the result will be equal to the integer just max value which will mean that we didn't update the result at all it stayed as it was declared and which will mean that like there are no unique characters at all in the string in this case we will just return minus one otherwise we return result so simply as that guys okay i promised you that we are going to get hundred percent let's actually check if we will get hundred percent and we go hundred percent guys here we go simply as that guys okay i think that's it for this tutorial guys remember elite code today keeps an employment away so make sure you do lead code and practice as much as you can and you know challenge your friends to see if they can solve this question efficiently or not and guys in order to support me please subscribe to my channel and i will see you next video guys good luck
First Unique Character in a String
first-unique-character-in-a-string
Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`. **Example 1:** **Input:** s = "leetcode" **Output:** 0 **Example 2:** **Input:** s = "loveleetcode" **Output:** 2 **Example 3:** **Input:** s = "aabb" **Output:** -1 **Constraints:** * `1 <= s.length <= 105` * `s` consists of only lowercase English letters.
null
Hash Table,String,Queue,Counting
Easy
451
931
hey everyone today we are going to solve theal question minimum falling pass sum okay so let me explain with this example so description said when we move to next row we have three ways basically so directory below and uh diagonally left and right so my strategy is um to calculate the minimum number at each place and in the end in the last row um minimum number should be answer so I'll show you how and then we start from Row one and uh so for example so when we calculate a minimum number at this place so um possible calculation should be from here or here right because from um this place so we can move like a directly below or right and from here so we have three Bas right here and uh from here we cannot go like this right so that's why um when we calculate minimum number at this space so we should calculate like 2 + 6 or 1 + 6 and which is a minimum so I + 6 or 1 + 6 and which is a minimum so I + 6 or 1 + 6 and which is a minimum so I think one plus six right so that's why now at this place minimum number should be seven right and then move next so um we can actually reach this place from this place displ this place right so three ways so we calculate um three times and uh in this case I think 1 + 5 times and uh in this case I think 1 + 5 times and uh in this case I think 1 + 5 is a minimum right so in the case this place should be six and then move next so at this place so from this place and this place so we can reach current place right so that's why minimum number should be 1 + 4 and why minimum number should be 1 + 4 and why minimum number should be 1 + 4 and five right so we finish calculation at low one and we use 765 for next calculation so let's move on low two and let's calculate this place so again um from this place and we can reach like this right we cannot reach like this so that's why minimum number should be 7 + 6 right in minimum number should be 7 + 6 right in minimum number should be 7 + 6 right in this Cas and 1 and then move next so from three place and 765 we can reach this place right so that's why minimum number should be 5 + 8 and 13 right and number should be 5 + 8 and 13 right and number should be 5 + 8 and 13 right and then um for this place uh from six and five we can reach this space right so in that case I think 9 + 5 is a minimum and that case I think 9 + 5 is a minimum and that case I think 9 + 5 is a minimum and 4 right so we finish iteration all we have to do is return minimum number in the last row so we have two 1 so that's why output is 1 in this case so that is a basic idea and uh one more important thing is that we have to handle like out of bounds so let's say from this place we can um move to like three ways right but uh from this place so we can move just two ways so if we go to right diagonally so that is out of bounds and from this place we can move two ways right so if we go to Left diagonally so that is out of bounds so we have to handle out of bounds but I'll show you how in the next coding section yeah so let's jump into the code okay so let's write the code first of all let me change Matrix to M because the Matrix is a little bit long and uh first of all let's calculate the length of Matrix so let's say n equal length of M and then so let's iterate through Matrix one by one and calculate a minimum number at each place so for Row in range and as I told you we start from Row one and uh until end and we use one more for column in range and n and then um let's calculate a minimum number at each place so we can do like this so M and the row and the column plus equal so minimum number and uh we have three ways right so first of all for left so M and uh low minus one so this is above row and uh so for left side there is a possibility that we will be out of bounds right so to prevent that we can do like this so Max and uh index zero or um colum minus one so when we are out of BS on column minus one should be minus one right so in that case we will take a zero as a index number otherwise C minus one easy right and we need to Comm and then next so directory below so this is a very simple just m and row minus one and just colum right very simple and then we need a another comma and then for right side so M and right minus one and uh so this case we will take a minimum number so first number should be our last index number so in that case M minus one right or column + 1 so when we are out right or column + 1 so when we are out right or column + 1 so when we are out of bounds C + one should be so let's say of bounds C + one should be so let's say of bounds C + one should be so let's say our length n is three in that case C + our length n is three in that case C + our length n is three in that case C + one is three right so that is out of bounds in that case we will take our last index that is index two so otherwise C+ one very simple right and otherwise C+ one very simple right and otherwise C+ one very simple right and then all we have to do is just return minimum number at last uh row so mean and M minus one yeah so let me submit it yeah looks good and the time complexity of this solution should be I think o n Square that's because size of Matrix should be n byn right so we didate through all places 1 by one so that's why o square and the space complexity is I think o1 we update the original metrix so that's why we don't use a extra data structure or extra memory so that's why yeah so that's all I have for you today so please support me with your action such as comment or hitting like button I'll see you in the next question
Minimum Falling Path Sum
maximum-frequency-stack
Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`. A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(row, col)` will be `(row + 1, col - 1)`, `(row + 1, col)`, or `(row + 1, col + 1)`. **Example 1:** **Input:** matrix = \[\[2,1,3\],\[6,5,4\],\[7,8,9\]\] **Output:** 13 **Explanation:** There are two falling paths with a minimum sum as shown. **Example 2:** **Input:** matrix = \[\[-19,57\],\[-40,-5\]\] **Output:** -59 **Explanation:** The falling path with a minimum sum is shown. **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 100` * `-100 <= matrix[i][j] <= 100`
null
Hash Table,Stack,Design,Ordered Set
Hard
null
27
hey are you doing so today we're gonna solve question number 27 remove elements we're gonna first read the question I'm gonna show you the thought process and how we solve it and then finally we're gonna code some of the solutions okay stay tuned all right let's read the question remove elements is the question we have given an array of nums and a value remove all instances of that value in place and return the new length okay cool so in here we have to make sure we're given an array and we're giving a number right and we have to remove all the instances from that array in place that's why they highlighted it in place and return a new like okay so we can have to do two things one remove the instances and to return basically the new length of this new array so these are the two things we need to do okay do not allocate extra space for any other array you must do this by modifying the input array in place with o of one constant extra memory all right so you can't go and create like a big storage of n sighs you have to use something that is very predictable okay that seems pretty simple the order of the elements can be changed that's kind of a hint er it doesn't matter what you leave beyond the new length okay that's a really big thing to what why would they sometimes when you read these questions you have to ask yourself like why do they even bother giving me these extra tips right or if you're going through the interview why do they even bother to tell me like these little extra side hints now you can only run into one of two cases right one case is the interviewer can be like really you know a punk and just like throw you off because he's having a really terrible day or with a bit of the dough you're trying to give you a hint to solve the problem right so when we're looking at this problem before we code with to ask ourselves okay what's the problem really asking right so you're given a race size given number and you just to remove those elements and give that size of that new ring right if we didn't have the limitation of constant space of this oh and one extra space memory space this sounds like a very simple question right just create an array iterate through it and push the ones that are not equal to the value that you're given right into that new array all right that seems simple enough but the key thing is we cannot use that extra space right so what can we do to solve this problem right so when I'm thinking about okay what do I need to do if I don't know how to solve this so I knew I know I need to a I need to go through every single number right so at the very least my time complexity needs to be all event time because I need to go through every single number to check whether or not it is equal to the value right so we need to know that so there's gonna have a for loop in there right the second thing with the thing about is like okay well as I checked through the numbers right I need to do something right but I don't know what that something is yet but in our case we have to find a way to either a delete it or be you know move it around right because it says here that you could change it where dollars can be changed right that's a tip so with that in mind I feel like that there are some really nice JavaScript things that we could use something that really pops into my mind right now is like okay so native however functions are gonna be like something like splice you know as I iterate through the array if I see the number equal to the number that's given to me I could just you know splice that value out and to use splice for those who don't know you just give the index and how many items do you want to splice out and then that effectively manipulates the input right you could do that then and that would work but let's see if we could think about other ways to solve it because there has been cases where interviewers don't like you to use functions right they want you to almost you know reinvent the wheel effectively right so how can you achieve similar things but without using these high order functions right if you think about it all right so we know that we are given X amount of space right and we experiment spaces meaning it's the input erase memory space so if we look at the example here right you're given a memory space of four right it was a array size to Forbes it with three two three and a value of three right so what you have to do in this case when we eyeball it we know that okay we need to remove the tail and the front but keep the two here right simple enough and then return the two right but what can we use here that can help benefit us right that we can if we don't want to use splice this is all the source solution so let's think about it okay well what are the data structures we can use that is you know all one space right we can always just create a variable you know and make sure that variable is of size you know something to store right so we could go like okay maybe you can think about okay what's available to us we could I think we could probably think about well I could use a variable to store this artificial like a pointer in a sense right if you think about it if you have a pointer right pointing at the index like say I want to start with opponent as position zero right what I could do is well as I enter 8 through the input array I can see if that value does not equal to the value I'm interested in and if that's the case then why don't I just you know put that value where it belongs which is at my pointers reference right and then increment my pointer to the next item right so what I mean by that is that ok well if you're saying a pointer to say for example zero right and you start iterating through your rate at zero right and assuming that okay assuming this 3 was a 1 or something like that what's gonna happen here right you're gonna all really cop is gonna be your zero one zero you're pointing at zero right and you iterate you can check is my 1 equal to 3 no all right well I'm just gonna make that number that space at my pointer position equal to where I'm at right now right I can go any way through but if it equals to the same I might skip it right by skipping it you effectively you know eliminate it right so let's dive into some code and see where can you solve this all right function I'm gonna go and remove this just to make things a little bit more clean so I'm gonna start the first approach that we're talking about earlier one of the things we need to sometimes check or if you go to the interviewer you want to ask them hey are there any edge cases like is there gonna be am I getting be given gibberish I'm gonna if they don't tell you anything in this case it doesn't tell me anything I'm gonna assume that they give me gibberish so I'm gonna check you if my numbers are a is true or not and it's not true I'm gonna return a 0 right so those are like I always like to have the first segments on top segments to put in like these edge cases check that's always what I like to do and then what I was mentioning before we're gonna write a simple for loop for let I equal to 0 right I is less than my nums blank and my I it's plus so what we're trying to do here is iterate through every element of that array right and check if that number numbers at I if that number is equal to the value we're looking for right if it is well what do we do well the first case I'm gonna try is just gonna splice it splice at the I and give it a 0 1 right so what you're doing here and I'm what I'm gonna do is basically I'm gonna spice it up and then I'm also gonna go okay reset my position right because I'm gonna go inner eight oh I go to 3 I'm gonna splice it out so it's gonna move this element right finally make sure that I got to reset my index back to where I started right because my new array is gonna be like Oh two to three which positions zero still here right so position show will be two right so I'll check that number so I got to make sure I have to decrement it and then at the end basically this will clean everything and you just return the nums not life right and you should pretty much get what you need so let's submit this and try if it solves anything great so this solves pretty much 99% of everyone and great pretty much 99% of everyone and great pretty much 99% of everyone and great space complexity too right however let's try another approach so we know that this way works but say you're not allowed to use splice right so what can we do here right so one thing we could do was mentioning before well why don't I create a variable well that's no pointer equal to zero right so this is gonna point into my like Mike I guess like the shadow reference you can think about it out that way and what I'm gonna do this time around is check and what I'm gonna do here is like skip the numbers that are not equal to my value right so my check here make sure I skip those numbers right and but the difference here is that I'm gonna be doing this all right well I'm gonna go set my nums at I actually don't have my pointer well equal to the value F nums at I right and then increment my pointer right so in this case what am i doing effectively I am just incrementing my pointer as I get items that are not equal to the value of them looking for right so in here I'm just gonna return my pointer the point will pretty much tell me the actual length of this new array without deleting anything right you know first approach we deleted things this one we don't really need to delete things we're basically shuffling numbers around within the same array and the pointer will basically indicate how long or how big that item would be right so let's see if this solves the problem hey yeah it does solve it's not as great as a splicing one but at the very least you can solve this problem you know that there's two approach one is you shuffle numbers around two is you actually just delete it in space and yeah that's pretty much it I hope you guys enjoy it if you like it this type of video give me a thumbs up if you don't you know just let me know in the comments and how I can prove I'm going to try to continue more now since we're all in this special situation but yeah hope you guys have fun and learn more delete code see you guys
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
437
that's our time complexity for the two function approach o of n square now that we understood the time complexity of this approach now we can go and optimize it hi guys how are you all doing in this video we'll take a look at path sum three problem difficulty level is medium so let's see what the problem description is so we're given a binary tree and in that tree each node represents a integer value and along with that we're given a target and we need to find out the path or the subtree in that tree whose summation would be equal to that target so if we take that example 3 let's say this example then if we know take nodes 5 and 3 then our sum would be 8 which is our target if we take node 5 and 2 and 1 then again our sum would be 8 or if we take node as -3 and 11 then our or if we take node as -3 and 11 then our or if we take node as -3 and 11 then our sum would be eight so those would be the three part that would give us some eight so we need to return the number of such path that gave us the target so in this case our return value would be three because there are three parts and there are some limitations like there won't be more than thousand nodes and the node values would be ranging between minus one million to 1 million so it doesn't mean much it just means that there are a thousand nodes and we can potentially have integer variables hold all the sum and everything we don't need to think about interior overflow and all that so that's the problem let's see how we'll solve this problem okay this is our whiteboard for path sum three problem and we have this tree exactly same from the problem description and our target sum is eight so as we can see there are three parts five three then phi two one and then minus three and eleven these three part give us the target sum equal to it now before we move forward with approach and solution i want to clarify that this problem is about path and not subtree i mentioned subtree in my problem description but that's not entirely correct uh so a sub tree would be like five three two so this would be a subtree but this is not a path so what they say path is like part starts from any node and keeps going down only so we need to find path uh a difference would be like let's say if they said like you have to find subtree then it would be something like 2 phi 3 minus 2 this would also give us eight so that's the difference so we need to find path and not subtree so let's focus on finding those path this does look like a complex problem but we'll go step by step we'll first have a simple solution we'll look at the time complexity and then we'll try to optimize it so let's do that let's try to solve this problem okay so what we'll do is to implement this or to approach this problem we'll try to implement this in two functions so let's say we have one function as f1 and other function as f2 so let's first try to look at what we'll do in function 1 and then we'll go to function2 so since the important part in this problem is that path can start from any node it doesn't have to start from root and it can end anywhere it doesn't have to end in leaf node so what we'll do is we'll have this function one what it'll do is for each node it'll call this function one again and it'll pass the same target so let's say if this function 1 is called for 10 with target as 8 what this will do is it'll recursively call for all the nodes so it'll call node 5 with same target it will call it for node minus three with same target as eight and subsequently they'll call their children's for the same function so this is kind of starting function where each node will think that i am the starting node in that path and i need to find that target in my children path along with my value so that's what this function will do recursively so now all we have to do is we have to write function f2 which will start calculating the values and then we'll have our count so let's see how we'll do that so now once this f1 is getting called for each node what we'll do is we'll call f2 for that node and we'll say start calculating the path or start finding the path and try to find this target or sum and that's how this will get started so f2 will be called for 10 f2 will be called for 5 and likewise for each node and then what we simply need to do is we simply need to add all this stuff and then return it so let's see what we'll do in this f2 to calculate this path so again f2 is recursive function so if node is null then return zero obviously and we'll start counting how many part are there whose target is equal to the sum so obviously if node value is equal to sum we'll say okay you know your node value is sum so that's it one path found so count equal to one and then what we'll do we'll calculate new sum where sum minus node value and then we'll say okay in the left tree try to find this new sum or in the right tree try to find this new sum and give me all the path and then return all those count so let's take an example okay so let's say for this five we called f2 and our target is eight so what this 5 will do it'll come here obviously 5 doesn't match 8 so we'll go here our new sum will be 8 minus 5 which will be 3 and this will say node.left node.left node.left and new sum is 3 so when will come here it will say okay node.value is 3 it will say okay node.value is 3 it will say okay node.value is 3 count is equal to 1. so we'll like try for more children but it'll not find and it'll eventually return 1. so we'll find our one path once this is done this will say okay find node.write which is here find node.write which is here find node.write which is here find the new sum3 now this will go here node value is 2 sum is 3 doesn't match so i'll come here now new sum would be 3 minus 2 which is 1. so this is done and our new sum is now 1 and we'll say okay this is null so node.write new sum is 1 call it node.write new sum is 1 call it node.write new sum is 1 call it and then this will call 1 matches 1 count 1 all the childs are null so we'll return 1. so again we'll find one more path and likewise we'll find this path also so eventually we'll get our three count for this so that's the implementation for this breaking up into two functions and function one is responsible making each node as the starting of the path and then function two is responsible for calculating that sum in that path so let's go ahead uh let's write this code and run it and make sure it passes all the test case and then we'll uh we'll actually come back and we'll look at time complexity and then we'll see if there is any optimization into it so but let's write the code for this and let's submit this code so this is our two function approach that we just did on the whiteboard this is the actual code for this so we have our initial path sum method and we'll recursively call this method for the children's of the current node and we'll tell them that start finding the path for this target and we'll do this for all the children so that each node thinks that it's the starting node in the path pathfinding process and that's what part sum2 will do you'll start finding the path for that particular target and what some do will simply take that node value subtract it from the sum and we'll call it for the left child or right child whichever returns that path will keep adding those count so that's the code let's run it ah let's make sure that it runs for the sample test case it does and now we'll submit it and we'll see if it runs against all the test cases uh looks like it just finished and it took around 21 millisecond around 42 faster than other submissions so it looks like there is some scope for improvement so before looking at optimization what we want to do is we want to look at the time complexity of this solution and then think of optimization so let's do that so to understand time complexity for this uh approach i've taken a different example i hope this helps us understand time complexity much easier uh i actually want to go into detail uh of this uh time complexity for this one because uh i've seen like i was reading it and i've noticed like a lot of people have referred this approach the two function approach as of n time complexity it's linear but i don't think that's entirely correct uh let's see what time complexity we can come up with so we know the approach we know that uh we'll call function one for each node and then each node will call f2 function two so let's see what happens when we call f2 for from phi so we'll go down for each node and we'll try to find this target right we'll say five so we'll subtract nine from five we'll say now we need to find four so we'll go here and we'll find the path as nine but we'll still going down just in case if there are negative numbers and we can find more path right so if we call f2 for five we'll traverse five nodes which is n nodes right now we'll call f2 from four and will traverse four nodes likewise which is n minus one now for three we'll call three nodes and will traverse three nodes which is n minus two and likewise we'll do it for rest of the nodes so this is our complete traversal complete time or nodes it'll take to give us the output so if you look at this pattern or this one we know the formula for this summation right this is n into n plus 1 divided by 2 which is 5 plus 6 divided by 2 which is 5 into 6 sorry so which is 15 right so 5 plus 4 plus 3 plus 2 1 is equal to 15. now if this is our time taken or this is our time complexity what this comes to is n square divided by 2 plus n divided by 2. now when we have n square we can ignore the linear part of it in terms of square that's more prominent and we can obviously drop the constant so our time complexity comes to o of n square so that's our time complexity for the two function approach o of n square now that we understood the time complexity of this approach now we can go and optimize it so we'll look at optimizing this uh approach we'll see if using some additional storage can we come up with approach which takes o of n time so let's do that so we go back to our original sample tree uh our actual target is eight and we'll try to see if we can come up with approach which is better than our previous approach so over here we'll use a technique called prefix sum uh but name doesn't matter much right i mean really my what really matters is how we can use it to solve this problem so in this approach what we'll do is we'll have a dictionary or hash map where we'll store the running sum of the path and will count how many times we've seen those values so without talking much let's actually first create that hash map and see how it looks like for the sample tree okay [Laughter] [Laughter] [Laughter] this is the crux of this approach that will help us find that path whose sum is that target so now let's say we have this dictionary and now we start traversing uh the tree again i mean in reality we'll be doing together but just for simplicity we have this and now we are traversing the tree so let's say we started traversing tree from here and we keep a variable called running sum now when we are here our running sum would be 10 when we come here our running sum would become 15 and when we come here our running sum would be 18. so let's pause here and let's think about it now we know that this phi 3 path is a valid path whose target is 8. so from this traversal can we find this path using this dictionary so now we've traversed 10 5 3 and our running sum is 18 right and our target is 10. so the trick that we do is that from this complete traversal to get this target 8 is there a previous path that we can eliminate so if we eliminate 10 then we get our path required path which is 8. so how do we find this 10 and how do we check if we ever hit this 10 or not so what we do is we do obviously this running sum i'll just write rs running sum we'll do minus our target so this will be 18 minus 8 and 10 so that gives us 10. and how do we find out that whether was there a 10 in the path like was there any previous 10 that or was there any some path which had 10 we go to this dictionary we say that this dictionary you have running some minus target in your anywhere in your keys so this dictionary says yes there was a path or a node whose sum was 10. so if we find this then we can say that yes there was a 10 and we can remove that and we'll get our path so we'll say that yes that's the count we need so we'll take count plus equal to 1 if we find this right so that's how we are using this dictionary to calculate the previous path that we can get rid of or we can think of that yes we had hit that value and if we remove that from running sum we'll get our path so let's make sure that we see it for one more example so uh same for this path right so 10 phi 2 1 again this is 18 so we'll again do running some minus target 18 minus 8 10 and we'll say yes we had seen 10 and we want to remove it so uh there was one path where it was 10 so we'll do plus 1 and then same for this part also right 10 minus 3 which is 7 and then 11 which is 18. so we'll do again same thing and we'll do plus 1 so we'll get our total three part so we're using this dictionary to find out that was there a previous path whose if we can remove that path we'll get our target so we do running some minus target to get that previous path and if there was a previous path with that value then we can say that yes we can make a path which is equal to it so we'll use this approach to optimize our previous implementation now we what we'll do is we'll traverse the tree only once as i said like we'll be calculating this dictionary and we'll be doing this calculation at the same time when we are traversing the tree so our time complexity would be o of n where n is the number of nodes our previous approach had time complexity of o of n square and this would be o of n so when we actually submit the code we should see some improvement so uh there is one more thing which i want to point out uh in the initial part of the video we differentiated between subtree and path so that differentiation is important here so i just created a like crude and simple explanation but in reality what we need to do is uh when we are traversing this path we'll be obviously calculating this dictionary and everything but once we finish this path we'll start traversing this path right and this path and this part so what we need to make sure is when we are done traversing this path we need to remove these values from dictionary so 10 5 3 which is 21 so once we are done traversing this path we need to make sure that we remove 21 when we are done traversing this path we need to make sure that we remove 15 from the dictionary or we reduce it by one right so that when we are calculating or when we are removing the previous part we don't hit those values right so that's the important part to understand between path and subtree if we had to find a subtree we would have done different logic so that's a little bit of backtracking removing values from dictionary so i'll actually show you when we actually go to the code on how we are doing that's simply just like once the function completes subtract that value uh from dictionary by -1 so dictionary by -1 so dictionary by -1 so let's go to the code let's see how actual code looks like and then submitted and let's see if we get any our final code for the hashmap base approach we have our hashmap declared here and then we call our path some do function where we start running sum as zero and what we do we add the root value into running sum and then we try to find out count where if we can get rid of any previous path and get the required path so we do running sum minus our target so if you remember our whiteboard we did like 18 minus 8 which was our target and we found out 10 and we had a path previously where 10 was there so we say that if we find that then we found one valid part or however many number of valid path are there and then we increment our map with current running sum and then we subsequently call path sum2 for left child and for right child and the remaining part that i said i will soon show in the code is the backtracking so once we are done with the current node and all its children what we do is if we remove that value or that running sums count we reduce by one hence we remove that node from our map and when we move to the other part of the tree we don't account for this node so that's how we backtrack and make sure that we are doing path and we are not doing subtree so that's what takes care of it and eventually we return the count so one thing we didn't talk about was we are adding a arbitrary value in the map we are saying that for running some zero just add one straight away now what this will do is this will take care of the root node whose value is equal to sum or target so let's say if our target is 10 and our root node is 10 itself then we'll come here we'll make running sum as 10 and we'll say running sum minus target 10 minus 10 which is 0 is there any key which in dictionary which has value 0 then we'll say yes there is 1 and that will be our count and then we'll say that's a valid path so root node itself can be a valid path and that's what this dictionary arbitrary value or map arbitrary value is so adding 0 and counting it for one so that will take care of root node so that's it guys uh let's run the code make sure that it passes the sample test and then submit the code and then run against all test cases and let's see how long it takes so let's see so it took two milliseconds it's faster than 100 of all the submissions so there you go guys the time complexity of this approach is o of n and the previous two function approaches o of n square so i wanted to show both the approach so that you guys have complete understanding and even though we have seen this approach ah i know this is complex and tricky to like visualize it and imagine it because we're removing the previous path from dictionary and we're traversing the tree and we're calculating the dictionary everything is happening at the same time so uh just take this code like i'll put the link in the description below uh run it or if you have whiteboard or if you have notepad and pen draw out a different tree of your liking and run that tree against this code and try to figure out why it works the way it's working and then you guys get a feel of it so try to do that uh let me know if you guys still have confusion questions let me know in comments or if you have any suggestion any better approach let me know in comments and then the usual part subscribe like and hit that bell icon for notification and i'll see you in next one
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
456
hello everyone welcome to our channel code with sunny and in this video we will be talking about the problem one three two pattern of fleet code its index is four five six okay so before moving on let's talk about the prerequisite that is being required when you solve this problem you must know the concept of binary search like if you are using uh c plus language then you must be familiar with set upper bound set lower bound you need to know these type of things otherwise you can implement uh also okay so what i would be doing is like first let's look over the related topic section so this problem can be solved with help of stack but i have solved using binary search analysis i will discuss this solution so given an array of n integers nums one three two pattern is a subsequence of three integers numbers of i numbers of j and numbers of k such that i less than j less than k and numbers of i is strictly less than numbers of t and is strictly less than numbers of g note that numbers of k must also be strictly less than one subject we need to return to if there is a 132 pattern in numbers otherwise return false okay so we will be discussing all the examples over here first then we would be approaching to the solution that i would be discussing right now okay so let's discuss the example one two three four one okay so let me kill the color one two three four okay so uh a 132 pattern is nothing but a sub sequence such that we would be uh it could be satisfying this condition numbers of i must be less than numbers of k must be less than number of g okay so first you are going to choose 30 just let's say you are going to choose this one and this one let's call these three integers as a b c okay so when you choose these three integers they must be satisfying this condition c must be less than b must be less than e okay note that the third integer which we have chosen must come in between and the second integer that you have used must come in the rightmost side and the first integer that you accuse it must come to the leftmost side okay so if these three integers satisfy this condition then you are going to say yes we have this 132 pattern okay so let's check whether there is a 132 pattern in one two three okay so what we're going to do is we're going to start with this one and fixing it as p and then we are going to choose a and c where a and c are the left most and right most uh integers fusion respectively okay so when you choose b over this position there's only one way you can choose a so a would be lying over here and c can be this one okay as i've already said c must line between then less than b then less than a now you can see b is already two and c is either three or four and a is one okay so you can see if you fix if you write down c as either three or four it will not satisfy this condition okay so fixing b over here is not optimal so let's fix b to the next position so i'm going to fix this b over here so see there's only one way that we can have c so i will pick c over here and b over here and a over here now note that a can be this one or can be this one now you can see since 4 less than 3 is not satisfied you are going to say no this is also like this is also not a 1 3 2 pattern ok so in this entire area that doesn't exist in the 132 pattern so we are going to output first so let's check how the output is coming out as 2 in this case 3 1 4 2 okay so let's say i'm going to fix b over here okay as i've already said c must be less than b must be greater than a so b is already one must be less than c is going to lie over this one or this one and a is going to be this one so i will write down three must be less than a but note that this condition will never satisfy because 3 is already greater than 1 but in this condition it says that 3 must be here this 3 is less than 1 which is also 1 3 2 pattern is not like it's not existing if b is over distance so let's fix b to the some else position so we'll fix b over so 4 must be less than c must be less than sorry 4 must be greater than c must be greater than a so a is only is having these two positions so and c is only having one position so i will write down 2 less than 4 must be 2 must be greater than e now a can be either this or this right so i will write down a as 1 so as 1 2 and 4 now you can see that this sequence is satisfied once we pattern satisfied what if i will write a as three if i will write a s three less than two less than four which is not satisfied so there must exist at any one three two pattern sequence then we are going to return blue if you will fix as1 ch2 and bs4 then we will say yes this one speak to pattern sequence exist okay so yes this case like the output is coming out that's true now uh how we're going to find out the general approach we solve this problem i will take the same example and explain how we are going to do that okay so it is like very much simple like you have you're going to choose three integers right a b c okay and it must satisfy c must be strictly less than b must be strictly greater than a now you can see whenever you are at any current position let's say at this position where you are having b what you will do is like you need to find the small like the largest integer which is strictly less than the value b and must lie to the right side of this b okay and i'm telling it once again you are at this position you need to find the largest integer which is the right of which is present to the right of this current position uh where the element b is and the value must be strictly less than the current value of the current position element which is b okay so how you're going to find it out so you must store all the elements to the right of the current position in the set that can also store a duplicate element then you must find out the lower bound of the current element b let's say we have the elements there called as 2 3 4 5 and the current b is let's say 4 so the lower bound will come out to be this one fourth position but you need to find this more greatest element which is strictly less than the value b which is nothing but this element so you will uh decrement one position back for the current iterator then you will get the greatest element which is less than strictly less than the current element b and it is present to the right side of the current position note that you need to store all the elements uh to the right of the current position in a set a multiset then you will you are going to find out the lower bound then which will help us in finding the greatest element which is strictly less than the current element value and which is present to the right of the current position now if you are able to get that element and c is going to be strictly less than b satisfied then you need to find the value of e like if there exists a which is going to be strictly less than this now you can see if you satisfy this condition you need to find the minimum element which is present to the left of the current position let's say the current position is i then you need to find out the minimum element which is present in the range 0 to i minus 1 if you are able to find out this minimum element and that satisfied that satisfies e is strictly less than c is 50 less than b then you are done then you have a 1 3 to pattern with the array so let's check it out how we can implement that efficiently i have accepted 4 so the time complexity would be of n log n because every time you would be searching for the greatest element which is strictly less than the current element which is present to the right of the current position so you will keep track of minimum element and you are going to store uh all the elements first in the multiset and as soon as you get an element you will decrease the degree like you will erase its entry from this multiset then you are always left with all those elements which are present to the right of the current position so we will find out the lower bound of the current element then you will check it out whether there exists the greatest element which is strictly less than the current element which is also present to the right of the current position if it exists and minimum is strictly less than iterated then that is that value which is strictly less than the current element value and which will also present to the right of the current position if minimum is strictly less than val that value that we are going to return to note that we are also updating the minimum value because so you at every position you need to know the minimum in the range 0 to y minus 7 and if all goes well and we are not going to find any element any pattern then we are going to return false final so if you guys are still any doubts you can reach out to us through the comment section of the video and thank you for watching this video you
132 Pattern
132-pattern
Given an array of `n` integers `nums`, a **132 pattern** is a subsequence of three integers `nums[i]`, `nums[j]` and `nums[k]` such that `i < j < k` and `nums[i] < nums[k] < nums[j]`. Return `true` _if there is a **132 pattern** in_ `nums`_, otherwise, return_ `false`_._ **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** false **Explanation:** There is no 132 pattern in the sequence. **Example 2:** **Input:** nums = \[3,1,4,2\] **Output:** true **Explanation:** There is a 132 pattern in the sequence: \[1, 4, 2\]. **Example 3:** **Input:** nums = \[-1,3,2,0\] **Output:** true **Explanation:** There are three 132 patterns in the sequence: \[-1, 3, 2\], \[-1, 3, 0\] and \[-1, 2, 0\]. **Constraints:** * `n == nums.length` * `1 <= n <= 2 * 105` * `-109 <= nums[i] <= 109`
null
Array,Binary Search,Stack,Monotonic Stack,Ordered Set
Medium
null
606
hello everyone so in this video let us talk about one more problem from lead code it is an easy problem which is construct string from binary tree so you are given a root of a binary tree and you have to construct a string out of that which consists of parenthesis and integers of that binary tree with the pre-order traversal of that tree now the pre-order traversal of that tree now the pre-order traversal of that tree now that's the whole thing that you have to do a pre-order traverse of the string do a pre-order traverse of the string do a pre-order traverse of the string like this whole tree and just find out this top of like if there's an output this particular tree in this like in this manner that is it is one then it is two and this three so like battery increasing whenever i completed the bracket closes out so now we move to the right hand side bracket open and so on so different trees in the nested form is stored so like it's the first tree that is one in the nested form it is two and four and so this is the left half and this is the right half so that now what you can actually understand is like we have to do pre-order that is like we have to do pre-order that is like we have to do pre-order that is fine but there is one small thing okay if you understood just go over the examples every time for any problem so what you can see is that in this problem as well and this problem what you can actually see that if we go on the left hand side it is having like 2 on the left hand side and it is having 3 on the right and third is fine but on the two on the left hand side there is nothing so they have put an empty bracket or on the right hand side they have something so they put four so what you can directly understand is that if there is nothing on the left hand side you have to still put a bracket out there but if it is on the right hand side if it has something that is fine now but if there is nothing on the right hand side let's say like this then you don't have to put a bracket for the right hand side all right instead of you don't have to put anything but for the left hand side you have to put if the left side doesn't have anything but right inside have then you have to put a bracket to understand that this is not the left hand side but the right hand side so that you understand this is a drive itself okay you have to understand this from this maybe let's see from this there might be a problem maybe to convert this to an pre-order traversal pre-order traversal pre-order traversal so you can understand that this bracket like it will not cause any ambiguity that this bracket is for the right-hand side tray not the left-hand right-hand side tray not the left-hand right-hand side tray not the left-hand side and similarly the left-hand side is side and similarly the left-hand side is side and similarly the left-hand side is empty but from this you understand that there is only one so that is only left hand side at the point okay now how you can do that it's very simple you have to just do a pre-order you have to just do a pre-order you have to just do a pre-order traversal using recursion and then at every point you have to just check that if for any note if it has no nodes as a child node which means it is a leaf node then you don't have to go any further you have to just print out that inside a particular parenthesis if it if any node doesn't have any right node only has a left node then you have only one bracket if it has a one right node and left node just do your recursion that is fine but it doesn't have any left node but it has right node so you have to again put a packet for that's the overall thing i don't have much to explain here because you will understand it from the code part because but that's our logic here that you have to just understand that this part is most important here let's move on to the code part if you doesn't understand we'll take one example as well what we'll do is that we have called a function that is built passing out this route this build function will take the root because the base conditions are there the base condition is that if the root is null there's nothing more to traverse then you turn the empty string else if the left and right are both which means that it is a leaf node then what we'll do is just we'll just print out the value of the node we are on we don't have to it any further down the line if the right node is null we only have to enter over the left node what i'll do is that we will what you have to see is that we will take the current value like whatever the value you have and then in the brackets iterate the left node value so it's better what we are trying to do is that we this is the value it is the value and in the brackets we are storing out the left and the right subtree values for a particular node so what we are trying to do is that for this value the left value only exists so we will only exit the left hand so left value in the brackets is so we will call this build function again for the left hand side of the tree node and put that in inside this bracket right but if there is the left right node is not null which means that it has something what we'll do is that or maybe the right node has something which means that we have to also take care of the left as well as right so we will first print out the root node value and then in the brackets store the left half like it did over or call the left half as well as now iterate over the right half as well okay we'll because let's say the left half will give nothing but an empty string because there it has nothing to be traversed out still we have an empty brackets up and closing and the right will have something so it will be stored inside this and call inside this and just stored inside these packets but if the right is null we don't have to give an empty brackets out there we just have to print one brackets for the left half of the tree and that's it and the value of the root like the node we are on similarly this is the recursive function this is the two base condition this is the conditions for the recursive part that's the overall code part i don't have much to explain here as well because you can understand it much clearly when you read the code part or if you just draw a route some of the cases because we have to go on the right hand side as well left hand side if both the nodes exist you have to only go like we have to print an empty parenthesis if there is nothing left hand side but there on the right hand side and don't have to write down anything for the right hand side if there is only left hand side there's only like two three cases you can add none and just very simple to put out this is a very standard type of things which is generally used in different problems so it becomes very intuitive when you solve your platform that's the rule tango stuff for random city it is like trading with the whole tree so it is like of n you're a traversal as well as nothing is stored in the space so no space not like oh fun you can assume uh and penguin city is off there's all time on city and space community for this problem if you still have any notes or if you want to give more suggestions for subscribe videos do ping me in the comment box and i will see you in the next one like recording and bye
Construct String from Binary Tree
construct-string-from-binary-tree
Given the `root` of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. **Example 1:** **Input:** root = \[1,2,3,4\] **Output:** "1(2(4))(3) " **Explanation:** Originally, it needs to be "1(2(4)())(3()()) ", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3) " **Example 2:** **Input:** root = \[1,2,3,null,4\] **Output:** "1(2()(4))(3) " **Explanation:** Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-1000 <= Node.val <= 1000`
null
String,Tree,Depth-First Search,Binary Tree
Easy
536,652
1,624
hello welcome to today's daily lead code challenge let's get to today's question 1624 largest substring between two equal characters all right so this is an easy level problem let's get to the description given a string s return the length of the longest substring between two equal characters excluding the two characters if there's no such substring return1 a substring is a continuous sequence contiguous sequence of characters within a string all right and then we have some examples the longest contiguous substring between a and a is zero between a b c a is two being the B and the C between c b XY Z or zxy 1 because there are no similar characters there are no characters that are the same all right so um it's pretty obvious that we have to keep track of start and finish for the characters that are involved let's see maybe what some of the constraints are there any odd characters no it seems like the only characters that appear here are the lowercase English letters um so we have an array or two arrays of 26 um and both keeping track of the two portions that we need to know the start of a character the first occurrence of a character and the last occurrence of a character let's just say this here times 26 and then we have last occurrence 26 let's have the res be Nega one and now it seems to me like we just have to iterate over all the characters in s and um and find the first and the last occurrence okay let's do this uh for CN and let's have a let's have the index as well and numerate uh s okay index let's have the index here it's going to be the order of the character that we're exploring right now if uh if C if index mhm if first occurrence of the index that we're exploring let's do c in DX C's index X is equal to -1 that means that we is equal to -1 that means that we is equal to -1 that means that we haven't found we haven't seen this character yet and if that's the case then we simply get this equal to the I else if we have already seen this before then we do the same thing but with c Index equaling with last occurrence equaling to I so now at the end of the traversal we should have a two lists the first and the last index the last first and last occurrence um arrays that are that tell me exactly what the first and last occurrence of each character are and they're going to be oops what did I do first occurrence times 26 index oh order of a so what I'm doing here is order tells me what the ASD character order is of a character if I want to have it zero indexed I have to subtract order a from it okay so now I get the um I get the characters here and you can see that the first occurrence of a is zero the last occurrence of a is one so all we need now is a return statement uh that says that uh oh no sorry each time I'm going to be doing this I also want to Max um uh size I want the max size to tell me exactly what the max size between the last occurrence of a c DX and a first occurrence of a c in DX okay now for the return value let's say it's going to be Max size um is going to be minus one because they want in this case the first occurrence is zero the last occurrence is one the difference between of them would have been one but we need zero if Max size is greater than or equal to Z else 1 all right and there we go pretty intuitive and we are 47th percent uh 40 26 percentile not good let's see what some of the other Solutions are maybe a bit faster um all right so they're proposing not even keeping track of the last character at all which makes sense last character is really not needed so what if we just say wait what was this last occurrence is just the I right so what if can we just say I here um would this also work yes and then we will remove this guy entirely from the but that seemed to have ran even slower okay let's submit this one more time without the initiation of last occurrence and if this doesn't work any faster then I really don't think this has anything to do with our code we are doing everything extremely efficiently we're only using one array just like what is happening here they're using a dictionary they're not using order okay so um I don't know if this is even worth going into but uh another way doing this is just having a dictionary and then removing this entirely and saying if um let's see default dict with the lamb. X equaling um1 okay let's do this one more time uh default yes I did mean that and a Lambda for initiating the index is not defined uh we just want the C here in that case cc is if this works any faster then sure but I like the array approach more personally and it doesn't all right so in that case let's stick with this approach um it's very common to define the property of a character within an array because it has this linear property you can they're and they're all consecutive um they very easily presented with ask key orders um in a simple array all right well let's end this here thanks for watching um I'll see you guys tomorrow bye
Largest Substring Between Two Equal Characters
clone-binary-tree-with-random-pointer
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
133,138,1634
1,762
hello everyone from today onwards I'm starting a series in which I'll be solving some lead code premium questions with different categories and different tags so as we know that there are not very much uh premium questions videos available on YouTube and internet so from now onwards I'll be solving only the lead code premium question so this is the first question it's very easy question not very much difficult but it's very interesting so let's just jump into the question and see how interesting and how easily can we solve this question so the question is building with an ocean view so question says there are n buildings on in a line you're given an integer height of size n that represent the height of the building in the line the ocean is to the right of the buildings a building has an ocean view if the building can see the ocean without obstruction formally a building has a ocean view if all the building to its right have a smaller height so the question Crux the Crux of the question is not very much complex I will just try to guide you and uh tell you that how the question says the question is saying that there are it's given an array which is considered to be as the height of the building the values is the height of the building so let's just take the first example which is 4 3 4 2 3 and one so these are saying the height of the building these are considered as the height of the building so as we can see there are four building with different height and the question says there is a ocean on the right of the building so let's just draw ocean great so this is an ocean which is on the right of the building or all the buildings it's not in between of somewhere or something but it's on the right corner of the array so it's saying the question is saying a building can view this ocean only if the height of the building is more than height of the building which is coming in front of him or which is coming uh ahead of him so it might be possible that there is one more building which has a height of this much might be let's just suppose five so if I'm considering this building has a height of five then no other building can see this ocean because the height this height is the maximum height that we can see over here so no other building can see this ocean so let's just remove this one so here I can see that okay one is smaller so uh by seeing this question I can add an intuition in our mind that okay that's for 100% sure whatever the height of the for 100% sure whatever the height of the for 100% sure whatever the height of the building of the first uh element it will always see the ocean I'm damn 100% sure that it will always I'm damn 100% sure that it will always I'm damn 100% sure that it will always see the ocean so I need to follow up with the rest of the buildings I don't have to consider with this building okay um because we are 100% sure that okay um because we are 100% sure that okay um because we are 100% sure that okay this building can see the ocean so let's just uh take rest of the building and see what will happen with the rest of the building if this is the height if this height is one okay cool so the next area's height is three the next building's height is three okay let's just suppose okay the building height is three the building which is in front of him is uh is heighted with one so we are 100% uh is heighted with one so we are 100% uh is heighted with one so we are 100% sure that okay this building can see this view this ocean because it height is more than any of the building which is in front of him so okay cool this can see the view let's just consider this too this is a pretty confusing like what why this should be they should see the ocean but no it's not possible because the height of the building is three which is in uh which is coming in front of him and uh he won't be able to see the building so this building can't see and this four this building four can see this view Ocean View easily because uh the any building none of the building has a height which is more than four or even equal to four so we can consider that okay this can see the view so it's very it's looking very pretty easy question not very much um comp Lex uh so we can make an intution that okay uh if I have to see this ocean I need to follow up from here not from here if I'll follow up from here it won't be able to uh I won't be able to know that which buildings are have a height more than the previous building so we need to return the indices of all the buildings who all can see this ocean so if I'm saying this so in this three we'll always see the ocean that's that is for sure two can also see the ocean one cannot see the ocean and zero can see the ocean so we cannot return the array like 23 or 302 or something like that we have to arrange it in ascending order so we need to do find something which will give us a proper uh answer in ascending order okay so what comes in our mind so if I can see this question I need to consider a maximum heighted building if I suppose there is a building which has a height of8 here so this building can see the ocean for sure now this building has a height which is more than the height of any of the building which is ahead of it so this building can dominate this area okay so if I'll consider this whole portion if I'll see any of the building in on the right of this building there's none of the building which has a height more than this building so I can see I can say that if anyone has to see this ocean behind this building he has to be more than the height of this building else he won't be able to see so we need to consider we need to have store it somewhere that what is the maximum height of the building so in this case we can use some kind of a stack or something like that okay um this building has a more height than the any of the previous building I'll keep this building in on the top next building comes okay this building has a more height than any other building then I'll keep that building on the top uh like eight is the height so eight will be on the top if any of the building which has a height 10 so that 10 will be on top if any building which has a height of five I should not keep height of five over here why I'll keep height of five because uh it can never see the ocean okay so we are following up the question and it's pretty much simple and easy so if you got this question we can just start to code uh at first you try by yourself and uh if you'll get the answer you can match with our my code or if you didn't get it I'm there for you so let's just start with the uh solution okay so what I'll do I'll keep a stack of integer uh let's say it's name is HD start a for Loop okay so I have to start from right to left okay so I'll be starting from right I'll go to left by reducing one now what I need to do I need to store so uh as I said that the first building can always see the ocean right this first building can always see the ocean so I'm 100% sure that first the ocean so I'm 100% sure that first the ocean so I'm 100% sure that first building can see the ocean so I can directly put uh inside this stack st. push Heights do size minus one I'm keeping index over here why because I need to know uh I need to return the indices and not the height of the building so if I need to return the indices I need to keep the indices in our stack so I'm keeping the indices in our stack so next what I will see what I will suppose is um if the height of the building which is inside a stack is more than height is less than the height of the building which I'm getting so in our stack three index is kept now the next array is we do not have this in the example so the next building okay let's keep this as eight so the next building is height of eight so we need to check okay the value at index 3 is if it is uh lesser than the value that we are considering then we'll push the index uh let's just suppose this has the index two so we'll push this index in our stack now if three this has a less lesser index value so what we'll do is we'll not keep this in our St because this will never be able to see the ocean this building can obstruct it so considering that example we'll just try and solve the question if SD do top so I'm keeping the entrix so I need to check from Heights hd. top if this value is lesser than the heights of I that we are considering right now then what we will do we'll push I in our stack simple now let us um after pushing all the elements what we will do is we will uh start popping out from the array and we'll make our answer so make for making our answer I need an integer variable result so while stack is not empty I'll be uh pushing all the stack values into our result so this will makes make sure that I have the answer in ascending order and not in any other order let's just check if it is working or not so okay all the test cases are passed so let's just submit it and check cool so it's working so what's the time complexity of this so the time complexity of this will be o of n because we are not doing anything else we are just putting it in our stack and comparing with the top of the stack so the time complexity will be o of n talking about the space complexity will be Al will Al can also be o ofn why o ofn because it's possible that all the height of the building are in an ascending order uh not in descending order so from bigger then smaller than smaller so all the values will be uh will be kept inside our stack so it can consume up to O of n space so this was the question and uh right we solve the question so thank you guys for watching this video and you have and if you have seen till last uh I really appreciate uh please like And subscribe and follow for more questions thank you
Buildings With an Ocean View
furthest-building-you-can-reach
There are `n` buildings in a line. You are given an integer array `heights` of size `n` that represents the heights of the buildings in the line. The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a **smaller** height. Return a list of indices **(0-indexed)** of buildings that have an ocean view, sorted in increasing order. **Example 1:** **Input:** heights = \[4,2,3,1\] **Output:** \[0,2,3\] **Explanation:** Building 1 (0-indexed) does not have an ocean view because building 2 is taller. **Example 2:** **Input:** heights = \[4,3,2,1\] **Output:** \[0,1,2,3\] **Explanation:** All the buildings have an ocean view. **Example 3:** **Input:** heights = \[1,3,2,4\] **Output:** \[3\] **Explanation:** Only building 3 has an ocean view. **Constraints:** * `1 <= heights.length <= 105` * `1 <= heights[i] <= 109`
Assume the problem is to check whether you can reach the last building or not. You'll have to do a set of jumps, and choose for each one whether to do it using a ladder or bricks. It's always optimal to use ladders in the largest jumps. Iterate on the buildings, maintaining the largest r jumps and the sum of the remaining ones so far, and stop whenever this sum exceeds b.
Array,Greedy,Heap (Priority Queue)
Medium
null
725
hey so welcome back and we're going to do leak code problem 725 called split linked lists into parts and so we're going to do just that we're going to return a list of linked lists and we're going to split them up into K lists all right so I'm assuming you already read the problem so we'll go straight into implementation and so the first thing that we're going to want to do in order to split this is get the length and so let's get the length sort of the size of this linked list which as typical code here so let's just go and start at the head and so we want to iterate through this entire linked list here so we just keep going until we hit the tail so as we go we'll be measuring the length or getting the length of this linked list so now that we have the length then we want to actually split this into parts and so we're going to create this list here and this is what we're going to be returning at the end here and so we want to split it into K parts so let's go and we're going to iterate K times so for each part let's iterate over it and so the first thing that we're going to want to do is figure out okay what is the sizes of these lists that we're creating and so to do that we want to get a base size as well as kind of an extra I'm going to explain this in a second here so a div mod of the length and K and so what this really means is say that we have a length of 8 here and then K we want to split it into three different parts and so what that means here is that the base size is going to be basically eight rounded down division of two or by 3 sorry which results in two and we're going to take the mod of this so 8 modded by three and that's also two and so what that means here is that we're going to split this list of length eight so that we have two nodes and then uh let's think here two nodes but then that's this part is what is the number of nodes on the base size for each of these but then there's extra so we have an extra two nodes that we can put here and so we're just going to add one here and then we ran out and so basically this becomes three and two okay that's the main kind of mathematical solution here so make sure that this makes sense okay so we're going to carry forward from here and so now we want to actually build our list for each of these kind of Parts here so build our list for each part and so to do that the typical pattern here is that we have a dummy node so that's going to be a new list node that we create with some random value we're just going to start at this pointer here and so we want to kind of mimic the same logic here of okay how many nodes we want to add for this particular part well that's going to be basically the base size plus if there's an extra we're going to use it so then extra is greater than zero so as long as we have an extra we'll do an extra node if we can and so we're just saying here okay so the current dot next is going to be the node that we're looking at so we want to kind of reset our node back to our head so the current dot next is going to that node and then the current is going to move uh to that node so we're just iterating across the chain and then we also want to update our nodes and then be pointing to the next nodes that we're constantly moving forward as well okay so it's kind of like a two-pointer okay so it's kind of like a two-pointer okay so it's kind of like a two-pointer method to iterate across this linked list so node.next list so node.next list so node.next so from here because we just used an extra what we're going to do is say okay if the extra is greater than zero then we just used one in the previous iteration here when we were constructing our part and so we're going to subtract one extra and then from here what we want to do is update the tail for this particular part to then be pointing to nothing now because we want to cut off so that they're completely isolated linked lists here so then current.next linked lists here so then current.next linked lists here so then current.next would be equal to none and then the only other thing is we want to add basically um let's think here the dummy dot next so that will be the head of this particular part here and so invalid Syntax for I had to say for in range great and let's try submitting and success so I hope this helped a little bit and good luck with the rest your algorithms thanks for watching
Split Linked List in Parts
split-linked-list-in-parts
Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts. The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null. The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later. Return _an array of the_ `k` _parts_. **Example 1:** **Input:** head = \[1,2,3\], k = 5 **Output:** \[\[1\],\[2\],\[3\],\[\],\[\]\] **Explanation:** The first element output\[0\] has output\[0\].val = 1, output\[0\].next = null. The last element output\[4\] is null, but its string representation as a ListNode is \[\]. **Example 2:** **Input:** head = \[1,2,3,4,5,6,7,8,9,10\], k = 3 **Output:** \[\[1,2,3,4\],\[5,6,7\],\[8,9,10\]\] **Explanation:** The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts. **Constraints:** * The number of nodes in the list is in the range `[0, 1000]`. * `0 <= Node.val <= 1000` * `1 <= k <= 50`
If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one.
Linked List
Medium
61,328
299
That a hello guys welcome to this new video but in this video we are talking about the next problem number one two three 021 and that means you must subscribe that How many are absolutely correct, meaning that out of the correct positions, there are only 13 numbers, there is only one number, the second account has only one number, that is correct or one pinch, and then how many numbers have you got after that, here I have two, one number and There are two questions, one number is coming and then how many numbers are required after that, so the position mileage is done, it is ok, cover it and look at it, the remaining one number is one and both the numbers are required, let's solve the question to win. For this, we need that number also the same and to take out that big one from this, think, I will go to this, I will check, if it is a festival, then this is that and this is needed, now the second that means that apart from this, what other numbers are here and here. Apart from this, what numbers can the children now subscribe to the school, what can they do, then what is there in my mind, then it is interesting in my mind that if I start the account with all the numbers except these bulls. I will store one account, there is one to cash account, it is very good for FD account, it is fine from now and then what should I do about the other one too, should I do it from everyone's account, there is zero account, there is one account, so now we are in this. Apart from that, I control that cigarettes are basically made, okay, so I want to compare both of them, how many are there in this, here are 20 soldiers, this is useless, this is here and here, how many are there, so how many others can I write that I can write something from here. Like and subscribe the number and tell me if you like it, but what will I do, I am a guest, that means I will add it, so whatever time is definitely nothing, this is the part in which you want the gas crisis position number, then subscribe first of all. Subscribe to Jhal Secret's account and I will select mine, I will call it Gas and then I don't have to do anything, I have to make it in both of them, in this too, if the account is there, which one is common, right for example, in this too. In this, if the rosary was filled with one five and there would be 138 in this question, subscribe again and again, I used to avoid it, then there is a back pain thing in it, then it is from the words, use of my introduction, initially take the counter of both, I gave so much, that yes. Tell me brother, it is correct, yes, it is absolutely correct, now what will we do, let's run it and these 520 eye lenses are cricket and I have plus Syed and I will check whether both are the same or not, if I wash them with both then I will check. If you like equal toe and dot face, then what will you do? Brother, will you press the boobs? Okay, if it is not so, then what should I do? If I want to create more accounts, then where will I have to add the code? To add for the account. For them, we will have to make one, so look, let's make an International School New Year to you, it is very beautiful, okay, what else will you do, now we will do it, brother, friend of one, now look carefully, there is a line here, that's a lot of people. If it is not clear enough, here I can say that the secret of the secret is the character against the right? Will ask on this, converting the character into interior, right, how do you convert the character into which is that and what is the name of the character? When we have to convert it to - why do we When we have to convert it to - why do we When we have to convert it to - why do we do it, then here I plus is a very beautiful idea of ​​​​Servi and Gas beautiful idea of ​​​​Servi and Gas beautiful idea of ​​​​Servi and Gas New Delhi 8 app - - - and here we will convert it to zero, it is very beautiful and in plus, from here we have From here we have all the options, remember what we did, we have created an account, now what to do with the account, we have this thing available and now we have to see that we will press this, there is a village on it, print it from the point and Electronic only plus and every time we will check rather we will add inside it we will add whatever is the meaning of it okay meaning of what minute cigarette why not Vinash Sharif are of one of oil and the ring to file okay and this mist That's K and another thing so now what to do now how do we convert this into Institute America Russia and these tears into these and inside this we will put first of all we will write that A plus celery pear and dot to send and inside this If we do today's boss and will do it in this, the stand has been made on plus B scale and we will return it, which alarms have been set, Ajay is worried about Ajay, I am Mukesh, let's leave the function for Ajay, that the university functions, Radheshyam Patel lets. According to Rahne Lagi Correct Answer on kidney latest updated on ki world cup final year status walking point hunting record kari live in relation with a near me but this 5 days 91574 say good to reduce it's so thanks for lips meet you next video is Ajay that a
Bulls and Cows
bulls-and-cows
You are playing the **[Bulls and Cows](https://en.wikipedia.org/wiki/Bulls_and_Cows)** game with your friend. You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info: * The number of "bulls ", which are digits in the guess that are in the correct position. * The number of "cows ", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls. Given the secret number `secret` and your friend's guess `guess`, return _the hint for your friend's guess_. The hint should be formatted as `"xAyB "`, where `x` is the number of bulls and `y` is the number of cows. Note that both `secret` and `guess` may contain duplicate digits. **Example 1:** **Input:** secret = "1807 ", guess = "7810 " **Output:** "1A3B " **Explanation:** Bulls are connected with a '|' and cows are underlined: "1807 " | "7810 " **Example 2:** **Input:** secret = "1123 ", guess = "0111 " **Output:** "1A1B " **Explanation:** Bulls are connected with a '|' and cows are underlined: "1123 " "1123 " | or | "0111 " "0111 " Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. **Constraints:** * `1 <= secret.length, guess.length <= 1000` * `secret.length == guess.length` * `secret` and `guess` consist of digits only.
null
Hash Table,String,Counting
Medium
null
931
hey everybody this is Larry this is day 19 of the Leo daily challenge hit the like button hit the Subscribe button press the one button uh join me on Discord let me know what you think about today's problem today's uh no just today's problem oh did the extra problem so we'll take a look at today is 931 minimum fling path sum all right given an N byn Matrix a way of integer Matrix return to minimum sum of any foring power F Matrix um I think I talked about this problem at some point in the past um but we'll talk about it again it has to be yeah just diagonal right cuz um H actually I guess it wasn't it has been a while but yeah uh I mean this is dynamic programming if you I mean obviously if you haven't been here with me so I'm going to go from the start and this is going to be dynamic programming the idea is that you know uh you can kind of parameterize um the best current state based on the previous row right so you could kind of even say it in plain English um for every cell it is just the minimum of the last three above uh this is also like very endearing to me this um this particular dynamic programming or at least this particular frame is that um uh yeah it's very meaningful to me because I think this was one of the earliest um usage of dynamic programming that I've used in quotequote in real life though it was as a side project because um if you ever used Adobe uh Photoshop or something like this nowadays you may you know there a couple of ways to scale a photo right um and basically the idea behind scaling a photo like the naive scaling is just you know um like if you make the photo half the size then everything just like shrink by two and so forth right um so that's one way to scale another way to scale of course is this thing called content aware resizing right um without going over how you know to do bigger but if you go smaller um there is this you know um ratio scaling thing that we just talked about but another way is actually this thing called um I forgot what the name is specifically but it's like minimum energy um minimum energy removal or something like this I forget what it's called but I think the like the technical term but basically the idea is that you can Define uh each cell and um or each pixel right as uh red green and blue and of course also by the way if you don't want to hear about this you can fast forward but it is interesting in case you know you sometimes ask like uh will these always be practical in real life or whatever so I'm giving you one example one that like I said is endearing to me but yeah but basically you can think about each pixel as you know red green and black or sorry red green and blue RGB uh and also an alpha Channel if you want to play with that though I think back then there I would say that there I don't know that there's Alpha but um Alpha being like the transparency of that pixel right and instead of like everything on you sell you can also like you can calculate the minimum sum if you will of all these things but not minimum on the colors but basically minimum on the change in color right you could say that for example if you have two Boos in a row then you could say that um you know maybe the Delta is zero or something like this where you go from like a green and a pure green to Pure red you can do some um uh what's it called uh it's not Oran distance but like the D2 distance right like you know uh Delta R square plus Delta green square plus you know Delta blue square and then you minimize that something like that or just Square Ro of that maybe right so like some distance metric right um and the logic there if you want to um go back to the logic is that well you want to take the line that has the minimum changes because those are the least the things that not interesting right let's say you have a picture of myself like Larry in a blue sky you don't want to remove if you want to remove say one line of pixel uh like one vertical line you don't want to go up down the middle and then like you know maybe I have a smer nose now or something right but what you would do is that if you calculate and let's say I have a maybe not here but let's say I have a black a blue sky background then you just take a random line that is on the sky and then basically you just shrink the sky behind me and maybe that like maybe there's a tree maybe there's the sun here and then it'll just you know take a line that doesn't have the Sun or something like that so something like that um is uh a very practical use of dynamic program back in the day and not even that it's just as very visual right because there's a lot of um cuz I remember another project I used to do with dynamic programming is uh a lot of uh well simulations but also like sports-based uh States right uh nowadays sports-based uh States right uh nowadays sports-based uh States right uh nowadays I think actually like to be honest I wish I knew enough to publish or something like this back then because I had all these ideas before a lot of people did because of my dynamic programming and stuff like this background but for example I'll give you an example is like baseball right baseball is a way easy to make discreet because basically you have like outs you have Innings you have the score and you know how who's on base I mean that's a very easy State obviously you can make things as complicated as you want with like other um Dimensions but yeah but based on that you could have like expected win kind of thing and then you could kind of do all these math backwards and all of this is just based on dynamic programming right because you have like a probability of you know like if Larry is up against I don't know uh um some pitcher maybe has 20% chance of um some pitcher maybe has 20% chance of um some pitcher maybe has 20% chance of getting a hit you have a 20 or whatever and maybe another one would be cck it maybe if I had if I know what you know if I knew clicket back then but just to give an example of like dynamic programming and states and that kind of math actually like not discovered by me I just kind of like was playing around with you know things by myself and wish like I said wish I published but like that kind of thing actually revolutionalized uh sports right now right like everything is about sport that kind of thing even if it's not quite the same um like there are other ways to do you know there also like linear regression models and stuff like so there different ways to kind of model these things in like basketball or American football or something like that um anyway so that was like you know a long time I'm not going to even say how long to age myself even more but um but yeah it's basically money board before money board kind of right like that was how long ago it was anyway that was a very long rent but you know hopefully this PR is straightforward to you uh it is um really one of the more basic dynamic programming problems uh the way the reason why I like to kind of tell the story every time is because um you're able to visualize it and kind of see it every time right like it's a very easy abstraction about like how to kind of do it and that def of dynamic programming and also competitive and a lot of these Leo problems in general is that a lot of these things are abstract but that's like a very real thing that you can actually Implement yourself and if you really uh if you have time and you looking for a project or like not a project I guess but if you want looking to play around you can implement this in uh I don't know half an hour and an hour because I know that python now has a lot of like UI libraries I'm not familiar with them so but you know so if you have everything set up you can set this up very quickly right like put in a picture at make a commment remove like five vertical lines or something right anyway um story time is over so uh that's what I have for the story time but let's actually kind of you know get around this problem so let's set up R is youal to Matrix cannot type I just came from the Cod up from outsid of my hands a little bit Frozen a little bit so I kind of you know warmed them up but yeah so for R in range of R right I guess in you know I guess a lot of the times I write these problems uh I do it top down for learning but this one I actually in general very much like to do bottoms up uh it's not even Bottoms Up To be honest it's just tabulation in a in um you know cuz I like to do it downwards as well though you know it doesn't really um you could you know um this is also another problem that if you watch yesterday's video that I talked about with respect to um you know yesterday was a very easy climbing step so also another fundamental problem so maybe we're just getting fundamental DP uh this week but one thing to know about this Poli problem is that it is also symmetric right and what I mean by that is that the minimum sum going from the top to the bottom is going to be the same as the minimum sum going from the bottom to top so there so it gives you more leeway with how to write this but it's also worth pointing it out right because is not always true and you don't want to you know you want to be mindful for problems that when it's not true you're looking for the other way right um and still you know solve the problem that's the biggest thing so yeah so basically here we can maybe say B s is equal to um is it minimum so that just say infinity right and let just say C is length of the first row right um yeah and then now for each row for each column then uh do I just set this up a little bit better I guess I do CU okay so the first row is it is just um best of row of C is just equal to the Matrix of uh z right and then now we start oh no not on the first row and on the first row uh it's just going to be equal to the Min of the previous row oops uh the same just directly up uh this is always awkward to write because oops I keep making same mistake because this could go out of bounds right so you have to kind of write something like uh oh man how do I keep writing that I don't know why but yeah and then if best uh or if cus 1 is greater than zero then you know C minus one right is less than or then I cannot type today right so something like that and then of course you have to add in the Valu so then after that you can just add in the right it's the Min of these three things maybe I wrote this in a weird way so or maybe the way that I would write is that um you know maybe I would just call this minimum previous I mean it's accurate but maybe it's a little bit uh obtuse right CU then now you can write something like oh see is equal to um the previous Min plus the current cell and then now at the end we just oh I just want mentally check that it works for negative numbers I actually didn't realize it with negative numbers but yeah otherwise then it just return the minimum of the last row and that's it in theory what would I do wrong uh I mean the good thing about DP is that you can always print everything out maybe I have a off by one somewhere I don't know so 213 okay so the six is going to be one or two oh yeah I just have typos everywhere huh CU this is the last World right all right not a big deal but this is why you know printing is the best debugging too you ask me I don't know but yeah looks good let's give it submit and yeah uh didn't make a m what did why did I get wrong answers last time oh maybe I just C to submit but by accident cuz I didn't even finish typing well this time don't know oh maybe I just didn't consider negative values or something is that it but yeah um this is going to be all of um this is linear time linear space and when I say linear I mean r * C because R * C is the linear I mean r * C because R * C is the linear I mean r * C because R * C is the size of the input um of course you can actually optimize the space even further to be sublinear uh to be all of C by just keeping track of the previous two rows because you can notice that here we only care about the last row and the current row obviously so now you only care about two rows and then after that you could throw away so if you kind of use that you can reduce this to ofc space but yeah as I say this one is pretty fundamental pretty straightforward um you just have to know it right this is very basic dynamic programming uh and if you're able to even if you understand it you should be able to get this very quickly to be frank um oh actually and I forgot that this is n byn i mean mine is more General but it doesn't really matter I guess but yeah um but also just to be clear uh you have to be careful um because if I had read this correctly I would have said this is n squ but n square is still linear in this case because n square is the size of the input so don't get confused or just say n Square I guess then you know you don't have to say whether it's linear or quadratic but it is linear in the size of the input that's what it is usually Shand for and the size of the input is n squar so yeah anyway uh that's all I have for today that's all I have uh yeah let me know what you think stay good stay healthy to go mental health I'll see yall later take care bye-bye
Minimum Falling Path Sum
maximum-frequency-stack
Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`. A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(row, col)` will be `(row + 1, col - 1)`, `(row + 1, col)`, or `(row + 1, col + 1)`. **Example 1:** **Input:** matrix = \[\[2,1,3\],\[6,5,4\],\[7,8,9\]\] **Output:** 13 **Explanation:** There are two falling paths with a minimum sum as shown. **Example 2:** **Input:** matrix = \[\[-19,57\],\[-40,-5\]\] **Output:** -59 **Explanation:** The falling path with a minimum sum is shown. **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 100` * `-100 <= matrix[i][j] <= 100`
null
Hash Table,Stack,Design,Ordered Set
Hard
null
1,663
hey everyone nitish aside hope you're doing well so let's start with the question so the question is smallest string with a given numeric value okay so the numeric value of a lowercase character is defined as its position like one index in the alphabet so the numeric value of a is when b is 2 then c is 3 and z is 26 okay so the numeric value of a string consisting of lower character is defined as the sum of its character numeric value okay so for example if abc is a string you are given so you can do the sum for this so a represent one b represent two and e is five so the sum of this is eight okay so you are given two integer and a k what you have to return a lexicographical smallest string basically in the ascending order with the length equal to n so its length will be like the string length will be equal to n and the numeric value basically the sum of the string should be equal to k okay so it's just tell about lexicography okay so these are some constraints so and basically 10 to the power 5 and n will always be less than equal to k okay so let's understand with an example so let's take example one so we have n equal to three and k equal to 27 which means we have three position one two three and we have to the sum of this uh alphabet should be equal to 27 okay so if we can see the output so for this case a y okay so let's just write down a represent one then this is one and this is 25 so if we do the sum for 1 plus 25 it will give you 27 okay and this is the smallest string that you can create like you also say like i can create a then you will take b then you will say x this is like its sum is also 27 bus but this is not a smaller string so we will reject it uh okay let's understand the other example also so we have n equal to five so that means we have five position one two three four five and our k is 73 okay so this is a s z so if we represent this is 1 this is 19 26 so if you do the sum so 26 it's 52 and 52 19 11 5 plus 1 6 71 and 71 plus 1 so it will give you 73 okay so this is the smallest string that you can generate okay so and then and k is always greater than n so like it's pretty simple like this if you have uh k like k will always be greater than n if it is less than like this is this then you can't solve it so let's see how we can approach this question okay so let's take this example okay so we need n should be three and we need to fill the sum for 27 okay so if you have to fill for the length of three you know the smallest uh string that you can generate is a like this will be the smallest so if you do the sum for this so this is equal to 3 but we need to make the sum as 27 okay and in the question it's mentioned like you have to create a lexicography so it's basically in the ascending order so what we can do we will fill like this will be our first step okay fill every position with a and from the second step what you have to do go from the last and fill the remaining k that will be left after filling the a okay so what we will do we will update our k so what we will do k minus equal to n okay so but will become k is equal to now 27 minus 3 equal to 24 okay so what we will do at every step now so like this will be a and this will also a so we will start from here okay and we'll do at that point whenever like our k is greater than zero okay so what we need to do basically reduce uh let's say if i have to fill z here so how can i feel like a representing one and if i add 25 to it what it will become it will give 26 and if i convert this into a sky this will be a z so that means my one is already present i can add 25 or it will become then z okay but now our k is only 24 okay so if we add a plus 24 what it will become so a representing 1 and this will become 24 this is 25 and this is basically y so what you will do you will update the latest from the last okay so you will update this will be a and this will now become y and you will reduce your k so k now become k minus equal to 24 so k now is zero so whenever your k becomes zero you don't have to go further you got your smallest string so this is the output for this case let's take another example and then it will be cleared okay so let's understand the approach with the with this example so what we have n equal to five so we have five position one two three four five so our first step is to fill all the element with a okay so we will fill a so this will become a and you will reduce your k so now k is become k minus n so this will be 73 minus n is 5 which is 68 okay now you have got your smallest string but your k is not empty till now so whenever you like so we'll do a loop whenever our k is greater than zero we'll do something so what we will do we will go from the last we will start from here every time what we will do we will subtract k basically what we will do we will subtract our k by k minus either you can subtract with k or the maximum number you can take is 25 because uh if i do a plus 25 this will become z but if i do a plus 26 so this cross the sky limit like after that any sky character will present so i can take only the maximum character as 25 okay so what we will do we will update our k and we will add this minimum number at here okay so let's write it like this uh let's remove this uh let's write it like this will be array of i what you will do you will plus equal to minimum of either 25 or k and your next step is always to subtract it by 25 okay so what you will do you will update your current i ith character so you will do a and your k right now is 68 or minimum is 25 so you will take 25 and you will add 25 here so this will become z and your pointer will commit here okay and you will reduce your k so k is right now is 68 after this it will become 68 minus 25 this will be 3 this will be 43 so k is now 43 okay we'll move further so we'll commit here we'll do the same step we'll do the minimum of 25 for k so k is 43 right now so but the minimum is 25 so we will update we will add 25 here and this will become z after this will reduce uh our k so k become 43 minus 25 okay so this will be 3 13 and this will be 8 and a 1 so this will be 8 and this will be 1. so now k is become 18 and you will move further you will come back here again you do the minimum of 25 or 18. this time your minimum is k so you will take it is 18 and you will add 18 at here and you will update your k so k will be now basically 18 minus 25 so which is less than zero so you will just stop it here and you just update this so this will become uh a plus 18 is 19 and 19 represent s after this like they will remain as it is so we come out of the loop and we got the smallest uh ascending string okay so you got to like you got the approach by we fill first all element with a because we will reduce our k from the last and whenever our k become less than zero we got our sorted string okay so let's write the code for this okay so we need a character array let's give answer new care which will be of n length and what we will do we will fill the character with a first step is this and we will update our k also so k is less than equal so we have done with that first step after this will loop uh while k is greater than zero and your n is also zero so what you will do you have to do uh on current index from the last is equal to plus equal to you have to do math dot min it will be your either 25 or the k after this you will update your k and you will just come out of the loop and after this we just convert the character into a string so this will be answer i think we have done with the code so let's run it let's see okay so this is value of let's run it so as you can see this is accepted like we are getting the output as a y and a y let's submit it so as you can see our code is submitted uh the time complexity for this is we are like a filling iris so this will be our order of and after this we are doing a again a loop over our area so it's order of n and the space you can say it's an uh like this is for the output uh answer so this will be order of n but this is for only for output so we can assume like we haven't take any extra space so we have solve in order of one hope you like it thank you for watching my video and do join the telegram group if you have any doubt and any concern thank you
Smallest String With A Given Numeric Value
detect-cycles-in-2d-grid
The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on. The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string `"abe "` is equal to `1 + 2 + 5 = 8`. You are given two integers `n` and `k`. Return _the **lexicographically smallest string** with **length** equal to `n` and **numeric value** equal to `k`._ Note that a string `x` is lexicographically smaller than string `y` if `x` comes before `y` in dictionary order, that is, either `x` is a prefix of `y`, or if `i` is the first position such that `x[i] != y[i]`, then `x[i]` comes before `y[i]` in alphabetic order. **Example 1:** **Input:** n = 3, k = 27 **Output:** "aay " **Explanation:** The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3. **Example 2:** **Input:** n = 5, k = 73 **Output:** "aaszz " **Constraints:** * `1 <= n <= 105` * `n <= k <= 26 * n`
Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
null
260
hello everybody welcome to my channel today is the day 23 and the problem is single number three so this is a problem theory of the single number series so if you haven't solved single number two already try to solve them before attempting this problem so that you will get some idea how to proceed so let's see the problem statement and try to understand so given an array of numbers nums in which exactly two elements appear only once and all other elements appear exactly twice find the two elements that appear only once so in the given example we have one two three and five so three and one appears once so we need to return three and five while one and two appears twice so notes are the order of the result is not important so in the above example we can also return 5 and 3 is also correct your algorithm should run in linear time complexity could you implement it using only constant space complexity so we will focus on the constant space bit later let's try to solve this the very basic brute force approach so first approach is sort the numbers of the array so if we sort the numbers this array will become one two three five once we sorted then we can first check the boundary cases so like if the number at zero index is not equal to number at one index then we that zeroth index number is our single number also we will check from the end as well the number at n minus 1 in index is not equal to n minus 2 index that is also our single number after that for all the rest of the number from 1 to n minus 2 index we will check this condition if the ith index number is not equal to i minus 1 and index and the i plus 1 index like left or right then it is our single number we will use that in our array so if we see the time complexity of this solution is the time complexity of sorting the array which is n log n and the space complexity is o of n so this is what problem is not expected so second solution will come like we will do count the occurrence of each number and yes iterate through the count and wherever we found the count is 1 that is our single number how we will do we will use the hash map here store the key and the value is the count of the number once we added this so this is line from the previous so you skip down for look this two line so once we count the frequency this will be the frequency like one is two times two is two time three is one time and five is one time then we will iterate through this value section wherever we found the count is one that is our single number so we will take those two numbers and return as the answer so if we see the time complexity is often and the space complexity of the solution is often but we need to try to achieve this space complexity in o of one and the time compressive often so how we will do so if you already sold the single number one and two you must have like we need to use bitwise operators like jar and all so let's understand first little bit how the jar works so these are the two important property of java operation which will be help in all the problem where we need to use the jar so if we do the jar of same number with the 0 we will get the same number itself and if we jar two numbers same numbers we will get the zero so this property is very important to solve the single number problem is straightforward using this two property and single number two is little bit tricky so you can try i have also video i will share the link of those videos so now let's understand what is the truth table of the jar so jar truth table is like if both x and y is same like 0 and 1 then the jar of these is 0 both of them is 0 while if both of them has different bits so the jar is 1. so this is very important property and this is a truth table object so let's move over the problem so we have this example one in the problem so if i write in the binary let's say for uh explanation perspective i just represented in a four bit binary representation while in the memory it is stored as a based on your bit machine system like 32-bit or 64-bit 32-bit or 64-bit 32-bit or 64-bit so here this and also the integer in java is represented 32-bit while the java is represented 32-bit while the java is represented 32-bit while the long is at a 64-bit representation in memory so one 64-bit representation in memory so one 64-bit representation in memory so one the if we write binary is 0 1 2 is 0 1 0 3 0 1 and 5 is 0 1 so now what we will do the first step we will if we draw all these number so this will eliminate all the numbers which are occurring twice correct as we already saw in the java property so if we draw this all the four numbers of the array we will get the three or 5 which is 6. so this is here representation of 3 in binary 0 1 5 in binary is 0 1 0 if we do so same bit means 0 and the different weight 1 then different width 1 and the same bit is zero so this is a representation of binary of six so now we know the jar of the two number which we are looking for now the how we will get these two numbers so if you see over here this is the rightmost segwit of our jar of these two numbers so if we are getting rightmost set with one here then as per the jar truth table like this if we are getting one then there must be the one of the number has that bit is set and the other is unset like one number will have zero and another number is one so we will make use of this property this is like a very critical property to solve this problem here so if we see here like 5 has that bit is 0 while the 3 has that bit is 1 so what we will do we will look for this bit and then categorize the all the numbers in our array into two group the one group which let's say the index of this bit is two uh let's say i let it call i from the right side so we will uh form two group one group like all the number whose eighth bit is one and the other whose ith bit is zero so why we are doing this is very important what we are doing we are trying to classify these numbers into two groups where so what will happen let's say we got one so if we see the zero the one will come fall in here and two will fall here second one will fall here second two will fall here and the three will fall here while the five will fall here so this is our group will be clustered and now as we already know the as per the jaw property the twice occurrence is automatically cancel out to 0 and if we do jaw with the c 0 with the number itself so same for here so once we did this we will get the first single number by drawing the all the numbers where the this set weight is making the zero um now the question is how we will check this all the like classifying this number so let's say we have this number six we got the jar of our three and five which is repeats binary representation of six so we got this bin now we need to first find out this bit and form a mask first so the mask will be formed uh we need to find the last one bit how we will find we will just do bit wise and with the one and then it's left shift every time and the fro i start with the zeroth from the last least significant frequent bit so this is like this we will use this if we do and bitwise and we will get 0 here then we move the 1 to here this will become this then we will do it wise and with again our jaw number this will be give us 1 so hence we found this is our mask once we got the mass we will try to apply this mass 2 in our all the numbers in our array which is like 1 2 3 1 2 and 5 so we will apply this mask and classify these numbers in the two group as explained here so this is how we will get the number so this is of one way to get the mask another way if you know already like we i explained this in my hamming distance video you can watch out so there is a algorithm which is named as brian karningam algorithm why using this algorithm if we write any number let's say if we have a decimal number let us say 6 itself 0 1 0 if we subtract 1 in this decimal number which will be 5 the binary representation of 5 is 1 0 1 and 4 is 0 1 0 so if we subtract 1 in that number and then the all the rightmost bit after the last set weight will be reversed so c here and including that bit as well so these two bit are same while these two bits are reversed so if these two bits are reversed so what we will do let us say we got the jar as jar and if we do a bitwise end of with jar of minus 1 so what we will get to the ah so let me explain more here this is very important point for this problem so first we got this is our let's say jar and if we do jar minus 1 will become our 0 1 0 jar minus 1 will become our 0 1 now we will take the bitwise end of these 2 we will get 0 1 0 so once we got 0 1 0 so this side is already changed now if we take the bitwise jar again with our jar number with the this product so let's this is 0 1 0 so we will get the mass 0 1 0 so this is the second way to get the mask from this number so once we got this mask we will use to classify the group so let's implement the code first so for implementation we need a one variable which is let it call jar initialize with zero then for int and in nums in any nums basically and the jar will be our jaw equal to jar into n once we got the jar we need to get this mass so int mask is equals to this jar bitwise and with jar minus 1 and then bit bitwise ah jar with the jar itself so that we will get the our mask once we uh got the mass we will use that mask here and then we will loop over numbers again int num in nums and then we will check if the so let's initialize our first number here in number which is with 0 we will check if this mask so we will do group wise the mask bitwise and with the number n is equals to zero so this fall into the one group where we will take this group number and do the jar with our number one itself and this number n we will get the first number once we get the first number the second number how we will get the second number so here if we have the number 1 and we know number 1 jar number two is our jaw so if we again do jaw with number one in with this boss side jar with number one so we will left over here number two and right side is jar of jar with number one so this is how we will get the number two so this will be written as a array of two numbers which is number comma jar with again jar with num one so we will get the num two so this is a simplest implementation so let's see it is compiling our code we are getting we can return any order let's submit our code so it is accepted so the time complexity of the solution is often and the space complexity is of one so this is the solution and another approach to get the mask is this is like very tricky it's not straightforward if we do jar and with the negative of jaw this is how you can get the same mask and then you can use so try it out to understand yourself and if you are not able to understand let me know in the comment section i will explain in more detail so thanks for watching if you like my solution please hit the like button and subscribe to my channel and hit the bell icon thanks for watching again
Single Number III
single-number-iii
Given an integer array `nums`, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in **any order**. You must write an algorithm that runs in linear runtime complexity and uses only constant extra space. **Example 1:** **Input:** nums = \[1,2,1,3,2,5\] **Output:** \[3,5\] **Explanation: ** \[5, 3\] is also a valid answer. **Example 2:** **Input:** nums = \[-1,0\] **Output:** \[-1,0\] **Example 3:** **Input:** nums = \[0,1\] **Output:** \[1,0\] **Constraints:** * `2 <= nums.length <= 3 * 104` * `-231 <= nums[i] <= 231 - 1` * Each integer in `nums` will appear twice, only two integers will appear once.
null
Array,Bit Manipulation
Medium
136,137
983
hey everybody this is Larry this is March 27 28th well I mean it's my 27th year but the 28th day of the RICO daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Farm um so I came here so that I could click on the happy lead code button get 10 lead coins uh it adds up I suppose uh yeah hope everyone's doing okay uh if I look very tired it's because I am uh I've been doing um I guess I'm 50 hours into my fast uh roughly speaking maybe 49 I don't know whatever right at some point so I'm a little bit tired but not from that because I actually that the fasting has been giving me a lot of energy which you know it's supposed to do um but I just finished doing a workout uh you can check me out on Instagram if you want to follow my workouts fit uh nothing too intense actually it was very intense but not like impressive per se I was just doing a lot of things uh so I'm a little bit tired from that uh on top of you know um on top of you know the fast so yeah so let me know we'll see how uh how Larry does lead code when fasted oh fast thing even all right let's do this uh hope everyone's doing it hope everyone's having a good week by the way a great week even maybe uh it's a little bit rainy here in New York uh and yeah let's go let's jump to it enough for the intro 983 minimum cost for tickets uh a medium Farm you have planned some train travel one days in a one year in advance the days of the year in which your travel are given in as an integer away days each day is one to 365 train tickets are still in three different ways one seven and 30-day different ways one seven and 30-day different ways one seven and 30-day passes and they cost different amounts um the pass allowed that many days of consecutive travel so if you have a seven day pass then um yeah then you could do seven inclusive I don't know why I said inclusive I guess it's just seven days right okay so then now you're trying to minimize I suppose yeah minimize the number okay uh and days what is oh uh okay I see so these are the days that they're traveling okay now I just wanted to because for a second I thought that the input was going to be something like you know like a almost like a billion of way of 265 elements but I guess this makes more sense okay I mean um I'm trying to think whether I mean so there is a my immediate dot is that there's a dynamic programming solution for sure um and I guess now that I think about it because of yesterday's DP um it probably is but before that uh or maybe after that I'm but before implementing it I think doing a contest to be honest or um I would definitely jumped into the diamond program because I know it I could code it in a few minutes and you know or whatever um on an interview it's a little bit tricky because I'm just trying well I mean articulate the things that I'm talking to you now um maybe in a slightly different way you know in a conversationally but I'm thinking whether there is a greedy-ish thinking whether there is a greedy-ish thinking whether there is a greedy-ish solution you know um my intuition is probably not but it I don't even mean like ingredients in like a pure greedy but just maybe something that is I don't know maybe not then I don't know nothing really comes to me something that um yeah this basically hmm is that true I want to say that this basically is um hmm is it is that true I want to say this is basically like a knapsack then maybe that's not quite precise that's why I'm hesitating a bit I'm just telling you a bit but in any case the idea is still very similar in that it is going to be pseudo polynomial um in the complexity uh meaning that it is polynomial depending on the range of the numbers right uh and in this case uh there's one seven and 30 and 365 being the constants that are relevant perhaps okay um I'm trying to think red so right now for implementation I'm just trying to think whether I want to do it uh as a as an array of 365 elements or maybe manipulate this the beauty about the trade-off whether the trade-off whether the trade-off whether um is that the beauty of the 2065 element away thing is that it's harder to get wrong um where if you kind of manipulate the dates as is it's uh it's definitely easier to get wrong uh in that they're like off by once and maybe not but that's how I usually try to think about these things when I think about it because and some of this may not apply to you in the sense that um you know I've stopped many thousands of problems so for me I know my strength and weaknesses and I know what kind of things that I make silly mistakes are not or have like a tendency to um and I try to avoid them right um you know at a certain point I gotta learn who I am right um so that's kind of like a little bit of that commentary but um yeah uh okay let's just let's do it the silly way first uh and how do I want to think about this right so I will bring my eyes a little bit um I mean I think the recurrence should be relatively straightforward right um there is some minor optimizations that you can make but basically your recursive function I uh I think it's going to do something like um calculate men say um the current day and that's it really right yeah I think so and then in this day if and here we will maybe say I use this to go to set of days right um um so basically the idea here it um one kind of not greedy per se but uh but are not greedy in its pure sense I say this with a lot of nuance because in dynamic programming um dynamic programming is built off this idea of um like local uh local Maxima type thing right where you know you're able to make a decision based on the current state um and in that sense in that particular time um very often that step is greedy in itself of course you're greeting over a lot of excessive search in a way but by reusing States uh you know sub uh or what's it called uh overlapping sub problems or something um so but yeah so basically the thing that I'm going to try to do today uh for this particular one not for today but just like for this day is what I mean is that we only want to buy a ticket if um if we need to travel on that day right um hope that makes sense because like oh I mean you could go in both directions really in this one I think um and that is symmetric but basically for example if you want to buy a dirty day pass um you know you want to but and the days are like 10 and 20. you know you want to buy the dirty day pass as late as possible right I think that makes sense like in real life you're not gonna buy it on day one no just in case you needed more then you know you buy on day 10 so that you know you kind of have you know you want to uh bracket it as much as you can and of course you could go the other direction um but the idea is still the same so then now we can do something like um well maybe traveling is better um you know if day is in traveling right because if not then we just calculate Min of day minus one and in this case I guess I'm going backwards right um yeah if day is traveling that means we have to buy a ticket then we have to do three decisions to make one is well I mean the three decision is what it sounds like we're just buying a one day ticket a seven day ticket or dirty day ticket right so basically we have I don't know day one maybe take it or ticket one maybe I don't know uh as you go to calculate Min of day minus one plus uh causes of zero ticket seven is equal to calculate Min of day minus seven plus cost of one and then take it dirty as you go to oops minus 30 plus cost of two right and of course we uh we have to get the base case so if day is uh not available then we just return um zero because we're done with the trip over with the buying of tickets anyway of course in this case we return the Min of ticket one ticket seven and ticket 30. and that's pretty much the answer um and we start 365 say or you could even start by Max of days I think that's probably fine as well um yeah yep so it looks good that's submit right now just kidding uh of course um if you know we talked a lot about dynamic programming so of course the it is a dynamic program portion so you have to uh yeah because this is there's just this just um uh this is branches out exponentially if you don't cache it right but the idea is uh the idea behind memorization um and a core part of dynamic programming is this idea well they're similar but uh but the idea behind memory station in particular um in specific is that if you're giving a function and for every same input that you get you have the same output then Gucci right so then you should like save it so that next time you do it you don't do the expensive thing right and they of course could go from zero to 365 and it's going to take all of one time per day and of one space per day so we're pretty good uh this is let's say d then it's going to take all of the time in total and all of these space in total and of course this is um uh this is a um like I said pseudopodnomio is what I mean to say um you can also say depending how you want to phrase it exactly this is linear in the size of days just because days is also bound the ray of the uh the size of the array is also Bound by 365 or D so I don't know how you want to phrase it uh but you know as long as you're able to communicate it to your interviewer that should be fine but yeah the way that I always do these uh especially for video is just uh yeah I guess Max stays and this bang is because that's just the max input that we can put in right so and in fact we do it very immediately so then now it has I think I do need to yeah I was gonna say I need a plus one but actually I already did it thank you 10 seconds ago uh yeah otherwise uh yeah okay uh just to the uh the casing is inconsistent I feel very bad about it but that's because lead code does it this way I like Kebab queso in that Kebab case was is it camo I don't know I'm confused so yeah but in any case oops how did that happen and that's pretty much what I have with this one I think unless I'm you know getting it wrong I knew I thought I needed a poem but I was trying to gamble being lazy all right fine and let's give it a submit hopefully this is not well all the time to exceeded shouldn't be did I miss something oh why did I set this to force I am being a silly bird today uh usually I check it but uh I don't know I blame it on the fasting and the brain fog or whatever I don't know it's not even true I don't know Bible First that is such a brainly bad thing and I've done this like in a thousand videos and I think this is the first time I've gotten this Vlog so it's a little bit embarrassing but uh I mean not I'm not that embarrassed its Mystics happen and I was talking so yeah um yeah we always talk about a complexity so that's what I have with this one let me know what you think let me know if this help out in your dynamic programming journey and yeah that's all I have so stay good stay healthy to good mental health I'll see you all later and take care bye foreign
Minimum Cost For Tickets
validate-stack-sequences
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold for `costs[1]` dollars, and * a **30-day** pass is sold for `costs[2]` dollars. The passes allow that many days of consecutive travel. * For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`. Return _the minimum number of dollars you need to travel every day in the given list of days_. **Example 1:** **Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\] **Output:** 11 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1. On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9. On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20. In total, you spent $11 and covered all the days of your travel. **Example 2:** **Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\] **Output:** 17 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30. On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31. In total, you spent $17 and covered all the days of your travel. **Constraints:** * `1 <= days.length <= 365` * `1 <= days[i] <= 365` * `days` is in strictly increasing order. * `costs.length == 3` * `1 <= costs[i] <= 1000`
null
Array,Stack,Simulation
Medium
null
171
welcome back everyone we're going to be solving Lee code 171 Excel sheet column number so we're given a string called column title that represents the com title as it appears inside of an Excel sheet and we want to return the corresponding column number so the example they give us a to z is 1 to 26. double column A would be 27 so it looks like a single column represents uh 26 and then we take the letter that we're at and add it so 26 should go to 27 a b 26 plus 2 is 28 okay let's check these examples out uh one a is one okay A B we just did that z y so 26 is z Y is 25 then output 701 okay so it looks like they're using a base 26 number system so uh Z is 26 we should multiply it we have two columns so we should multiply by 26 and then add 25 for y so let's do that try it out so Z is 26 we have two columns so we have to multiply by 26 plus 25 for y what do we get 701 Okay so how can we solve this let's create a mapping we know it's a base 26 number system so let's create a mapping we will do like so we want the alphabet value as the key and the index as the value for index value and enumerate string the ASCII and we're only working with uppercase letters so uppercase what does this give us this gives us print mapping so you can see so this gives us a dictionary with the alphabet and their values however they're mapping a as one instead of zero so we're gonna have to increment all of our values by one run this again and okay now we have the correct mapping so now we know we're going to return a number so let's just have a result equal to zero right okay so if we only have one column we should just be able to return um mapping of whatever our column title is right but let's say we have two columns we won't be able to do that we'll have to Loop through every value so let's do that we will Loop through all the characters in our column title so four character and column title what are we going to do well we know if we have multiple columns we already have to multiply by 26. so we'll say our result is going to be multiplied by 26. and then what do we have to do then we have to take the current character we're at and add that value to our resulting number so I'll say res plus equals the mapping of our current character so uh and we know we're going to return res so let's run through an example we have a right it's only got one column but we still do this Loop so we start reset zero res multiplied by 26 0 times 26 is zero now we take the value of a inside of our mapping and which is one right A plus zero or zero plus one is just going to be one we return one okay example one passes a b um so again 0 times 26 is zero plus one for a is going to uh give us one and then we move on to the second character which is B so what do we do first month Pi by 26 but right we already did a so res is 1 in this case so 26 times 1 res goes to 26 and then we just add on whatever the value of B is which is 2. so that gives us 28 so that passes so let's run this and see what happens so we pass all three test cases we'll submit and it does run okay so what is the time and space complexity of this problem well we know the time complexity of our mapping is going to be o of n y o of n because we're using a for Loop to grab all the index and values in our enumeration and adding them to a dictionary uh what is this Loop going to be this Loop is also going to be o of n oops y because we are looping through every character in our given string and doing some sort of operations on them and then we're just returning at the end so we know our time complexity is just going to be simplified down to O of n the space complexity is going to be the length of our mapping right but our mapping is only ever going to contain 26 characters um in inside of it 26 key value pairs so that can simplify down to um well we'll say o of K where K is the number of key value pairs inside of our mapping we know it's always 26 so we can just simplify that down to an O of one space so that'll do it for Lee code 171 Excel sheet column number
Excel Sheet Column Number
excel-sheet-column-number
Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding column number_. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... **Example 1:** **Input:** columnTitle = "A " **Output:** 1 **Example 2:** **Input:** columnTitle = "AB " **Output:** 28 **Example 3:** **Input:** columnTitle = "ZY " **Output:** 701 **Constraints:** * `1 <= columnTitle.length <= 7` * `columnTitle` consists only of uppercase English letters. * `columnTitle` is in the range `[ "A ", "FXSHRXW "]`.
null
Math,String
Easy
168,2304
282
Hello Karishma Kapoor Welcome Surface Expression Ad Operator So let's get into this problem, today's problem is that you must have given an extension inside it, inside which only numbers will be stored and you must have given some target, now you have to tell yourself that your Which operators can you apply on your Puri string so that your entire string gets converted into its target and you have to return the same in how many faces and in what ways can you apply operators on your screen? So that your entire string should be converted into your target and you have to return the same paste because your question is simple and the latest ones you can apply are multiplication operator, addition operator and subtraction operator, so if you are in this question. If you look at then in this example you have given a string of one, two and three and your target is six. Okay, so if you add these three numbers once and try then how much is 3 + 2. once and try then how much is 3 + 2. once and try then how much is 3 + 2. 3 + 2 is science and What is 5 + 1? 3 + 2 is science and What is 5 + 1? 3 + 2 is science and What is 5 + 1? 5 + 1 is 6. So 5 + 1 is 6. So 5 + 1 is 6. So what is our addition to our three numbers? Their addition becomes six. So if we apply addition operator on our three numbers, then our entire string will now be in six. If it gets converted then one way it is ours and the second one is that if we multiply these three numbers then how much is 3 * 2. This is six. This then how much is 3 * 2. This is six. This then how much is 3 * 2. This is six. This string is already ready. 6 has been formed, but if you multiply one inside any of your numbers, then it does not make any difference to the number, then your last answer will be 6, even after multiplying by one, if your If you multiply all the three numbers, then your string is fine with only 6 sides. Apart from this, no other operator can do it. If you add 'in' inside 'three', can do it. If you add 'in' inside 'three', can do it. If you add 'in' inside 'three', it becomes six. If 'in' is added inside it, then ' If you it becomes six. If 'in' is added inside it, then ' If you it becomes six. If 'in' is added inside it, then ' If you do plus one then it will become 7. If you do 7 alias .3 + 2 then it will be five. If you 7 alias .3 + 2 then it will be five. If you 7 alias .3 + 2 then it will be five. If you do apn in one then it will be reduced to five and similarly if you have put apn combination then you will get a mather within which you will be able to make your string six. Therefore, we have done both the methods. This is a simple question, so if you have understood your question well, then let us see how we will solve it. Let me do this to solve it. What should I do to solve it? Na Apne Ko, which operators are allowed? One Apne Ko Plus Operator, by checking all these three operators, we will see which operator is giving its answer and on G, the operator will be giving its answer, Apne will go above this and the rest you can start. Okay, so first of all, our first number is A, so we will put any operator on top of the first number, hence the first operator is in our own string like this, so how can we take the first number in our own string like this? Now, when you are taking your first number, you have three methods, you can either multiply, add, or subtract, so try doing all three. So first of all we multiply tu inside one so 1 * multiply tu inside one so 1 * multiply tu inside one so 1 * 2 how much will tu become, okay now 1 + 2 how much will one plus okay now 1 + 2 how much will one plus okay now 1 + 2 how much will one plus tu become 3 okay and one minus how much will tu become 1 - It will be okay and one minus how much will tu become 1 - It will be okay and one minus how much will tu become 1 - It will be 2, okay, similarly, what will you do? Even after hitting 3, you will see all your results. Okay, so the answer you have now is that once you have come, what will you do, after you get there, when you get three? By doing this, that means I am adding three inside my string, so again you will have three options that you can either get your multiply done by this or you can get your plus done or you can get your minus done, get all three done. If we see, how much does 2 * 3 three done. If we see, how much does 2 * 3 three done. If we see, how much does 2 * 3 become? First of all, if we apply our multiplication operator, then 2 * 2 becomes apply our multiplication operator, then 2 * 2 becomes apply our multiplication operator, then 2 * 2 becomes six. If we have found our answer, then what will we do with this whole spring which is 1 * 2 * 3? We will spring which is 1 * 2 * 3? We will spring which is 1 * 2 * 3? We will put it in our answer, okay, then we have got 2 back, okay, that means the intermediate answer was Tu, so within Tu, we will add one plus to Apna and check that three is Tu plus three, that's it, Tu plus three is five. Which is not equal to our six, so we will discard it. Similarly, you minus three, let's see, you minus three, minus one, which is not your answer. Similarly, you have three, now after three, you have Again there are three options either you can multiply your number or you can add your number or you can subtract your number, so first of all multiply your number and see how much will 3 * 3 become, 3 see how much will 3 * 3 become, 3 see how much will 3 * 3 become, 3 * 3 will become its 9 which is If you don't have your answer * 3 will become its 9 which is If you don't have your answer * 3 will become its 9 which is If you don't have your answer then you will discard friends, then you have three, okay then 3 and what is the next operator, next update means next number is back to you, three and your next operator is plus, okay then 3 + 3. It becomes 3 + is plus, okay then 3 + 3. It becomes 3 + is plus, okay then 3 + 3. It becomes 3 + 3 = 6, which is what is the target of Apna, 3 = 6, which is what is the target of Apna, 3 = 6, which is what is the target of Apna, means Apna has again got her answer, then what will Apna do again Apna, this spring is 1 + 2 + 3, okay, this spring is 1 + 2 + 3, okay, this spring is 1 + 2 + 3, okay, this is Apna We will push in our answer which will become this string, okay then back to our answer which is three, and this time the operator which we have is the subtraction operator, okay, subtract three from three. If we give 3 - three from three. If we give 3 - three from three. If we give 3 - 3, how much has it become, it becomes zero because our answer is not there, then we will start printing this also, the last number we have, that is, our last time 88 result is minus one, our next number which is You can add your own, that is three and you have three choices. Okay, so first of all let's multiply your own, then if you add yours one in three, how much will it come? Mins one in three is minus three because there is no answer of yours, so this is If we start append -1 + 1 / 3 then that start append -1 + 1 / 3 then that start append -1 + 1 / 3 then that tu will come which is also not our answer then we will discover friends too and if we add mines one minus three then that will come minus four. Since we also do not have our answer then this too. Apna will be discarded and in the last, all the Apna answers will be stored in the requesting sub, so these will be Apna answers, then Apna will return it in the last, where all the answers have come, this is Apna's simple solution, what will Apna do? You will store your first number like this and then you will always have three methods to add the second number. To add all the numbers after the second number, what will you do for that, you will do your research, you will run your method based on your recognition which is the first. There is a number inside it, first of all welcome the multiply operator and we will try to multiply our second number, we will run it again then what will we do by adding it to the number, we will try to do plus for the second number and then we will try to multiply it by subtracting it and see our For the next number and so on, wherever your answer will be coming, meaning wherever your string is, its size will increase, meaning your answer will come on the last number of your string and if your target is being achieved then your What will we do, we will add the string inside our R and if our answer is not being created then we will simply discard it and rewrite it. Once we see its code, what did I do in its code? First of all, I created my vector answer. And I have created a temporary string inside which I will first store my temporary answers, okay, and then finally, when my temporary answer becomes equal to my target, then I will do something with it in my final answer, okay. I have created a previous in which we will store how much each of our intermediate results is, that is, 1 + 2, how much is results is, that is, 1 + 2, how much is results is, that is, 1 + 2, how much is one plus, if it is three, then we will store it as our previous. First of all, we have passed our string in the function. Key starting means starting index is passed zero then I passed my full string means s then I passed my target answer string means passed vector string then I passed my temporary answers. Under which you are storing your temporary answer and passed your previous state and this is your result so it will come along with your current state. Okay, so let's look at our function once to see what this function is doing so that our What are you doing by directly returning your answer in the last, after running this function? Okay, so first of all I said that you have to start your answer only if it is equal to the size of your string, that is, in the last of your string. If you are standing then check that if you have reached the size of your string then what is your result i.e. what is your result after performing the current operation, is i.e. what is your result after performing the current operation, is i.e. what is your result after performing the current operation, is it equal to your target, if it is equal to your target. If so, it means that you have done all those operations on your string, then what will you do, you will convert your temporary into your ashram and return it to the final one, and if this does not happen, it is your research, if it does not reach the target, then what will you do? Will simply return, then what have I done, I have created a string, what will I do inside it, I will store my current number, if my number is three, then I am going to add or subtract it with my previous string, so what will I do? Now why have I done this, I have done this because inside this I have told you directly that I have to take my individual numbers but if my target is like this, then my target is That late post would be 36, okay then what do you have to do, it is 36, now you cannot make it with one, two and three, but if you suppose it is late, then you do 12 * if you suppose it is late, then you do 12 * if you suppose it is late, then you do 12 * 3, it is okay if you make it 12 * 3. If we do Assam, 3, it is okay if you make it 12 * 3. If we do Assam, 3, it is okay if you make it 12 * 3. If we do Assam, then it is okay, then how much is 12? It is 36 because it is equal to our target. Okay, so we return this, which means this is also a valid solution. It is not necessary that we have all the numbers in our string. You can also combine them to get individual numbers, so what I did is I created HD inside which I will store my current and I created current inside which I will calculate my current zenith, what was my answer till now, okay in this I started rating inside my Puri string that first of all I am seeing that if one is taken then once is up, the answer is coming, if vansh is or is coming, then from Apna 12, we will see that the answer is coming from well. What is it and if you are not getting your answer even from 12th then you will go to your last 123 and see that this 123 Sapna answer is correct, so what have I done, I have given my index, which means my starting index, whatever. Must be I have taken him and made him tally his last words or should I go till the last one and see if he is getting the answers on Cap Na Kahani also, that is, if Vansh is not getting answers then try combining Van and Tu together and make them 12 and even from 12, you did not get your answer. So let's suppose 123 and see whether your target is 123 or if you translate it as 123 then you do not need to apply any operator. It is normal if you write your 123 then that will also become your answer. Okay then I said. Then both of them had said that leading serials should not come even on Apna Kahaani. If it is 03 then it is not allowed, so I would have seen that if Apna Jo means Apna Jo has come, it is Greater Dane Index. Okay, it means Apna is a broken digital. The number is being created, it is okay, the index is your late supposition and you are trading on the third number, meaning you are trading on the third position, so what have you done, you have created one digital number and after creating 2 digital numbers, you have seen that Apna's first index was where we were standing, meaning G index Apna had to be started, it is zero, meaning Apna is serious A, leading zeros are A, so what should I do, break it, you do n't have to calculate for that, it's okay otherwise. Sir, what will you do, if it is not so, then what to do, what to store inside the current, your current number is ok, append your current number and what will happen, what to store inside the current, we store our actual numbers inside the current, ok then. How is the actual number of Let Suppose, first of all Apna Tu Aaya, okay then we will write it but if you want to make Apna today's chat number, Let Suppose 23 has been made, after Tu, three has come string meaning how the tweet is happening like this but within it Apna What we have to do is we have to add 10 inside the 2, so what will it become and then if we add plus to it will become 23. Okay, so this is how it is going on inside the numbers, so what I have done is that inside the current, these Now do 10. Now your current is zero. Initially do these 10 in the current and then min the value of zero in your string so that it gets converted in wait. Okay, what did you do with this? With this you made your whole number. This is your number coming in the spring so that instead of printing your answer string, print your temporary string and create this pane for your number so that you have also performed your operation and checked that your number is as per your target. Is it coming nearby or not? Okay, then what I have said is that if your index is zero, that means you are working towards your first number, you are working within the first number, then you do not need to do any operation. So what will you do, if your index is zero then you will not perform any operation, then how can you perform any operation on the first number, as if you had made it, then directly mines one mines, you mean mines one plus one in one. You can't do it like this, your first number will come naturally, after that your second number is ok for your string, for the target and your current means your current is even, what will come inside your sum, inside your currents. That is only the force number which will be its current, so what I said is that pass your current which will become your previous ring for your next operation, meaning the previous number will be created and now only current will be stored in your result because now your own For the first number, you have done it. Okay, then what I said is that if it is not so, your index which is not zero, then what you have to do is you will read your operation, so what I said, you run your string for the next number. Run it from And here I am, what have you done inside your string, first of all, the temporary string which was already there, that is, it was the previous temporary string, okay, that has been taken, then inside that. First of all, I have added my current string, that is, whatever number is my current, I have given it to us in the estimate tool, so first of all, I have to do plus, then I have to do mines, and then I have done these, now to do plus mines. There is an easy method for this, whatever is your result, add the current inside it or whatever is your result, min it, put it in the min operator and your previous will be used for your next operation. If there is an addition to the previous one, then it will become the current and I give my subtraction, it will become the current, but ours is multiplication, we cannot do multiplication like this, what will happen in multiplication, if ours was tu plus three, then this is okay. The entire result size is being generated, so if you want to multiply the latter by 10, then you will write these 10 like this. Okay, so this 10 should be multiplied by three, but if you multiply it directly, then what will happen that these 10 will be It will be multiplied by five and your answer will be 51 whereas the answer should have been 32. Okay, so what will you do to whiten this condition that it was 3 + 2 5. it was 3 + 2 5. it was 3 + 2 5. Okay, what will you do within the size? We will subtract three, that is, we will subtract our previous number which came then 5 - 3, number which came then 5 - 3, number which came then 5 - 3, how much is it, you are done and then what will we do with our previous number, we will add it back by making it 10. Okay, so what will it become 30 + 2 32 Okay, so for this become 30 + 2 32 Okay, so for this become 30 + 2 32 Okay, so for this I have done this entire operation and then in the last I am comparing here that if apni is at the last of the string then compare the result and return this in the last Let's submit our solution once and see
Expression Add Operators
expression-add-operators
Given a string `num` that contains only digits and an integer `target`, return _**all possibilities** to insert the binary operators_ `'+'`_,_ `'-'`_, and/or_ `'*'` _between the digits of_ `num` _so that the resultant expression evaluates to the_ `target` _value_. Note that operands in the returned expressions **should not** contain leading zeros. **Example 1:** **Input:** num = "123 ", target = 6 **Output:** \[ "1\*2\*3 ", "1+2+3 "\] **Explanation:** Both "1\*2\*3 " and "1+2+3 " evaluate to 6. **Example 2:** **Input:** num = "232 ", target = 8 **Output:** \[ "2\*3+2 ", "2+3\*2 "\] **Explanation:** Both "2\*3+2 " and "2+3\*2 " evaluate to 8. **Example 3:** **Input:** num = "3456237490 ", target = 9191 **Output:** \[\] **Explanation:** There are no expressions that can be created from "3456237490 " to evaluate to 9191. **Constraints:** * `1 <= num.length <= 10` * `num` consists of only digits. * `-231 <= target <= 231 - 1`
Note that a number can contain multiple digits. Since the question asks us to find all of the valid expressions, we need a way to iterate over all of them. (Hint: Recursion!) We can keep track of the expression string and evaluate it at the very end. But that would take a lot of time. Can we keep track of the expression's value as well so as to avoid the evaluation at the very end of recursion? Think carefully about the multiply operator. It has a higher precedence than the addition and subtraction operators. 1 + 2 = 3 1 + 2 - 4 --> 3 - 4 --> -1 1 + 2 - 4 * 12 --> -1 * 12 --> -12 (WRONG!) 1 + 2 - 4 * 12 --> -1 - (-4) + (-4 * 12) --> 3 + (-48) --> -45 (CORRECT!) We simply need to keep track of the last operand in our expression and reverse it's effect on the expression's value while considering the multiply operator.
Math,String,Backtracking
Hard
150,224,227,241,494
1,502
hey everybody this is Larry this is can make arithmetic progress from progression from sequence so this is Q one of the recent contest so you can watch myself this live after what's doing the contest so there won't be that much commentary but basically the idea I have is that okay we could make an arithmetic progression using all the numbers then they have to be sorted right because otherwise if it's not sorted then you're gonna run into a case where it gets bigger and it's smaller then well you oughta Magni can I make it so if you can make it you're gonna have to sort it so basically what I did was I sort it and then I just check actually very naively but for every two adjacent numbers I checked whether that is the same as the difference between the first two numbers and then that's pretty much it if it's not Dennis for us if it is then it's true pretty straightforward of end time apparently maybe we could do and then square with a thousand word but yeah oh sorry oh and on this point but after sorting which is and again yeah it's just brute force watch me do the live coding now no but sniffles
Can Make Arithmetic Progression From Sequence
construct-k-palindrome-strings
A sequence of numbers is called an **arithmetic progression** if the difference between any two consecutive elements is the same. Given an array of numbers `arr`, return `true` _if the array can be rearranged to form an **arithmetic progression**. Otherwise, return_ `false`. **Example 1:** **Input:** arr = \[3,5,1\] **Output:** true **Explanation:** We can reorder the elements as \[1,3,5\] or \[5,3,1\] with differences 2 and -2 respectively, between each consecutive elements. **Example 2:** **Input:** arr = \[1,2,4\] **Output:** false **Explanation:** There is no way to reorder the elements to obtain an arithmetic progression. **Constraints:** * `2 <= arr.length <= 1000` * `-106 <= arr[i] <= 106`
If the s.length < k we cannot construct k strings from s and answer is false. If the number of characters that have odd counts is > k then the minimum number of palindrome strings we can construct is > k and answer is false. Otherwise you can construct exactly k palindrome strings and answer is true (why ?).
Hash Table,String,Greedy,Counting
Medium
null
857
hello guys welcome back to the channel today we are solving Elite code heart problem 857 minimum cost to hire key workers I would highly recommend you should read this problem statement at least twice because it is little bit tricky so I hope you have read the problem let's jump right into it what it is asking to make a paid code group okay where we are following these two conditions are first is the second is minimum wage first is pages is according to relative what is related for example someone is paid 10. sorry someone has a quality 10 paid 70. now if we add someone to this same group here's quality 5 what he will be paid 35 basic match so it is clear now further question arises we need to paint this group minimum so it is so in first point it is told that we have to have related and to Define relative we have to fix something what is this is boss for this question and using some story so that it is more relatable rather than just some mathematical facts so we are using boss is one that According to which everyone is paid involves is paid 70. his enter links will be paid less according to their qualities so this story is cleared of why boss so no questions big question is something like that we want to make paid this group minimum and we have to decide their boss we can write this thing like this somehow quality your group into boss fraction why we did this because it is same as doing this repetitively if 10 minutes speed if 10 quality speed 70 what will be paid it will be a repetitive kind of calculation so converted this to this more generic some quality and boss fraction if you have some knowledge of maths then something should be in denominator that cancels quality so it is wage upon quality Force fraction is wage upon quantity why wage upon quality because we need wage so we cannot put this in this so basic maths basic uh why I am conveying because sometimes we don't these things don't strike so now our question is boiled down to sum of qualities so quality into voice fraction and the minimum wage has to be paid so we have to decree make this minimum and make this minimum so how are we gonna achieve this foreign questions like top K elements you must have known that there is only one quantity that is that one quantity that is to be determined but here boss fraction is also changing and sum of quality is also changing so we have to make sure that this is always minimum so to make sure this is minimum we will store this in the array sorry vector Vector of where or vector of vector Vector of vector why we are using this these containers you will understand so with was fraction we will put quality why we are using why we are pairing these two things because we need some and sum is changing every time we will go out look out of the loop calculate the sum that very much time taking so that's why we are clubbing these things together and we will sort in increasing order while increasing order because increasing order it is always in minimum increasing fact fashion this thing is clear and here as a result we don't have to think about boss fraction false fraction is taken care now other thing is sum of quality now this thing and how if we put some thought to it how we can maintain a sum that is meaning that is using priority U which type of priority you Max if type priority you why Maxi because in order to make us your sum minimum you have to eliminate the maximum so in order to eliminate the maximum you have to have a maxi because in the top there will be a Max you just have to pop it out that's it so these two things are cleared how our question boils down to this the only thing you have to understand is boss story because here the wages are relative and if I try to sell you mathematical time type of proof then into you there will be no intuition you cannot produce this knowledge again in some other question you need problem solving not rotten not rotter learning the solution just so what is the elbow is make boss action comma quality salt in increasing why to always have minimum always minimum handle some Authority using PQ Max Heap y maxi to eliminate the max now when it is when PQ size is equals to K compute and how are we gonna compute sorry how are we going to compute this which is by some wedge image into current boss fraction if question questions come in mind why current correction because as you can see it is increasing fashion and we also have to maintain the minimum wage if minimum wage is not that high of the boss then how will you be able to pay this one so current wage is for current boss fraction is used and if PQ size is greater than k as usual pop it pump and minus from Q sum minus sign let's take example and it is 10 25 and 25 it's what it is it's quality and this one is wages which is at 70 50 30 . 30. . 30. . 30. in case two let's make the vector boss fraction is which upon quality so 70 upon 10 comma their qualities with them uh wage upon quality comma 20 and wage upon quality their wage is 30. that is 5. so it is in increasing order this is 6 this is 2.5 this is 6 this is 2.5 this is 6 this is 2.5 this will be 7 so it will look like this six comma five and seven comma ten now this is clear this will be inserted because K is 2. r olity quality sum will be 20 plus 5 25 now as discussed here when p is equals to K we will calculate this so it's 25 into what is the current uh boss fraction is 5. why we are taking boss fraction 5 because we want to maintain a minimum wage if minimum wage of boss is not high enough how his under link will be paid it will be 125 okay now again this enter now this condition will be encountered P Cube greater than K pop Q minus sum will be and point to be noted we are taking Max C so the max is 20. this will be part this and this 10 plus 5. 15 now what is our current now this will go to this PQ size is equal equals to K because now we are again having to now the current is current boss fraction is 7 into 15 35 0 105. it is leg less than so this is our answer I hope guys you are understood the problem I know my English is a little bit here and there but that's why I'm making the video too have a more fluent it is almost 14 minutes now we will discuss the code please ignore the background noise if it is coming this is our container y double obviously we are taking fraction s making filling those con filling that container what is this we are typecasting because intent is int not so we typecasted our numerator because if we have one thing in numerator uh in double so we will have a whole quantity double and quality is same at it as it is sorted in increasing order are Q sum and our result it is what is this it is maximum it is just uh what I can I say a way of doing things when we are taking minimum we take Max that's if you do in affiliate code you know what is this it is Max Heap Maxi priority View we now are iterating on this container what is worker dot second quality we are taking the sum of quality pushing the same in the priority you while we are pushing the same into the priority because while we are doing the sum we need the minimum and how to get a minimum eliminate at the maximum so we have to put the quality in the maximum why not other thing we have taken care of other thing so what is the other thing boss fraction using the Sorting because if you have done problems like top K and all that we can handle only one thing in the priority queue not many things at the same time that are changing in this question sorry so if the parity size is greater we will decrease the sum and pop it out and when thus when we have our required size we will just calculate our fraction uh the wages it is just basic comparison and we will return the answer let's submit our code and see if it is running or not hope you guys like the solution I know my English is not very good but that's why I'm making video and you cannot cry about things you have to get better there is no one coming to help you are your own helper so keep grinding see you in the next one bye
Minimum Cost to Hire K Workers
positions-of-large-groups
There are `n` workers. You are given two integer arrays `quality` and `wage` where `quality[i]` is the quality of the `ith` worker and `wage[i]` is the minimum wage expectation for the `ith` worker. We want to hire exactly `k` workers to form a paid group. To hire a group of `k` workers, we must pay them according to the following rules: 1. Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group. 2. Every worker in the paid group must be paid at least their minimum wage expectation. Given the integer `k`, return _the least amount of money needed to form a paid group satisfying the above conditions_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** quality = \[10,20,5\], wage = \[70,50,30\], k = 2 **Output:** 105.00000 **Explanation:** We pay 70 to 0th worker and 35 to 2nd worker. **Example 2:** **Input:** quality = \[3,1,10,10,1\], wage = \[4,8,2,2,7\], k = 3 **Output:** 30.66667 **Explanation:** We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately. **Constraints:** * `n == quality.length == wage.length` * `1 <= k <= n <= 104` * `1 <= quality[i], wage[i] <= 104`
null
String
Easy
2260
690
everyone welcome to my channel so in this video i'm going to go over this question do some live coding work at the same time i'm going to try to follow the general interior steps while trying to solve this problem so first of all let's read through this question to get an understanding so you give a data structure of the employee information which includes the employee's unique id their importance value and their direct subordinate ids so for example is a leader of employee 2 and employee 2 is the leader of employee 3 they have the importance value of 15 10 and 5 respectively then it is represented by like a list of the two posts something like this and then note that although employee 3 is also a subordinate of employee 1 but it's not direct report so now given the employee information of the company and then employee id you need to return the total important value of this employee and all of their subordinates so it's something like um we try to trade the total of the employees importance value based on uh his or her importance for mario i know the importance value of his or her reports both direct and non-direct reports both direct and non-direct reports both direct and non-direct reports so for the for example something like this for the total of the importance value of employee 1 it is going to be 11 because 2 and 3 both report to number 1 importance value for 1 is 5 then a five for two uh sorry three two four two three four three until it's 11. so let's take a look at some notes so one employee has at most one direct leader and may have several subordinates so the maximum number of the employee will not exceed two thousand so it seems like not too much of the room to think about ash case at this moment uh let's think about how to solve this problem so for this problem um pretty clear not too much of the room to think about the solution essentially we are going to use recursion or dfs uh to solve this problem so what we are going to do is first of all we are going to have a map the key of the map is employee id and value is employee data structure employee class and then for this dfs uh we start with uh employee with id as id with within the input and then we call this dfs so the reason we have the map is for uh for to speed up the lookup otherwise if it is less than we are going to be very slow regarding the uh the lookup based on the id so the runtime is going to be all of n and is the number of the employees because we first of all we need to do one pass to pass this list into the map and also for dfs uh at most we are going to go over all of the employees so that's essentially why it is all event regarding the runtime so let's do some uh coding work on top of this first of all i'll just overload the function with guide importance but here we are going to pass a map as i said key is employee id value is the uh while there is the employee itself so employee is okay id all right so first of all uh we are going to go over this list and try to turn it into a hash map so we have integer and this will be over employ ease so employee map dot put the employee e dot id and employee self so that's it and then the next part is we are going to try to call this overload function guide importance passing the employee map and the corresponding id so um so total value as equal to zero first of all we are going to have um okay so first of all we are going to get the employee e is equal to uh well if it is if it doesn't exist then we definitely need to so if employee house the contains key if it doesn't have the id then you're just going to return 0. otherwise it means it contains the employee then we have the total value first of all start with well we first have the employee here employee is equal to employees dot get id and then total value starts with the value of the employee itself uh so id and then you go over all of his or her uh separate uh all of his or her direct reports so for let's say employee report so employee dot speed subordinates uh okay so this is uh employee the id so this will be like the integer well we go through all of the reports and uh total value plus equal to get importance on top of employees and the report id and finally we just return total value so that's pretty much it for this piece of code uh for simplicity i'll just rely on this platform to help us do the debugging and testing but in real interview you need to do uh testing yourself so let's see this uh for this two but they expect this three white is that so good importance let's see why so we have one two and three so we are looking for two so the output is all right so the out so the id importance and subordinates oh i didn't actually oh it's not id it's actually the important so that's essentially why um get importance yep so that i think this should be that's a typo all right so let's do a submission for this piece of code all right so that's it for this uh cooling question so if you have any questions regarding this piece of code or regarding the solution feel free to leave some comments below if you like this video please help subscribe this channel i'll see you next time thanks for watching
Employee Importance
employee-importance
You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs. You are given an array of employees `employees` where: * `employees[i].id` is the ID of the `ith` employee. * `employees[i].importance` is the importance value of the `ith` employee. * `employees[i].subordinates` is a list of the IDs of the direct subordinates of the `ith` employee. Given an integer `id` that represents an employee's ID, return _the **total** importance value of this employee and all their direct and indirect subordinates_. **Example 1:** **Input:** employees = \[\[1,5,\[2,3\]\],\[2,3,\[\]\],\[3,3,\[\]\]\], id = 1 **Output:** 11 **Explanation:** Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3. They both have an importance value of 3. Thus, the total importance value of employee 1 is 5 + 3 + 3 = 11. **Example 2:** **Input:** employees = \[\[1,2,\[5\]\],\[5,-3,\[\]\]\], id = 5 **Output:** -3 **Explanation:** Employee 5 has an importance value of -3 and has no direct subordinates. Thus, the total importance value of employee 5 is -3. **Constraints:** * `1 <= employees.length <= 2000` * `1 <= employees[i].id <= 2000` * All `employees[i].id` are **unique**. * `-100 <= employees[i].importance <= 100` * One employee has at most one direct leader and may have several subordinates. * The IDs in `employees[i].subordinates` are valid IDs.
null
Hash Table,Depth-First Search,Breadth-First Search
Medium
339
191
groups so the problem is coming we are given a binary integer or integer in the form of binary format and we have to find the number of ones present in the binary integer so let's take an example one two three you know how to calculate the binary sleep so two follow zero then the problem is one that is four those four then two brothers eight so if they're given an integer like one zero one and this represents one using digital represents two percentages one means yeah it's present to eight so eight plus two plus one is 11. so this is like let's say six is given then it won't match two it's six so we keep answer those so in this given integer this is the binary formula the first and third are given as one so first is what for this whole so four plus one four plus this is zero it is not taken then one side and we have to find the number of ones in the binary language so that is with and we do and operation of one because see if it can take this minor integer if I do it and operation is available so that this is how we calculate the number of points so initially you let's take this information so consider series it is so that is how we count the number of one so if this game rise to one then count will give to me then you should have one variable icon that will be incremented and yeah so once you finalize you have to move to the next remain integer present here so how do you get this so this is done by using the right check but here they have told it's an unsigned integer so we should perform unsigned by dry shift which will have the signal with three so this is so let's see now two what is the binary format of two only this number will be one remaining all will be zero so zero one zero which is nothing but one zero remaining integer which present here so by doing a fried chicken operation we reduce this input on all the remaining bits whatever foreign so one zero right okay 10 seconds you so in the Y connection here to see until X okay so one variable in count equal to zero so okay next start of the value by n not equal to zero you have to do this add operations account plus equals to n and plus then in this right shift operations so yeah our greatest uses written successfully something is
Number of 1 Bits
number-of-1-bits
Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)). **Note:** * Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`. **Example 1:** **Input:** n = 00000000000000000000000000001011 **Output:** 3 **Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits. **Example 2:** **Input:** n = 00000000000000000000000010000000 **Output:** 1 **Explanation:** The input binary string **00000000000000000000000010000000** has a total of one '1' bit. **Example 3:** **Input:** n = 11111111111111111111111111111101 **Output:** 31 **Explanation:** The input binary string **11111111111111111111111111111101** has a total of thirty one '1' bits. **Constraints:** * The input must be a **binary string** of length `32`. **Follow up:** If this function is called many times, how would you optimize it?
null
Bit Manipulation
Easy
190,231,338,401,461,693,767
9
in this video we'll be going over leak code question number nine palindrome number give it an integer we have to return true if the integer is a palindrome and return false if it's not now a palindrome is a sequence that reads the same backwards or forwards for example these numbers are palindromes because reading them backwards still results in the same number however these numbers would not be palindromes because they result in something different now there's actually a very simple way to do this which is to First convert the integer into a string reverse it and then see if the reverse string is the same as the original string and this right here is just Python's way of reversing a string now this solution works but the question challenges us to solve this without converting the number to a string so here's how we're going to do it the idea here is that we don't actually need to reverse the entire number we only need to reverse half the number for example if this is the number we can just reverse the first three digits and then compare these two to each other if they're the same then the number was a palindrome but how will we know when we've reached the halfway point well since we're transferring digits from the original number to the Reversed half the original will be greater than the Reversed half until we reach the halfway point when the original half is less than or equal to the Reversed half we know that we're done we can also handle numbers that have an odd number of digits but we'll just have to recognize that the two numbers will be off by one digit which will be attached to the Reversed half so let's take a look at how we can do this in Python let's assume 1221 is the number X that we are given first we need to take care of some edge cases if a number is negative then it can never be a palindrome since the minus sign would always appear on the opposite end so we can just return false immediately the other case is that no number ending in a zero can be a palindrome because it would also have to have a leading zero for example for the number 10 to be a palindrome it would have to be written as 0 1 0 which is not a valid way of writing numbers so the way we test if x ends with a zero is by calculating X Mod 10. remember the modulo operator Returns the remainder after performing division so if the remainder after dividing X by 10 equals 0 then the last digit is a zero and we can return false now the only exception to this rule is the number zero itself so we also make sure that the number isn't zero next we'll create a variable called half that will contain the Reversed half of the number now we'll enter a loop as long as X is greater than half which is how we'll know that we've reached the halfway point so now we'll update the half variable and I'll do this in two steps to make it clear what's happening so first we'll multiply half by 10 which doesn't do anything right now since half equals zero then we'll take X Mod 10 and add the result to half well 1221 mod 10 equals one so now half equals one the next step is to update the X variable using floor division remember floor division will round the result down to the nearest whole number so 1221 divided by 10 then rounded down is 122. notice that what we effectively did was transfer the one on this side over to the other side now 122 is larger than 1 so we'll loop again first we'll multiply half by 10 so 1 times 10 is 10. this is so we can make room for the digit that we're about to transfer next we'll do 122 mod 10 which is 2 and add that on so now half is 12. next we'll do floor division with 10 again to update X and 122 divided by 10 rounded down is 12. at this point 12 is not greater than 12 so we'll exit for the last line of code we'll check two conditions and if either of them are true we'll return true remember that if the original half is equal to the Reversed half then the number is a palindrome so that's what we check for here in this case 12 is equal to 12 which means we do have a palindrome since this part is true the function will return true and we are done now you may be wondering what about this part well that's the part we have to use if x has an odd number of digits let's do another example to see this let's say one two three two one is our new number the function will start out the same way by declaring a half variable and entering the loop the next two iterations are essentially the same as the previous example first we'll multiply half by 10 and add one so half equals one and we'll reduce a digit from X next we'll multiply by 10 again and add 2 so half equals 12 and we'll update X so that it's now 123. at this point x is still greater than half so we'll Loop one more time we'll multiply half by ten and now X Mod 10 equals three so half equals 123. X is then updated to be 12. now X is less than half so we exit and evaluate the return statement 123 is not equal to 12 so this part is false so let's evaluate the next statement here we recognize that half may have one extra digit at the end so we'll four divide half by 10 and then compare the two now 123 becomes 12 and we can see that they are equal to each other therefore the number was a palindrome and the function returns true
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
318
hey everybody this is larry this is day 29 look at all those checks uh of the leeco may dairy challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom maximum product of world links um yeah hope everyone's doing well the new contest or one of the new contests is cut in at least for me in about 40 minutes so hopefully this is good practice didn't do so well in the earlier one mostly because q4 required um what is it called uh segment tree which i am familiar with but it's been a while uh or you know yeah i just didn't have yeah i'm just not as familiar uh with it in a good way but uh yeah uh anyway uh yeah uh let's go given the stream we're trying to maximize of length i and j okay uh where the two words do not come okay yeah uh okay so i mean given that n is equal to a thousand square should be fast enough of course this being the code and this is python this is a little tricky right and also because okay i said n square is fast enough or at least a thousand squares fast enough but that means that you have to do the two words not sharing a common letter part in a very quick way if you don't then it'll be you know like if you just do i don't know something that goes through each one every time then and it's going to be too slow so what you want to do is pre-process it such you want to do is pre-process it such you want to do is pre-process it such that you are able to do set intersection in a quick way i think to be honest i think if i were to do it in a clean way i would have something like this right so i have um let's say okay and as you go let's do it then let's just wait it out and what i mean right so i have sets as you go to um i'm going to say this for so that basically we have a set for each uh word and then we could pre-process it such that pre-process it such that pre-process it such that of course basically let's actually ignore the pre-processing for now we'll ignore the pre-processing for now we'll ignore the pre-processing for now we'll ignore this thing for now um with pre processing let's say we have something like this and then we have some like uh check whether words of i and what's up j uh have common uh letters right and of course this is going to be very expensive because it's going to make a thousand say you have to look through the word if you have to look through the word you're already kind of lost and so um so we have to do some pre-processing um so we have to do some pre-processing um so we have to do some pre-processing right because this is a thousand even though you can maybe make it out thousand over two or a thousand square over two uh by doing just this just one simple trick uh well yeah uh and then now and then if this also takes a thousand by looking at the word you're way too slow so basically we can reduce this to 26 but it probably is still too slow because if you think about it's going to be 26 times a thousand kind of over two for a thousand choose two but uh and if you really do the math it is still like 13 million or something like that right i'm just doing it off my head but which to be honest in most language is probably fine uh but in lead code lego it's is very weird for python but this is a good thing anyway so yeah so we do this that'll be too slow 26 being the number of characters but um and this is what we would have right so our pre-processing would have right so our pre-processing would have right so our pre-processing would look something like this let's just do it anyway where uh sets up i is equal to let's just say get set of words right actually i guess we can just do none times n and then just do it here also words of i not words but yeah so now given a word and a set is what it what we want is just a set of order characters we've seen right so for c in word s dot at c return s and that's pretty much it um we're going to run it i just to be clear i my expectation is that it doesn't um doesn't fit but basically we can do something like if set of i and sets of j meaning that if the intersection if the length of this is equal to zero meaning that they have no common letter because this is just a set intersection it says in the second have no calculator then we do um oh we do the length okay let's also just do the length real quick uh so links just go to um and this one is easier to write when we uh help uh length of word survive right so if they're in this section then they'll also have a best for answer that's just the way that i write it and then here uh current is equal to length of sets of i oh but i really did this right sorry length sub i times length sub j and then if current is greater than best is real good um yeah so this will uh be correct unless i have some typo but like i said i don't expect oh i don't know if this will pass just and this is some of this is python some of this is lead code or a lot of it's leak code to be honest because you know 13 million it should be fast enough to pass but yeah so we'll see let's give it a submit i like i said i don't know that i expect to pass but let's see how long this takes right uh oh actually it does pass so i lied here um yeah so this looks good then but what i was gonna do is turn into bit mask right so now um people ask me what a big mask is a lot and i do a tutorial on it and this time i'm going to use this up as an opportunity to go over a little bit of what i what this is right so this is going to be fast enough of course but as you can see but what we can do is change this right so instead of so this is now uh gets a set of characters of word right so then now another way to write it of course is a boolean away right so instead of a set we can just do force times 26. and then now we can do something like s of c is equal to true it doesn't really work because see we have to convert this to um we have to do this and then now you have to write this in a little bit different way but that's basically the idea right let's we just convert it to a set to a list of 26 characters and of course there is some you can think about this as a boolean array but another way to do this is actually just having a bit mask right and a bit mask is the same idea as this um except for now instead of you know if you think about this array what does that look like right so that's going to be initially it's going to be force dot force right so 26 of these i'm just going to abbreviate another way of writing this um just for visualization it's going to be f or something like that right 26 of them just for 10 areas because and then now and of course it's an easy understanding the first one is a the second one is b c d e f g right so then now we just have to flip it and what this does is that let's say we see a letter c we go to letter c the third letter and we flip it from f to t and basically that's all we're doing with big mask right so now what is a bit mask is just transforming this boolean array into an um a bit array right so now instead of ffff or false force first was force you now have a bit that number that represents all the zeros right so now these are all f's and if we let's say convert it at a c we just convert it to the third character from zero to one and that's basically the idea that we're doing so let's do that so that let's say s is equal to zero and then here instead we do right and uh if this looks awkward to you it probably is you know for the first time but basically this is just i um left shifts by the number of characters so basically you're saying let's say we already have s and let's say this is s what we're doing is we're now just getting a number that's shifted by some um some number bit and then so this is let's say this is uh yi i'm shifting it to the right so maybe that's a little bit confusing but now we all or you go it so that this basically sets it from here and then puts it here it's basically what it does and if it's already a one then it just you know does nothing so that's basically the idea here and here the n does the same thing which is the intersection right so now you're given two of them and if they contain a common letter that means that the bitwise n will have something that's not zero the only way to have no common letters is if they you go to zero so basically if this is equal to zero then we do this other magical thing and that's basically the idea a bit math doesn't have to be tricky but you just have to get used to think converting what we did um you know a bullion array of 26 characters two just bits of 26 characters right and this looks okay let's give it a submit and see if it's that much faster i suspect that's yeah that's probably what i did a year ago um yeah uh let's have i'm just curious because yeah there's something that i would do a little bit uh but yeah um that's pretty much it like i said this is gonna be n also n so this is gonna be n choose two because we know uh yeah it's gonna be n choose two and this is still uh technically 26 but now you're doing you know all the numbers together which is why it's faster and as i always say this is only a constant speed up so yeah i mean it is what it is and in most languages uh this will only be fast if the sets are like up to 32 characters or maybe even 64 if you use it long but yeah otherwise as you can get see this actually shifts gets a little bit expensive and even the oil gets expensive uh if you get too big so definitely look out for that uh cool uh that's all i have for this one let me know what you think stay good stay healthy to good mental health i'll see you later and take care bye
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
478
hi everyone this is sunny kumar from iit bhu and welcome to my channel code with sunny and today i am going to discuss the problem generate the random point in a circle index number is 478 and the problem is of medium type of lead code okay so let's discuss the problem now given the radius and xy positions of a center for circle and we have to write a function rand point which generates a uniform random point in a circle please uh note the term uniform we have to generate the uniform random points okay that are in the circle okay so there are some important points also given along with let's read it out a lot input and output values must mean floating point okay and radius and x-ray positions of center of the circle x-ray positions of center of the circle x-ray positions of center of the circle is passed into the class constructor okay a point on the circumference of the circle is considered to be in the circle oh yes that's what i want to uh get that okay land point returns to size 2 into array containing x positions and y positions of the random point generated okay so we have to do that okay so how we are going to approach this problem and what should be the logic to this problem let's move for them okay so i'm going to just to write down the code and along with i'm going to explain how why this is happening and what should be the exact logic to that okay so let's move further okay so i'm going to do one thing let's uh write it down first let's define the pi values let's say constant okay constant double and i'm going to declare my pi as three point one four one five nine and it would be like two six 0 5 3 5 8 9 7 9 then i have 7 3 i think and then it should be like that okay i think it doesn't matter about that so okay so also i'm going to declare three from three variables of double type double m radius and it would be like also m x enter that would be center okay and i'm going to also declare another variable of double type and it would be like my center okay and let's move further to write down the functions so in the constructor i need to declare uh i need to declare the m radius mx enter and my center so let's uh do that okay so m radius should be written as i'm going to write radius simply and what should we do in case of mx center and my center i simply assign them as it is so my mx center would be simply x enter okay and what should be my m y center my center would be simply y center okay let's move for that so i need to declare the rand point function now or show how i am going to write the my rand function so let's focus on that okay so first i need to we all know that to generate to have a general equation of a coordinate on the circle we need to write the coordinates as x equals r cos theta and y equals r sine theta okay so for generating the random part we need to generate a random degree and we need to generate a random radius to be so that we can generate any random point in the circle or on the circle okay so first let's define a random degree theta okay so i am going to write here double theta should be twice into and i am going to write the value of pi and into a let's call a function uniform note that i need to generate a uniform function that is uniform points so let's define a function here again i need to write a function here double uniform that needs to return the uniform random values so let's write it down like return the double value of random values that is random is going to generate it is like let me write here r a and d rand function and let us divide it by random x okay i think this should be fine okay so this will return the double value so i have generated the random theta and what about generating the random radius double r equals i think you should write as rand no many you viewers will think it must be the double radius that is random it should be rand function directly and that is i need to call a uniform function sorry i need to call a uniform function but this doesn't happen why this doesn't happen because it does not generate the uniform function uniform random points so the reason is that let's move to analyze the with the help of picture okay so let's move to that okay so you can see here i have a diagram here so that is going to denote the reason specific reasons why this is happening so let's look at the math that leads to the square root of lambda because i am going to write my new radius as r equals square root of uniform function so why i am taking the square root this is because let's say as you let's write it down assume the simplicity that we are looking with the unit circle that is r equals to one so let's first assume that we are looking for the unit circle r equals to one so the average distance between the points you can see these are the points the average distance between the point should be the same regardless of how far from the center we are going to look okay so this means that for example that looking on the perimeter of circle with circumference 2 that is i am going to consider this now circumference 2 they should find twice as many points as the number of points on the perimeter of a circle with circumference one okay so you can see if i am going to look on the circle with circumference 2 we need to find the number of points exactly equal to the double not going to say exactly i want to say that twice as many likely as for the circumference equal to one so in that case uh we need to consider a such a method so that it can generate the uniform random points for every r okay so i'm going to say one thing i'm going to add one thing more since the circumference of circle uh 2 pi r in we all know that the circumference is going to be written as like 2 pi r circumference 2 pi r grows linearly with r it follows that the number of random points should grow linearly with r so in other words we can say the desired probability density function goes linearly okay so according to this these concepts there's another involvement that we can also say that according to the uh according to you can say that i want to add one more thing we are going to use a trick inverse transform sampling if i am going to consider the inverse transform sampling it says that for generating the uniform radius we need to consider as r equals square root of the random function sqrt of random function okay so i need to consider the square root of the random function to generate the uniform points on the circle okay so also you can also there are many reasons to prove that also you can say note that the point density is proportional to the inverse square of the radius so hence instead of picking r we can pick from 0 to r max square in inversely you can say r is going to be the square root of the theta okay so i can say so it will be as simple just take a square root of the random function okay so let's move further okay so i need to complete this one okay so i need to take a square root of this uniform function okay then what should be our answer in this case that is return vector of double i'm going to return the double so it would be like just simply write down mx center because we all know that any point on the circle or inside circle can be written as r cos theta uh x as r cos theta and y s r sin theta i have generated the random theta and random r is going to be generated with the help of square root of uniform function okay so mx center plus radius into m radius and it should be multiplied by cos of simply theta okay and i need to give a comma here and need to write another parameter that is my center plus r into m radius and it should be multiplied by sine theta now because i am dealing with y coordinate i think this should be fine okay so i should give a here okay so let's run this function and check it out if this is going to be a fine or not okay so yes it is fine so let's submit this code directly okay so if you have any doubts do not forget to mention in the comment section of the video and i will ask you to like this video share this video and do subscribe to my youtube channel for latest updates thank you for watching this video
Generate Random Point in a Circle
generate-random-point-in-a-circle
Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle. Implement the `Solution` class: * `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle `radius` and the position of the center `(x_center, y_center)`. * `randPoint()` returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array `[x, y]`. **Example 1:** **Input** \[ "Solution ", "randPoint ", "randPoint ", "randPoint "\] \[\[1.0, 0.0, 0.0\], \[\], \[\], \[\]\] **Output** \[null, \[-0.02493, -0.38077\], \[0.82314, 0.38945\], \[0.36572, 0.17248\]\] **Explanation** Solution solution = new Solution(1.0, 0.0, 0.0); solution.randPoint(); // return \[-0.02493, -0.38077\] solution.randPoint(); // return \[0.82314, 0.38945\] solution.randPoint(); // return \[0.36572, 0.17248\] **Constraints:** * `0 < radius <= 108` * `-107 <= x_center, y_center <= 107` * At most `3 * 104` calls will be made to `randPoint`.
null
null
Medium
null
297
in this video we're going to look at a legal problem called serialize and deserialize binder tree so um the goal for this question is that we want to take this binary tree and we want to serialize this into a string so that we when we deserialize this we take the string that we serialize and then deserialize this and turn it into a binary tree right that we can use um and then the tree node looks something like this where it has a value the left node at the right node and then uh where the goal is we want to construct this binary tree once we get this string right so to solve this problem first we have to know what kind of tree are we getting in this case we know that this is not a complete binder tree because the complete binder tree will look something like this we are building the tree from left to right but this is not right where we can see that we have left node which is empty right in this case we have right notes right children um so in this case we're not getting a complete binder tree and um so what we have to do is we have to figure out how can we traverse this binary tree so that we can serialize this and at the end when we can be able to apply the same algorithm to deserialize this uh this binary search tree right so in this case one way we can do this is we can do a level or traversal right there are four ways to traverse level water pre-order in order and level water pre-order in order and level water pre-order in order and post order traversal so one way is we can use level or traversal right we can just like what the example is showing us we can traverse level by level we take this node two three and then null four and five right just like what example says so if we were to turn this into a string like this how can we reverse back how can we just like turn it into a string so in this case if we were to turn this into string what we can do is we can apply the algorithm or i should say the formula where if i want to access the left tile for no one all i have to do is just say uh the current index right n times two plus one this is the left child for the right child in this case is going to be n times two plus two right in this case it makes sense zero plus zero times two which is zero plus two is two so in this case the left the right child is three the left child is two but it works for this example right but what if we have example what if we have a situation right where we have something like this where we have a node six here and a node seven in this case if we have a node six here in o7 we cannot apply the same algorithm because in this case if we were to uh serialize this right we will get something like uh one two three null four seven right in this case because there because this part is already null so we cannot get its chosen because this is already null so we're going to get six seven and null so in this case one two three four one two three no null four five six seven and null right so if i want to access the no force left children we apply the same algorithm this will give us index 11 right but the index for this one right here will be one two three four five six seven eight right in this case we're going to put 6 here and 7 right here and then x or null or not we're not right so in this case this is going to be 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 so in this case it will be index seven so it will give us an inaccurate answer so we cannot use level or traversal like this so how can we solve this problem what we can do is we can either use pre-order or post order because what we pre-order or post order because what we pre-order or post order because what we can do is we can serialize the current node then we can serialize the sub left subtree then we can serialize the right subtree and at the end we're going to get something like this where 1 2 x which is the left and the right children right the left and the right child for no two and x basically symbolize null and then we can have three which is the right side right once we're done with the left serialize the left side we're gonna focus on the right side which we have three four five and x and so on right this is the um the left and right child tile for the no four and the right the left and right tile for no five right so we get something like this and what we can then do is we can apply the same algorithm to dc to deserialize by simply having an index right in this case we can have an index that points to the current index which is starting in here right we deserialize the current node right in this case we have us we're going to turn this into a string uh string array right we by simply splitting the comma we get a string array and then what we're going to do is we're going to starting from the uh the first element and we're going to deserialize the current element we're going to turn this into a root node then we're going to have a increment index by one and we just uh passed down recursively to serialize that uh deserialize the left side once we serialize the left side we're gonna come back and deserialize the right side right where i should say the right subtree right so the goal at the end we want to return the root node so we're just going to apply the same exact algorithm right which is going to be pre-order traversal be pre-order traversal be pre-order traversal or you can also do post order but i find that pre-order is more straightforward that pre-order is more straightforward that pre-order is more straightforward so in this case i'm just going to apply pre-order traversal in this pre-order traversal in this pre-order traversal in this question so let's try to do that so what we're going to do is we're going to have a recursive method so we it takes a root node right in this case what we're going to do is that if the root node is null right for example let's say we have an empty uh the root is null right we can what we can do is we can just return we cannot just return a null in this case we're going to return a string representation of null okay so we're just going to return x once we have that base case then we're going to do is we're going to deserialize the left side deserialize the right side and then at the end what we're going to do is we're going to return with the current root node the value plus the left substring right or i should say the left side the string of the left subtree and the string of the right subtree and we separate them with a comma so we have something like string left which is equal to serial lies roo dot left serial lies root.right and then we're going to do is that we're going to return without value with a comma and we're also going to return the left plus a comma and we're also going to return plus the right so this will give us so first we serialize the left side and then we serialize the right side if the current node is null we're going to return a x symbolize a null right so in this case once we've done that we're just going to append it onto our current string which is going to be rudolph value plus comma plus the left string plus the right string right once we've done that what we're going to do then is we're just going to focus on these serialize and to deserialize we're going to do is we're going to need a um we're going to need a stream array and then we're also going to need an index which start at zero and this will be a global variable because in this case we're just moving um basically moving each and every single element pretty much getting iterating each and every single element in the array right and we're just similar serialize the current element serialize the left side and the right side we're traversing the left side once done which is going to start traversing the right side building our right subtree so the goal is so the way how we do this is pretty simple we're just going to say array is equal to data.split array is equal to data.split array is equal to data.split with splitting based on the comma and now we're getting a strain array then we're just going to return a dfs method okay we're not passing anything because we're making array and those two variables are in a global variable and we're returning a tree node okay so we're going that first search right where we're basically building the current node traversing the left side to build it to build our left subtree and then come back traversing the right subtree to build it if the current value that the current index is pointing to is null then what we're going to do is we're just going to return a null value right so let's say we're taking this as this example if we were to serialize this we're going to get something like this um this case we're going to have x right and then we have the l the right subtree which is going to be 3 x or i should say 3 4 5. and then x right so in this case it's going to be the left and right for no four and left and right for no five then what we're gonna do is we're just going to say if the current value is x then what we can do is we can just return all right so if array at index um is so where i say dot equals right in this case arrays at index.equals index.equals index.equals x then what we can do is we're just going to return all but we also have to make sure that we're getting the current element the current index incremented by one so that we can move on to the next element right so what we're going to do then is we're going to deserialize the current element if that's not if this current condition doesn't satisfy so just to deserialize all we have to do is we just go and say tree node root is equal to mu tree node we're just going to say integer dot parse int this will convert a string into an integer we're going to say array at index and we also have to make sure we increment the index by one okay because in this case we're just going to move on to the next element after we're getting the element added onto the root and then we deserialize the left root.left is going to be dfs we're going to pas we're going to the depth for search the left side build the left subtree return its root pen and assign it onto the root of left then we're going to build the root out right which is equal to dfs okay and then we're just going to build the right subtree right and then at the end we're just going to return the root okay so basically we're defining our base case here right and then we uh deserialize the current value right we build our left subtree and then and return its root and build our right subtree and return its roots or assign the right to its root right and the goal at the end we're just going to return the final route so okay so let's try a few more examples okay so let's try was a weird case for example let's say we have six and seven okay so let's try to submit and here you can see we have our success so this is how we solve this uh serialize and deserialize problem on the code
Serialize and Deserialize Binary Tree
serialize-and-deserialize-binary-tree
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. **Clarification:** The input/output format is the same as [how LeetCode serializes a binary tree](https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-). You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. **Example 1:** **Input:** root = \[1,2,3,null,null,4,5\] **Output:** \[1,2,3,null,null,4,5\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-1000 <= Node.val <= 1000`
null
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
Hard
271,449,652,765
1,019
hello everyone i'm here to do my 100 lego challenge today we have leeco 101.9 today we have leeco 101.9 today we have leeco 101.9 next greater note in linkedlist so this question is very long but i can summarize in this example now this example is input as a linked list like a node and two is connected to uh one is connected to five and this is one of the list note and the problem is one we have to output a array integer array saying that if 2 is the first one and in the corresponding uh index right here they're looking for the next greater element which is five in here next greater element five also for one decent position uh we're looking for something as fine so that's greater element next greater note but eventually is a in the integer inside array so when five have nothing right there so we have to leave it as a zero another example in here this is a let's just imagine this is a list i mean uh linked less than 2 next greater note 7 had nothing on the right side stack greater than 7 zero for 4 f 5 for the next greater integer for three have five have nothing to zero so basically this is the idea of this question but okay before you start going to this um questions i wish you can go back and take a look at one of the example that i have uh i will put the link in the description it's called next greater element one and next greater element two you can see it in the link i highly recommend you to take a look at that one before you jump into this question because it's the same basically same thing so now we can um take a look at this question but in here um first thing we do i feel like it's cheating because we first changing the data type to a list new arraylist by changing the this node become this so while has not equal to no this dot at dot val and dot equal to hat dot next we're basically changing this data structure to become a list um sometimes it's just like that and it works stack we're going to have a stack if you want to have a clear explanation you can please go back to that to video new stack so output will be an array output new ins list i mean it's not size right so now we have everything ready we put this in later here it's much clearer in this way why do we need the stack um first we loop through this array now we if we have two we pop i mean put it in the stack uh if you see one put in the stack now we see five and five is bigger than 1 and then at this place we put 5 in here then pop out this one take out this one and now we have 2 only in the stack but currently the for loop is at five now we see two is smaller than five so two next number is five also so we fill this in here and after looping the array nothing to do i mean nothing for this five for the next element then we just jump out the for loop and this is unchanged becomes zero as a default now we have output as zero for all across all the integers no problem with that uh let's not size we look through the whole entire um what's it called a list arraylist while the stack is not empty and stack dot peak smaller than current list dot get i right actually peak is an intake uh index so we are looking for dot get start that works so if that happens so we will make output stack dot pop its index because we put the index in the stack we pop that out like when we pop this one pop that out is equal to list don't get i the current um current integer so cool other than that stack should add the current i because you want to put everything in there and after everything just return the output as a result this is it for this question um if you not quite understand this one uh you can please go back to the first video i go through step by step just like how we did in here it's just really similar hopefully you understand and also for the first video you have we use a double for loop to do this question too and that way is much more intuitive by using stack and here just a question that practice stack how to use a stack so this three video is basically the same questions and hope you get something out of this and i will see you in the next video bye
Next Greater Node In Linked List
squares-of-a-sorted-array
You are given the `head` of a linked list with `n` nodes. For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it. Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `ith` node (**1-indexed**). If the `ith` node does not have a next greater node, set `answer[i] = 0`. **Example 1:** **Input:** head = \[2,1,5\] **Output:** \[5,5,0\] **Example 2:** **Input:** head = \[2,7,4,3,5\] **Output:** \[7,0,5,5,0\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 104` * `1 <= Node.val <= 109`
null
Array,Two Pointers,Sorting
Easy
88,360
785
hey everyone welcome back and let's write some more neat code today so today let's solve the problem is graph bipartite I don't know if I'm pronouncing that correctly but we're given an undirected graph with n nodes now n is not given as a parameter but we're also given a second parameter which is graph but thankfully this is actually an adjacency list and usually in graph problems we have to build these ourselves but in this case it's provided for us basically the first or zeroth array represents all of the neighbors of the zero node so in this case we have one two three because the zero node over here has one two three neighbors and the same for the next array and so on so to get the number of nodes we can just take the length of this array we want to know if this graph is bipartite that means that we have to split this graph up into two distinct sets let's call them A and B and you can kind of think of it however you want but the simplest way to understand this is basically to say that every node in this graph cannot be in the same set as any of its neighbors that's the simplest way to think about this and when you think of it like that then the problem becomes a little bit easier not quite easy though and I'll be honest I probably know how to solve this just because I've kind of seen this pattern before but the idea is that any node can't be in the same set as its neighbors and when it comes to graph problems we know kind of the main algorithms available to us are DFS or BFS we know there's more academic algorithms but you always want to start with either of these can we solve this problem in a relatively simple way and in this problem we actually can so let's think about this let's just start from some arbitrary node and we always know the zero node is going to exist because the nodes are numbered from 0 to n minus 1. so let's say this node is going to go in a set let's say a and actually in this problem I'm going to be calling the sets either the odd set or the even set so for the first node let's put it in the even set so 0 is going to go here and the reason I'm putting it in even is because we're going to be alternating because now from zero like I said none of its neighbors this guy or this guy remember these edges are undirected none of these can go in the same set so all three of these nodes must go in the odd set but how exactly are we going to do this the way I'm kind of drawing this is a BFS because we're kind of going about it in this layer instead of just you know going to one neighbor and then running a DFS from that neighbor so that's kind of how I'll also code this up we're taking now this layer and now adding all of these to the odd set so one two and three now from each of these let's continue to run our BFS algorithm so maybe from three let's go to all of its neighbors well what we're going to try to do is go to this first neighbor and since we're coming from an odd node we expect this neighbor to be an even node in this case the node is already visited how would we know that should we have a separate data structure to check if a node's been visited not really because we're already keeping track of it here and what I'm going to be using for this is actually just going to be an array because we know each of the nodes is numbered from 0 to n minus 1 we can literally just use an array where probably we want to initialize the array initially with all zeros to say that none of the nodes have been visited but let's say maybe when we reach an odd node we number it with one and when we reach an even node we number it with negative one to distinguish between those two that should be easy enough and that's just kind of a minor detail you can kind of represent that with many other data structures but the important thing here is when we are continuing our traversal we go from a node and we reach a node that's already been visited well our expected was that this node should be an even node so we have to check is it an even node yes it is so that's fine and we definitely don't want to continue the traversal from here because it's already been visited we don't want to continue to repeatedly visit the same node that was good but now we're going to notice a problem from here now let's go to our other neighbor too the expectation is either this node has not been visited in this case it has been visited though and if that's the case this should be in the even set but it's not it's in the odd set that's a problem because these two nodes have to be in different sets we have a contradiction so this graph cannot possibly be bipartite but you might think well why did we make both of these red in the first place why can't this guy be green remember it was because of this Edge over here because yeah these two aren't neighbors of each other this isn't a neighbor of them either but these guys are neighbors if we got rid of this middle Edge over here then we you could kind of split it up like this where these two go in one set and these two go in the other set Now you kind of realize this problem isn't crazy hard once you kind of conceptually understand that some people solve this problem instead of distinguishing between odd and even like I'm doing which I think is intuitive because we want to alternate each time some people use color like when we start we're starting green and then the neighbors are going to be red and then so on are going to be green you can do it however you would like I'm probably going to stick with this approach though and since we are just doing a pretty normal graph traversal without repeatedly visiting the same nodes the overall time complexity is going to be the size of the graph in this case it's going to be Big O of e which is the number of edges plus v which is the number of nodes memory complexity though I think is just going to be number of vertices because we're already given an adjacency list we don't have to build it ourselves so now let's code this up okay so first thing I'm gonna do is create our odd asset I'm just going to call it odd and then I'm going to initialize it to this multiplied by the length of the graph and I said set but it's obviously an array and what we want to do is map the node index or the node I like the value of the node whatever you want to call it mapping that to whether it's odd and if it's odd let's say we set it to one and if it's even we set it to negative one it doesn't really matter you could swap these the important thing is that they are going to be alternating so now let's call our BFS starting at some node I what we're going to want to do is they clarify that this graph might actually not be connected so after we Define our BFS we want to actually run it on every single starting point so we're going to take the length of the graph and for I in that range we're going to want to call our BFS for every single I and if we try to visit the same node multiple times our function here should immediately return we don't want to end up doing that how will we know if we visited this node already well that's what we have our odd map for at least that's one of the reasons for it if this value is not equal to zero which we can write just like this then we want to return immediately and at this point we don't know that the graph is not bipartite so what I'm going to do here is actually return true because from this BFS we need some indication whether the graph is bipartite or not that's what we're calling the bs4 in the first place so we're always going to check the return value if it's not true that means the graph is not bipartite and at that point we can just immediately return false and if that never executes out here we're going to return true now to actually do the implementation of the BFS it's pretty cookie cutter well there's going to be a little bit of nuance here but the boilerplate is almost always the same we're going to create a q we're going to initialize it in this case with the I value you have to pass in an array to initialize the Q in Python and here I'm going to initialize this value also in the visit set and determining whether it's odd or even since it's a starting point and we know for sure this eye has not been visited because if it was we would have returned by now we're going to initialize it with a negative one I guess because this is going to be an even point and then we're going to say while the queue is not empty we always want to pop from the queue we're going to set that to Q dot pop left because when we append we're gonna append to the right and then for this node we don't have to mark it visited because the way we're doing it is marking it visited here as soon as we add to the cube we're going to be marking a node visited so we just need to go through all of its neighbors and thankfully we have an adjacency list that's provided to us and for each neighbor we will want to say Q dot append that neighbor and we'll also want to say for odd we want the odd of the neighbor to be set to the opposite of the node that we're coming from we want to alternate this now you can kind of see why I made this one and negative one we could have done one and two but that would have required a little bit of extra logic here maybe an if statement or something but when we have 1 and negative 1 we can alternate these pretty easy I can take the value from here and just say negative 1 multiplied by that so that's what the neighbors value will be but we don't necessarily want to visit every neighbor what if this neighbor had already been visited before how would we know that we would check if odd I and if it's been visited we don't want to visit it but there's actually another case if it's been visited and the odd value is equal to the node that we just came from these two nodes are adjacent and they have the same value for odd that means we found a contradiction at this point we should immediately return false so that's exactly what we do here and we only want this to actually execute if this node has not been visited so we do need to add an else here and not just an else probably an else if to say uh not odd of this node it hasn't been visited so then we're going to add it to the queue and give it a value and let me fix that now if we never return false from here we should go ahead and just return true and that is pretty much the BFS and being able to detect nodes with the same color slash odd value which I'm calling it and at this point I kind of regret not using Color you can do whatever is more simple for you I thought being explicit about the fact that these are alternating would be easier to understand but maybe that's not the case and I actually just realized over here we're always initializing this that's not the node that we want to check if it's not null or this is the node that has been visited already it's the neighbor that we want to check and I think we actually don't even need this line because it's a bit redundant this part would only be true if a node had been visited already so actually I'm just going to go ahead and get rid of that part of the code and just leave this as it is and I see the same exact bug down here of course this node is always going to be visited so we would never even append so here let's change that to the neighbor we want to make sure the neighbor is not visited and then we can go ahead and Traverse the neighbor so now let's run this to make sure that it works and as you can see yes it does if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io it has a ton of check out neatcode.io it has a ton of check out neatcode.io it has a ton of free resources to help you prepare thanks for watching and I'll see you soon
Is Graph Bipartite?
basic-calculator-iii
There is an **undirected** graph with `n` nodes, where each node is numbered between `0` and `n - 1`. You are given a 2D array `graph`, where `graph[u]` is an array of nodes that node `u` is adjacent to. More formally, for each `v` in `graph[u]`, there is an undirected edge between node `u` and node `v`. The graph has the following properties: * There are no self-edges (`graph[u]` does not contain `u`). * There are no parallel edges (`graph[u]` does not contain duplicate values). * If `v` is in `graph[u]`, then `u` is in `graph[v]` (the graph is undirected). * The graph may not be connected, meaning there may be two nodes `u` and `v` such that there is no path between them. A graph is **bipartite** if the nodes can be partitioned into two independent sets `A` and `B` such that **every** edge in the graph connects a node in set `A` and a node in set `B`. Return `true` _if and only if it is **bipartite**_. **Example 1:** **Input:** graph = \[\[1,2,3\],\[0,2\],\[0,1,3\],\[0,2\]\] **Output:** false **Explanation:** There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other. **Example 2:** **Input:** graph = \[\[1,3\],\[0,2\],\[1,3\],\[0,2\]\] **Output:** true **Explanation:** We can partition the nodes into two sets: {0, 2} and {1, 3}. **Constraints:** * `graph.length == n` * `1 <= n <= 100` * `0 <= graph[u].length < n` * `0 <= graph[u][i] <= n - 1` * `graph[u]` does not contain `u`. * All the values of `graph[u]` are **unique**. * If `graph[u]` contains `v`, then `graph[v]` contains `u`.
null
Math,String,Stack,Recursion
Hard
224,227,781,1736
1,842
let's go slowly colon signer 800 542 next 7 digits now for this question to give us string now and it is uh um you must numeric string and uh this kind of number industry which is uh hiring so um to ask between the smallest Point you're larger than num that can be created by rearranging its digits so uh what do we do let's take a look at say example one two one the next uh greater Penny using the same digits that is two one two and also uh this is also a planet but we know this is in a big sending order that's these three or two is extending order so there is no Next Step greater one using the digits the same digits so iterating our empty string and uh for this part four five uh four and four five for the next great one so five four five so what we do is that we can separate this number into two parts the left part and right so it's a popularly there is a one um uh in the middle right so if we can find the next parameter for the left part um then we compose the right part and then we can retain the results it is uh similar to the question of next permutation right so what we do is that from the uh for example we have a number to five to six four three one right so what we do is that we do from the right so let's find the first one which have purchase the elements number which have right here uh greater numbers that we find two right and then we're from six finder which number is greater than two um on the rightmost so that is the street right then um foreign from index um I mean not only to write but that must have a number of written in this uh platforms to last uh defined by the last uh remember the best and that's true index okay so we call this indexes is uh three of us right with us I'm gonna miss running next one so anyway right and that is not okay so um this will be about that so for our this numbers uh behind here right so popular there is a capital right so for this character we don't need to care about that and for this if this is left part you know we just handle this that part and then we um compose this one to um foreign so um we use a step one to step two to four to handle from this part right the left part so this part and uh and then uh after we doing this we come we just uh reversely to uh um so there's no character here right so what are we doing something um this is that this is uh um so um sound like something like a question so uh part uh and then part two that is we compose the whole stream and plus impulse that so let's begin to record for this so what we're going to do is that we can uh confidence want to be direct but it's in LA because let's get HMS and uh documents so you know if your name is similarly equal to 10 which member because before um it's out should I have no changes right um no chapter 10 chemistry because look say that there is a no uh no bigger one so what we need to do is that uh we complete M because uh a divided by two okay so what do we do is that the pro now we're handling the next permutation of the lesson okay so what we do is the relative index plus management for into I equals and minus one M minus one that's uh I waited equal to zero time management we need to have I equals m minus 2 because we need to compare it to the right so if you have commands uh noun I a smaller than my last one okay so be aware how well um index reports right so um the thing is I think if after we're doing this we bring that equals minus one that means uh the left part is in a descending order so for example return any screen right so this is a conquest is a bit different than the next limitation for next cumulation permutation we need to reverse um then what I need to do is find the last index greater than this now uh this number so what do we do is in the last index to close minus we know at least only the right one is greater than this that's all about the equivalent I was uh last index um all right related um this should be not right now this is a character one two three purple uh two is a greater than charge one right so we um we don't need to convert this to integer um index then we have the last index of course so for this one we don't need to break so this is step two step three is one so up for array that's this and then the last step is reverse all right that's platform to um so this uh well we are recompose from the left step right so uh for the rest that uh the left part for the rap part we just uh um your composite and whatever it is yeah maximizing and I fast pass what we are going to use array uh n minus one minus R equals array I in the end what we do is all right so we need to house uh swap in the reverse function rather it's uh go up uh all right we need to write that so what are we doing so when you have a temporary child and of course I like that close yeah and also um this is what up and uh also I have um reverse not right uh shy away I think so stop I mean okay so I really couldn't choose uh yeah I mean um that and uh we can't then move to start the interactions so you know how it is here um yeah right thank you um 9 17. now this is all right online right let me see us I need to write volume two but tons so um okay something like that time complexity would be oh um less right so it's done base uh we just covered this to charity to also be a lens
Next Palindrome Using Same Digits
number-of-calls-between-two-persons
You are given a numeric string `num`, representing a very large **palindrome**. Return _the **smallest palindrome larger than**_ `num` _that can be created by rearranging its digits. If no such palindrome exists, return an empty string_ `" "`. A **palindrome** is a number that reads the same backward as forward. **Example 1:** **Input:** num = "1221 " **Output:** "2112 " **Explanation:** The next palindrome larger than "1221 " is "2112 ". **Example 2:** **Input:** num = "32123 " **Output:** " " **Explanation:** No palindromes larger than "32123 " can be made by rearranging the digits. **Example 3:** **Input:** num = "45544554 " **Output:** "54455445 " **Explanation:** The next palindrome larger than "45544554 " is "54455445 ". **Constraints:** * `1 <= num.length <= 105` * `num` is a **palindrome**.
null
Database
Medium
null
140
hello everyone welcome back here is vanamsin and today we are diving into a challenging critical problem called World break 2 so let's get started first let's break down our problem so we are given a string as and a list of dictionary word and our task is to add spaces in the string to construct a sentence where each word is a valid dictionary word and returning all possible sentences so till to illustrate uh consider an example if our string s is cut sand dog and our dictionary words are cut cuts and sand dog our output should be cuts and dog at Sand dog so to solve this problem we will use an approach called Deep first search so DFS and a technique called memorization and DFS is a traversal technique used for searching the depth of any particular path before its breath and we will start with the first character and look for dictionary words that matches the first few characters and we recursively apply the same approach to the remaining part of the strings and we will find the matching words and we add it to our current sentence and move forward so it's very interesting problem and but we don't want to repeat the same calculation which is where memorization comes in handy so we will store our result in a dictionary and whenever we reach a point we have already visited we just fetch the result from the memorization dictionary instead of recomputing it so now let's translate this approach into a python implementation so we will Define a methods word break so it's already defined by list code in solution class with s and word as an input parameter and we start by creating a set of our words dictionary for a quick lookup and an empty memorization dictionary then we will Define helper function DFS which takes an index as n parameter and in our DFS function we'll first check if we have already computed the result for this particular index in our memorization dictionary if so we return the result right away and then we will look through our string as for our current index and we form a substring and if any substring is in our word dictionary we will recursively apply DFS on the remaining string so once we will have the result of the remaining string we will add a current word to each of the sentence we got from the recursion and if our current index reaches the end of the string s we add our current word as a complete sentence so finally we will save our results in our memorization dictionary using the current index as the key and return the result so let's implement it and the if this implementation works so let's start okay so word set word dict and memo will be just Helper and DFS index check if we have a result H for this index if index in memo dictionary then return memo with indexed and return empty list if index exit string length so if index is length s return empty and result will be RI and for e in range of indexes plus one Len plus s and substring will be indexed to I and if substring in word set so get the result of breaking the rest of the word so it will be result as res DFS of I index and 4. sentence in rest will be results append substring Plus empty sentence if sentence else wait and if it's the end of the word we add it as potential sentence so if I then of s result and substring save the result in our memo so memo index results and return result and return DFS of zero index so there you have it so let's now test our Solution on a few test cases and you will see our solution work or don't work and memorization techniques whether it make it efficient or not but main part if it's working hopefully it does so I'm running the test and yeah it's working at for example for this particular string of uh cats and dogs uh it could be read a cast sound dog and we have in dictionary cat cuts and sand dog and our output is both cats and dog at and cats and dogs so uh it's uh tricky one and also the for the second output same as mentioned before so uh pineapple pen Apple so we have a dictionary of Apple pen Pine and pineapple and it could form it so this particular string could be written as pineapple pen April or pine Apple pen apple or pineapple pen April so yeah so we have successfully done so it's really tricky but fun task so let's run it for unsynthesed cases so it will be much harder to pass it but yeah we done it successfully so there is much more test cases so if we skip some part in logic it might fail but this one passed everything so memory beats 11 so good and runtime also very good 50 8 of runtime bits and most important uh approach past so all good so remember understanding the problem and devising uh and a plan are just imported as writing the code so I hope this tutorial help you understand how to solve word break 2 problem using DFS and memorization uh with dictionary in Python and you have uh understanding of how similar problems could be implemented so thank you for watching and if you like please make a thumbs up and subscribe for more coding challenges tutorials Solutions and as usual most important stay motivated keep practicing happy coding and see you next time
Word Break II
word-break-ii
Given a string `s` and a dictionary of strings `wordDict`, add spaces in `s` to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in **any order**. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "catsanddog ", wordDict = \[ "cat ", "cats ", "and ", "sand ", "dog "\] **Output:** \[ "cats and dog ", "cat sand dog "\] **Example 2:** **Input:** s = "pineapplepenapple ", wordDict = \[ "apple ", "pen ", "applepen ", "pine ", "pineapple "\] **Output:** \[ "pine apple pen apple ", "pineapple pen apple ", "pine applepen apple "\] **Explanation:** Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** \[\] **Constraints:** * `1 <= s.length <= 20` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 10` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**. * Input is generated in a way that the length of the answer doesn't exceed 105.
null
Hash Table,String,Dynamic Programming,Backtracking,Trie,Memoization
Hard
139,472
11
hey guys welcome to the tech grant today we are going to solve the lead code problem of container with most water like and share the video subscribe to the channel to get further update so this problem says that we have to find container with most water and the container is defined using an array so given a non-negative integer array so given a non-negative integer array so given a non-negative integer a one to a n each represent a point at coordinate i ai and vertical lines are drawn such the two end point of line this and this find two lines together so and it has been given that no you may not slant the container and n is at least two so you will have some water trapped every time and the example given here is in the vertical line this is the case represented and max value is 49. okay so to approach this kind of problem you need to uh in this case you are not worried about whatever is there in between so it's simple max whatever value of this length and this width is there so basically that is the maximum amount of water trap or the max area that is trapped here so for this what you can do is you need to find between the two end points if you start from here and you go till here so between the two pillars in consideration whichever is lower so that will trap the water for you if this uh if something is more than this pillar so it will overflow basically so it will trap water only till this level so you need to get the lower of the two pillars at the far to end and multiply it by the distance between the two pillars so if i was considering this first pillar and this last pillar so water trapped between these two will be whatever value of this pillar length which is one into whatever distance between these two pillars are so there are nine elements here so the distance between these two pillar is nine or rather eight so that is the uh that is the amount of water or that maximum area which is start between these two pillars now to solve this problem you need to keep track of the lower pillar among the two and you need to get the track of true boundary so what we can do here is we will start from both and basically first to the lower end or the left side will use we can use two pointer solution here so the left side we can put it on zero and the right side we can put it on n minus one which is the last pillar here and the formula can be the minimum the whatever the minimum of left hand right we have uh basically it will not be left and right it is given as part of the height so it will be whatever height we have at left and whatever height we have at the right multiplied by the distance between the two which is right minus left so this is the zeroth position and this is the last position which is whatever length is there so this height dot length with n here n is equals to height dot length so this formula should give us the water trapped between any of these two pillars so to get the maximum if suppose this we store it in temp so max value will be max of face max val here so max will be maxwell comma 10 so every time i get more area i will just replace my max value with that value now how do we increment and decrement the two boundary the left and right so if i consider these two pillar now this pillar cannot trap more water than it is already trapping between the left and the right side because if you see the width wise this is the maximum that it can trap and height wise this is limiting me so out of the two pillar i need to eliminate this pillar and move on to my next pillar which is an element eliminate this pillar and go to the next pillar so by that logic every time among the two pillar that i have i will eliminate the smaller pillar so if the height of my left if it is less than the height of my right so in this case i will eliminate my left pillar otherwise i will eliminate my right pillar so if this is the case then i will increment my left boundary otherwise i will increment my right boundary so this is the logic that you can think of because the reason is very straight forward it is because this cannot trap more water than it is already trapping between uh the two pillars because we are limited by the smaller pillar and the distance between this and the right most pillar that is the maximum distance it can go so that is why it cannot wrap more water than that and it is only relevant to remove the smaller pillar among the two so let us solve this should be a pretty straight forward solution so if i say max equal to zero and i will return this max value and will have a left side like this which is equals to zero initially we'll have a right bound which is my height dot length minus one these two will be there do i need anything else i don't think so and we will go on till left is less than right so basically we are shrinking this space so we are we started from here and the left bound from here and right bound from here and we are moving towards this side so it's like the left is moving towards right and my right is moving towards left so we'll move this or we'll move this so this will be moved as long as the left is still lower than the right bound this will be the criteria and max value that we are calculating it will be math dot max of my max whatever we have so basically it will be this i will incorporate both the formula together so and it will be between this and the temp value so temp value will be math dot min and min of the same left hand right so it will be of this multiplied by the left minus the right minus left so whatever this value is there and i will multiply it by right minus left so this will give me my max value now i just need to incorporate this condition so again just copy it here if this is equals to if the right one is greater so i will increment my left otherwise i will decrement my right i think there is a mistake here so it will be minus i cannot go further towards right so i will just decrement this value so that should be it let us submit the solution it seems okay we'll submit so seems okay so that is how we solve the problem and this problem has been asked in a lot of big tech companies so i'll be solving further problems if you have any other problem that you want me to solve then do put it in the comment section i will visit it and i will definitely solve it for you guys so thank you for watching the video see you in the next one bye
Container With Most Water
container-with-most-water
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`. Find two lines that together with the x-axis form a container, such that the container contains the most water. Return _the maximum amount of water a container can store_. **Notice** that you may not slant the container. **Example 1:** **Input:** height = \[1,8,6,2,5,4,8,3,7\] **Output:** 49 **Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49. **Example 2:** **Input:** height = \[1,1\] **Output:** 1 **Constraints:** * `n == height.length` * `2 <= n <= 105` * `0 <= height[i] <= 104`
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle. Area = length of shorter vertical line * distance between lines We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
Array,Two Pointers,Greedy
Medium
42
645
um hello so today we are going to do this problem which is part of lead code October daily challenge the problem is set mismatch so we have a set of integers um which originally contained all numbers from 1 to n but there was an error and one of the numbers is duplicated and the other one is missing right um and so what we want to recover this and find the duplicated number and the missing number um yeah so that's pretty much it the duplicated number is duplicated only twice right um and the missing number is not there so for example here uh 2 is duplicated right and three is missing so we'll return two and three here we are supposed to have from 1 to n so one to two um two is missing and one is duplicated so return one two so that's the idea now how do we solve this um so first let's divide it into two parts the first part is finding the duplicate number um yeah so we can divide this into two things one is finding the duplicate number and the other one is finding the missing number so let's see how we can do that um so finding the duplicate number should be just um uh sorry we can just take the list of numbers and take the list of unique numbers so that would be one two four and just subtract what we get in result would be would contain the duplicated number right because the other ones occurred only once and then it will take one of the instances of the uh of the duplicated number and we will be left out with just this so to find duplicate it should be just um the sum here right of this minus the sum of this right we can also like convert those subtraction but it's easier this way to get the exact number right because this would be um this one would go with this one this two would go with this two this four would go this far and then we are left only with the duplicate number which is two right um so it's just the sum of numbers minus the sum of the unique numbers to get the list of unique numbers we just do a set of numbers right um okay so now we have the duplicate number how do we find the this missing number so we know that the numbers are from 1 to n right so we can just have the list of numbers so in this case it's one to four so we can have one two three four and we have the list of the other numbers which is one two four right um unique numbers right we don't want the duplicate number because we are not interested in so if we take the difference between the subs of these we should get the missing number right because we have the list of unique numbers right from 1 to n except the missing one and here we have all of them including the missing one so if we subtract the sums we'll get the missing one right um so that's pretty sure for there we can just say it's the sum of the numbers minus not the numbers we want the range from 1 to n here so that would be the range from 1 to n so in Python to get to n we need to do n plus one and what is n and it's just the number the length of numbers and then we need to subtract the unique numbers so that's sum of this maybe to make this more relatable you can we can do like unique is equal to this right and here we just subtract this and this is n just make this more readable here um yeah so that's pretty much it to get the missing number now the problem wants us to return both so duplicate first and then the missing one and that should be it so let's run this okay I'll submit okay so that passes test cases now in terms of time complexity we are doing oven here with the sums uh for each one of them it would be at most oven so overall it's oven time we are also using this set here in this sum of range here um so it's all vents space as well okay 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
Set Mismatch
set-mismatch
You have a set of integers `s`, which originally contains all the numbers from `1` to `n`. Unfortunately, due to some error, one of the numbers in `s` got duplicated to another number in the set, which results in **repetition of one** number and **loss of another** number. You are given an integer array `nums` representing the data status of this set after the error. Find the number that occurs twice and the number that is missing and return _them in the form of an array_. **Example 1:** **Input:** nums = \[1,2,2,4\] **Output:** \[2,3\] **Example 2:** **Input:** nums = \[1,1\] **Output:** \[1,2\] **Constraints:** * `2 <= nums.length <= 104` * `1 <= nums[i] <= 104`
null
Array,Hash Table,Bit Manipulation,Sorting
Easy
287
239
hey guys how been going this is Jer let's solve a lead code problem today it's 239 sliding window maximum you're given an array of integers nums there's a sliding window of size K which is moving from the very left to the very right you can only see K numbers in the window yeah each time the sliding window moves right by one position return the max sliding window what does it mean here is input this is an array K3 is window size we need to outut 3 35 67 so this is the array this is where the initial window is so the maximum of this window is three so three and then we move the window to the right uh with one step and then we got still the three is the maximum and five um yeah we move to five is the biggest one so now it becomes five and the next one is three uh this negative 1 still five six is the biggest one so it's six 7 3 6 7 yeah biggest seven so yeah let's just first try the uh naive solution we just move through move uh the sliding window and then um for each window we can just uh get the maximum right so that what does it mean uh we're just naive solution uh for each WI window uh for each we will move the window for n times and then uh negative uh technically it's uh n Nega k um but uh we need to travel through the items to get the maximum so it's still near here and then for each we W noop uh the window again to get the maximum so it's NK anyway this is maybe not the best let's first give it a try to S to get the maximum to get it right okay um so how do we do it so we need to start from the first element and uh go to the next element so my idea is we will use the I uh focus on the ending item ending deex and start um popping oh we don't need that we just start because for this kind of we just start from the uh this Index right and uh yeah and anyway we will go back and gets the items uh get gets the uh maximum from the within the K steps cool uh okay let's start so uh let's end the index which is I uh okay uh W four I equals okay then uh it should be K uh like one two three the index is K yeah and then i n and let's do some quick return here so if nums length smaller than K let's maybe give the give it a bigger size font size get uh code editor font size maybe 16 is better great oh this too big sorry this is New U not cool okay this is may be better okay uh yeah and here will return um we need to return Ray right just to return empty and uh and here we just uh create a result array yeah and then we want just to go backwards so for let k = i just to go backwards so for let k = i just to go backwards so for let k = i negative uh k equal I um maybe not yeah and we need it K is bigger than um I think it should be I negative K uh wait a minute if like three is one negative i1 -2 so i1 -2 so i1 -2 so it's -1 I uh K negative in uh -1 I uh K negative in uh -1 I uh K negative in uh decrease and then we will get the maximum right so let here we would just let maximum equals nums k a i equals K oh not K should be J sorry it's a it's conflict okay Noms I okay then we don't need to start from I we just from I negative one great and Max equals math Max uh nums J um and this means we just a push to resolve right push to Max and then we can return the result I think it should work it's pretty simple yeah wow this is a wrong answer what did we are missing one item I know what happened it's not K it's K negative one great let's submit I think it's t anyway the times yeah t Okay uh let's try to improve it this is a naive solution okay um let's look at the example again so um for this one I at 1 31 the next item is-3 and it's the smallest so we add it is-3 and it's the smallest so we add it is-3 and it's the smallest so we add it here well it's window we have to add it here and next one is one we can see that actually we get the same maximum because the one is smaller than three right three is the maximum it is smaller than maximum so it just to be popped uh without affecting the next one uh because ne3 um is smaller than 1 is smaller than three so three is the maximum now we get five becomes the biggest one and now these two are will not affect the maximum for the next few Windows right so you can see for next one it's still five uh I mean if the next one is bigger than five then yeah but this two will not affect this five so technically this could be replaced with a five so this is an idea so when we get uh let's start with one yeah and then we get uh 1 three right 1 three because three is bigger than one so we can actually replace this three it literally means that actually we don't need this um full array to hold two threes we can actually collapse it into a more compact data structure like just three together with its repetition like two threes in this array right and negative one is smaller than three so we can put it in it okay let's just uh yeah let's just uh use the parenthesis there two of them it means the there are two threes okay I just use the asterisk it's easier to type uh you know what I mean okay um the next one isg -3 so it's the next one isg -3 so it's the next one isg -3 so it's smallest so with this the biggest one are on the left and the smallest one on the right -3 right -3 right -3 right and but now it's only four items now so we need to uh move one out from the left which is three so we remove one uh right remove one was one actually but now uh we're removing three because it's not affecting the maximum so here we've already started collecting the maximum is three here when we get -3 remove out is three here when we get -3 remove out is three here when we get -3 remove out so it's still three and now we get five is bigger than every items here it's decreasing but it's bigger than ne33 it's negative 1 it's bigger than a three so actually it will replace all of them and uh it becomes three fives so now it's big it's five time uh three great the next one uh six is bigger than five so it becomes six we'll pop all of them and replace just a three six and uh the next one wait a minute is 3 three five double five where is this going to be six okay3 and three oh there's a three here sorry so it's three is smaller than it so it's 2 three now oh no this one it's two three two five and three now so it's still five and six is bigger than all of them so it's three sixes and the last one is seven is bigger than all of them so it's seven um three so with this Improvement what we get um for this one uh we can easily get the maximum from the left one you see it's three uh because this one is not enough so we three five six seven so we don't need to do the uh another loop inside the window again um and uh the every time we push an element if it is smaller than the right one the smallest on the right so if it is smaller we just push it otherwise we will keep popping right pop this one and push to the right position to keep it non decreasing or non increasing just decreasing uh decreasing array you remember wonder that if does that mean this uh it's still the uh same time complexity um that's not true actually um so for like for this one um for five here let's say when we pop neg3 it will be popped it will never come back again I pop negative 1 this item it will not be uh it will not come back again so for each item um it will come to this list maybe not all of them will come um maybe yeah it will be uh put into the array and maybe replaced with this the right item um and uh it will be popped naturally like a sliding window right go right and the leftmost item will be um popped or it will be replaced once so either way it would be gone from the array so it's still linear time um so it won't be like a quadratic time so for this approach we can actually improve the time complexity to Z uh to linear time um to but we need to maintain this extra stuff right it's space for time uh we use extra space to calculate some information um this one obviously it's linear space so it's linear space uh linear time the thing is actually we could do even better what is the meaning of this count it's actually like say it's actually for this three uh for this five let's take it take this five an example the five is here right 53 means actually the uh distance between the target item to the start index of the window let's say the actually uh the count equals the uh distance between um window left window star to and the target index so for example for this five it means for this three it means that this five is three um like three items away from the start so five here uh one two okay this one is 335 here right okay so five 3 three5 this one so this one is one item two item three item well the distance actually is two but um yeah I think yeah you know what I mean it's distance is two but there are three items count from the window right so actually this equals the target index because we already know the start index of this window uh we can actually uh make it even concisor more concise um just use this array use uh the index to replace the count so we need to use array to hold I would say the like a peak use the index to hold uh the peak like a not Peak items um how should I put it the yeah I don't know how to tell give you the name sorry for my bad English but anyway uh I would say the important ones okay cool so let's start from the first one um the first one the is obviously it's only one item so yeah and then three is bigger than one right uh so we keep it track of this index it's two and uh ne next one is uh negative 1 um negative 1 is smaller than it and so we keep this index three uh the item is 31 and uh from here we can start um collecting the results so this one is three um okay so the next one is uh neg3 so 2 three 4 steel three and the next one is five is bigger than um the three items so all will be popped and uh it will be five uh yeah the five the index five okay then item is five as well so this is five and next one is three so we got 5 six and it's still five and next one is six one bigger than all of them so the index is uh seven and we get uh six last one is seven the index is eight it's bigger than it so it's seven so you see that we can basically get the same uh I think this one is more easier to understand but once we know what's happening understand the this number is actually a distance between the uh index um it we can actually create the same um algorithm by both tracking the number and the uh number and the count but actually if we get the index we can both get the number because we already know the rate we can access the number and also we can get the distance uh is we can subtract the index from with the uh the window start right so we can make it even better so let's give it a try um here is the same now we need to use the array to hold the index let's say uh important uh indexes great uh so let's for now we will start from the uh I let I start from zero I smaller than numar nth i++ from zero I smaller than numar nth i++ from zero I smaller than numar nth i++ one okay so for each item we will try to update um the indices wait a minute what about a natural pop natural Pop um oh it's the same we will pop so here Nega one here we stop there one step missing here um is for 3 1 what about natural Pop um let's say um here five right 335 this one if the next one okay here next one is three so we push the index in if the next one is um here 2 3 4 2 three 4 three what if there is a Nega four right negative four then we need to actually push it push this two out so the index we need also like so natural pop uh we need to check if uh the index um if we need to pop naturally or uh forcely H yeah I think this easier to understand okay um yeah so for if for the item let's say the item is equals if keep like no uh put this item into indices array um with put item in into array by popping the uh smaller ones okay so let's start with uh how should we do it so while Let's uh top equals H how should I do this one top I think while okay if important IND thises if there's no such thing okay here if or k equals zero we you return okay if this one is zero empty we just uh push it otherwise we will keep pop the items right no not push the item that push to the index um and while important indices n is bigger than zero and the last item is smaller um or bigger or equal yeah if it is equal we still need to pop yeah if it's equal to the uh item we will pop it will pop so in the end um the we can just push the index indices so oh this one is the same so while oh yeah this one actually we don't need this yeah I'm stupid great so we pop it if the top item exists and also it's smaller or equal to the to it we just uh pop it and then we push it in um great so this is uh push and we will pop an item right this will start from if I um is bigger than K NE one we need to pop this is push um need to pop one from left also um I yeah here's we what when we need to pop and how do we pop as mentioned here for example if IND this is smaller than it then we do nothing right we only pop once it's um bigger than it or equal so if I is bigger than um bigger than the indices 1 we pop it on no on shift it's DQ uh which is uh shift sorry this is sound do we need this one for example for the first one it's one but it's equal to yeah we need this one so let's combine these two if we should try to pop and also it is bigger than this one then we pop it yeah and then we are ready to collect the result so the okay so this is the result this is auxiliary auxili auxilary uh sorry let me check if I get the right word it's auil auxiliary um array so it's not should not be count as the time uh space count uh cost result we push um we get this index and we can actually get the number um zero great I think it should work bam wrong answer ah okay oh why we get some why we get one H oh sorry yeah we should need collect only when it's ready so we need to actually keep this one I should verify my um implementation before i r if we should collect and also need to pop from the left and collect result okay we should put this before it ah run answer still god um what's the issue here let's verify it so we start from zero it will end at the last index we get the item which is one here this one is empty array so we just push the index in it so it's actually uh one uh zero I is bigger than it no K is three and the second one is three because three is bigger than the oh I see so this is index it's not Iden yeah this one is my bad bam still wrong answer what the heck um I for shift okay anyway um I think here we get the number because it's bigger so we pop and this one becomes one the next one becomes two I is two negative 1 um because we cannot pop so we just push the index so it's one two now we need to if I is bigger than the index oh this one is the start so actually is um I Nega K1 so it's minus k + 1 bam still run answer oh God I'm so stupid so anyway so for now two so is this zero so it is so we pop no actually okay here two I is two k is three so it's zero is zero wait a minute zero oh we should not pop yet wait this is wrong oh it's not so actually we it's different we should start collecting result from this one but we should pop after it so it's actually if I bigger than this one okay start from K we need to pop it but if yeah man bam jeez what's the problem here okay so I is two now three obviously we don't pop and here I two uh this one yeah we push the three in right we get three and then we go to next one is uh I is three -3 it's small so we uh I is three -3 it's small so we uh I is three -3 it's small so we push it so it's one two three okay now I is three yeah now we need to um pop and I is uh three this one yeah one is wait if it is the same okay this is the window of so oh it should be bigger than it we then shift if it is the same we don't need to shift wait a minute so when we shift it means inclusion so oh I see this is maybe the cost okay finally um I hope it works come on okay great works this is interesting I think I've done some similar questions before is like calculating the um his history histogram is it histogram the name histogram yeah calculated histogram um what I did before is still doing the same like uh collapse into uh rectangles by some uh nth account and actually it could be uh packaged into a more concise data which is the index this is similar I think um yeah it's pretty fun to solve it okay hope it helped see you next time bye
Sliding Window Maximum
sliding-window-maximum
You are given an array of integers `nums`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position. Return _the max sliding window_. **Example 1:** **Input:** nums = \[1,3,-1,-3,5,3,6,7\], k = 3 **Output:** \[3,3,5,5,6,7\] **Explanation:** Window position Max --------------- ----- \[1 3 -1\] -3 5 3 6 7 **3** 1 \[3 -1 -3\] 5 3 6 7 **3** 1 3 \[-1 -3 5\] 3 6 7 ** 5** 1 3 -1 \[-3 5 3\] 6 7 **5** 1 3 -1 -3 \[5 3 6\] 7 **6** 1 3 -1 -3 5 \[3 6 7\] **7** **Example 2:** **Input:** nums = \[1\], k = 1 **Output:** \[1\] **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` * `1 <= k <= nums.length`
How about using a data structure such as deque (double-ended queue)? The queue size need not be the same as the window’s size. Remove redundant elements and the queue should store only elements that need to be considered.
Array,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
Hard
76,155,159,265,1814
234
foreign question and the question's name is palindrome linked list so in this question we're given a head of a single linked list and we have to return true if it is a palindrome else we have to return false so palindrome is a sequence that reads the same forward and backward if you take a look at example one two one is the same when you read it from left to right and one two one is the same when you read it from right to left so we return true and here 1 2 is not equal to 2 1 so you return false so in this video we are going to solve using o of n space complexity and in the follow-up video I'm going to make a follow-up video I'm going to make a follow-up video I'm going to make a video on how to solve it with over one space as of now I haven't recorded that video yet I will give the link to that video in the description box below now let's take a look at this example and see how this can be solved I've taken the same example so this is the head of the linked list which is pointing here and we have the nodes one two one and the last node is pointing to null and I've created a list so that we can add these nodes as integers into the list and then check profile in row so I create a new word quad current and point it to the head of the linked list I access each node and go till the end of the linked list and add one node at a time into the list we created now current is pointing here so add the current dot val into list so one will be added here and move current to the next point now current.val is equal to 2 and point now current.val is equal to 2 and point now current.val is equal to 2 and add it into the list 2 will be added here and increment current is pointing here add current.vile to the list here add current.vile to the list here add current.vile to the list current.wal is equal to 2 again so add current.wal is equal to 2 again so add current.wal is equal to 2 again so add it to the list and increment current now current is pointing here current dot val is equal to 1 added to the list and increment current now current is pointing to null so we end the iteration and we got all the elements into the list now we have the list in the same order as the nodes inside the link list now we declare two pointers to check for parallel Row the first pointer I'm going to name it left so left will be pointing at the beginning of the list and right pointer will be pointing at the end of the list now we check if the value at left write is equal or not yes they are equal so you would increment the left pointer and to decrement the right point now we again check if the value of left and right are equal yes they are equal so you decrement the right pointer and increment the left point so once left crosses right so left was beginning here and it's now here right was beginning here and it's now here so it means they crossed right so you can end the iteration so once they cross and you still didn't return false you can return true as the output so let's take another example inside the list if list contains elements like this left will be pointing here and right will be pointing here the value of left and right is not equal so you return false and it is not a palindrome now let's code it up in Java so this is the function given to us and we are given the head of a linked list the return type is Boolean so we have to return true or false so let's start off by doing a base check if head is equal to null then we return true because null can also be considered as parallel now let's create arraylist since the values inside the nodes are integers let's create a integer arraylist now let's create a current node and point it to the head of the linked list so with this current pointer we are going to access each node and insert it inside the list we created now we iterate until current does not reach the end of the linked list now in each iteration we are going to access the element at current and add it to the list dot add current.val current.val current.val and now we move the current pointer to the next node so current will point to current.next current.next current.next so this will happen for all the nodes present inside the head and now we have all the nodes as integers inside the list now we have to check if the integers inside the list is a parandrum number or not so let's declare the two pointers as I mentioned left will be pointing at the first integer and right will be pointing at the last integer at the end of the list and now until both the pointers meet this while loop will run so left should be less than right now we have to check if the integers at these two pointers are same or not so using the get method on the list let's get the element pointing at these two pointers so if the element at the left pointer is not equal to the element at the right point then you can return false so if you consider this is a list so this element is not equal to this element so if it is not same you can return false else you increment the left pointer from here to here and you decrement the right pointer from here to here so left plus and right minus and finally outside the while loop you can return true if it has not return false here it means that it is a palindrome number now let's try to run the code our test cases are running let's open the code there you have it our solution has been accepted so the time complexity of this approach is of n because we are doing a one pass to reach the end of the linked list and the space complexity is also often because we are using the RL list to solve this question that's it guys thank you for watching and I'll see you in the next video thank you
Palindrome Linked List
palindrome-linked-list
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_. **Example 1:** **Input:** head = \[1,2,2,1\] **Output:** true **Example 2:** **Input:** head = \[1,2\] **Output:** false **Constraints:** * The number of nodes in the list is in the range `[1, 105]`. * `0 <= Node.val <= 9` **Follow up:** Could you do it in `O(n)` time and `O(1)` space?
null
Linked List,Two Pointers,Stack,Recursion
Easy
9,125,206,2236
1,694
hey everybody this is larry this is me going over q1 of the weekly contest 220 on the last lead code uh reformat phone number so this one actually to be honest um i had some trouble with during the contest just because i know that my weak point is just making sure about the edge cases and not getting wrong answers so uh so to give me that support hit the like button the subscribe one join me on discord but now uh this is a yeezy ish problem it's just that you have to be careful right well it's easy to understand but it is you know implementation that's always going to be off by one if you're not careful and you rush it so i took my time to make sure that it was um right and yeah i'm gonna go over my code because i don't think this i think this conceptually is okay i did it in python so i you know again this is contest code maybe it's not something to you know maybe it's not the best way to learn to be honest but this is what i have during the contest i just want to be honest because um you know when i optimize for time you know code readability might not be the top thing so this allows me to replace the empty spaces and the dashes and remove them and then i just put them in an array and i take each number three at a time and then for me the thing that i notice is that if you take three numbers in a time if the only case that can come up is uh especially noticing the constraint that they're at least took two characters um in the number string or the two at least two digits in the number um then the only case where um the last secret the last chunk so the last chunk can only have you know mod three right which is technically zero one and two but if it's zero that means that the last thing is going to be three um if it's one we'll go over it and if it's two it's okay because of the rules that are given uh so we only have to look out for the case where the four extra digits which means that the last uh block of numbers is only has one digit then we have to take the last two box because then it's going to be three plus one for four and then just make them into blocks of two and that's basically what i did in a really ugly way you could probably come up with something better and i definitely feel you and you can observe that but uh in terms of complexity it's gonna be roughly the same maybe not uh because the way that i did is technically n squared because of um or this slicing and moving indexes if you're really careful with just like having pointers you know keeping track of the index that you're keeping track of and then removing them and adding them uh as you need then you can do this in linear time i didn't because again um during the contest i'm trying to solve for um as fast as possible right uh but yeah uh that's all i have with this problem uh let me know what you think let me know how you did during the contest uh share me share with me your code and you could stop it or you could watch me salvage during the contest next what why not oh i see oh okay so um okay this is annoying but so hmm so up that's not good oh whoops this is yes you got it wrong uh hey thanks for uh watching this video explaining the problem uh let me know what you think ask questions because then i can answer them preemptively or join the discord uh hit the like button the subscribe button as well that works and hopefully i'll see you again bye
Reformat Phone Number
make-sum-divisible-by-p
You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`. You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or fewer digits. The final digits are then grouped as follows: * 2 digits: A single block of length 2. * 3 digits: A single block of length 3. * 4 digits: Two blocks of length 2 each. The blocks are then joined by dashes. Notice that the reformatting process should **never** produce any blocks of length 1 and produce **at most** two blocks of length 2. Return _the phone number after formatting._ **Example 1:** **Input:** number = "1-23-45 6 " **Output:** "123-456 " **Explanation:** The digits are "123456 ". Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123 ". Step 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is "456 ". Joining the blocks gives "123-456 ". **Example 2:** **Input:** number = "123 4-567 " **Output:** "123-45-67 " **Explanation:** The digits are "1234567 ". Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123 ". Step 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are "45 " and "67 ". Joining the blocks gives "123-45-67 ". **Example 3:** **Input:** number = "123 4-5678 " **Output:** "123-456-78 " **Explanation:** The digits are "12345678 ". Step 1: The 1st block is "123 ". Step 2: The 2nd block is "456 ". Step 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is "78 ". Joining the blocks gives "123-456-78 ". **Constraints:** * `2 <= number.length <= 100` * `number` consists of digits and the characters `'-'` and `' '`. * There are at least **two** digits in `number`.
Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost index for every prefix sum % p.
Array,Hash Table,Prefix Sum
Medium
1016
73
so today we are looking at lead code number 73 it's a question called set matrix zeros okay so we have a m by n matrix and if an element is zero we want to set its entire row and inside entire column to zero and we want to do it in place so there are three different approaches to this you can see here in the follow-up a straightforward solution is follow-up a straightforward solution is follow-up a straightforward solution is probably a bad idea a simple improvement uses m plus n space but still not the best because you devise a constant space solution we can do a constant space solution but it's very complicated and it doesn't follow any pattern and i think that going through the trouble of trying to do the constant space solution is not going to really get you a great roi because you're probably not going to remember it if you ever see this again in an interview so i think the intuitive approach the middle approach is actually the best one on handling this uh this particular question okay so let's take a look at that um we're going to have our matrix here we have one we have zero and we want to get all these uh columns here to zero and all these on the row here to zero here you can see we have zero here we're going to have this column turned to zero and this row to zero and this column here to zero okay so let's take a look at how we can approach this in a more intuitive way so we have 1 101 1 okay so we're going to have a matrix here that's 1 and 1 0 and one okay and so the intuitive way to do this is if we create an auxiliary space in a result array and keep the addresses of where all the zeros are happening in our input matrix we can then go iterate over the matrix again and uh on that address and then just go ahead and use the helper function to create just to set all the rows and all the columns to zero at that respective address so what do i mean by that let's say we have our ad our rows here is going to be 0 1 2 columns here is going to be 0 1 2. we're going to iterate over this array and we're going to find the address of this 0 and put it in a result array okay we're going to set that to 1 and one okay this will be a row and this is going to be our column whoops okay and now what we're going to do is we're going to create a helper function and all it does is it just goes and sets whatever address we give it every single uh element in that row to zero and every single element in that column to zero okay so what do i mean by that let's say we go to one then we're gonna go and keep the row fixed okay so we'll keep this fixed and then we're gonna create an i variable and just go through all the columns and set them to zero okay we're going to go ahead and do one more iteration and we're going to go ahead and keep this column fixed okay and then we're going to set all the rows to 0. okay and so then our result is going to be what we need which is 1 0 and 1 0 1. all right so that's one way to do it what is our time and space complexity on this our space complexity would be m plus n because we have to create this result array here so we can abbreviate that to o of n on space okay and then our time complexity is going to be quadratic we're going to have to do a few passes but we're going to have to the length of the array we're going to have to do everything in that sub-array have to do everything in that sub-array have to do everything in that sub-array as well okay so we'll have n squared on time okay so let's go ahead and jump into the code so what we're going to have here is we're going to have a result or a zeros addresses and we'll set that to an empty array and now what we're going to do is iterate over our matrix and find with the addresses collect all the addresses where we have a zero so four let i equals or let me just do row column row equals zero row is less than okay and then we're going to do our inner loop here so we'll have let column equals zero column is less than all right and so now we just want to check at this particular cell do we have a zero so if it's zero then we just want to push that address into our xeros address all right so that's all we got to do for that and then what we're going to do is we're going to iterate over our zeros address and we are going to set zeros and we're gonna go ahead and put in um our row we can just create a separate variable let row equal let column is going to equal okay and then we just go ahead and put in our row and our column and our matrix okay so that's all we have to do in our main function and then we just want to create a helper function here and we're going to take in a row we're taking a column and we're going to take in our matrix okay and so now what do we want to just make two passes and keep the row and the column real or the column fixed and in our i variable we go and set all the zeros so and then so here what we want to do is we want to say our matrix at um we can keep the row fixed okay so if we keep the row fixed then our column i is going to equal zero set all that to zero okay and then here what we're going to do is let i equals 0 i is less than and then we just want to do matrix of i and column is going to equal 0. okay let's go ahead and run this and uh let's take a look here cannot set property of zero of undefined matrix of ic plus matrix of i and column um i believe we have to switch these around so we just want to do i here and then keep our column there and keep our row here and keep our eighth variable there we go okay so we'll do one more pass here see if we can get better time on it yeah there we go so it's not the most optimal solution but it's a good intuitive one and i think with this question you just want to step through everything make sure you get your variables right these matrices problems is really like stepping on a minefield there's just so many easy ways you can find bugs in this so you just want to make sure you really map out your variables map out whether you're on your row or your column and you can get through these pretty unscathed taking that approach so that is lead code number 73 set matrix zeros hope you enjoyed it and i will see you all on the next one
Set Matrix Zeroes
set-matrix-zeroes
Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s. You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm). **Example 1:** **Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\] **Example 2:** **Input:** matrix = \[\[0,1,2,0\],\[3,4,5,2\],\[1,3,1,5\]\] **Output:** \[\[0,0,0,0\],\[0,4,5,0\],\[0,3,1,0\]\] **Constraints:** * `m == matrix.length` * `n == matrix[0].length` * `1 <= m, n <= 200` * `-231 <= matrix[i][j] <= 231 - 1` **Follow up:** * A straightforward solution using `O(mn)` space is probably a bad idea. * A simple improvement uses `O(m + n)` space, but still not the best solution. * Could you devise a constant space solution?
If any cell of the matrix has a zero we can record its row and column number using additional memory. But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker? There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
Array,Hash Table,Matrix
Medium
289,2244,2259,2314
1,399
hey Aaron how's it going today we will be looking at this problem that is called count largest group and all the problem really asks you to do is that given an integer n each number from one to n is grouped according to the sum of its digits and you have to return how many groups have the largest size so all this problem is really asking you to do is just list all the numbers from 1 to n and group all those numbers depending upon the sum of the individual villains so for example they've given you here that if n is equal to 13 you'll have to list all the numbers from 1 to 13 and then group all those numbers based on their sum of the digits so all the groups that you will get they've also listed on the groups that you will get which are 1 comma 10 because the sum of the digits of 1 as 1 and the sum of the digits of 10 as one as well similarly you have 2 and 11 so the sum of the digits is 2 because 1 plus 1 is equal to 2 and the to itself is also equal to 2 then you have 3 and 12 because the sum of digits of 3 is 3 and the sum of digits of 12 is 1 plus 2 which is 3 and so on they've just grouped all of these numbers according to their sum of the digits and you see that the groups with the largest size are 1 comma 10 2 comma 11 3 comma 12 and 4 comma 13 and you have to return the number of groups that have the largest size so that's what you have to return the total number of groups that have the maximum possible size right so this problem is pretty easy to implement all you really need to do is maintain a counter for each of the possible sum of digits you might encounter so for example you have to maintain a counter for the times that you get the sum of digits as one for all the times that you get the sum of digits as 2 3 4 and so on so for that we also need to know that how many possible sums do we have and how many possible sums are possible when we add up the digits for that you need to look at the constraints once you see that the constraints are from 1 to 10 to the power 4 that n can range from 1 to 10 to the power 4 and in this range the minimum sum that is possible is obviously 1 and the maximum as possible would be when you get the number nine right because the range is still one folder for zeros so the maximum number that you can actually get by adding up the digits in this range is when you encounter four times nine because that will sum up to the number 36 right nine plus nine that ends up being 36 so you need to maintain a counter for all the numbers from 1 to 36 because these are all the possible comes that you will encounter right so the first thing I need to do is create a vector which will maintain all the counts for each of these or digit sums so I'll create an integer vector and I'll call that count and the size will be 37 by 37 because this will allow indices ranging from 0 to 36 right and the highest thumb that we can get is 36 right so we create this vector now we will just iterate through all the possible numbers that we might encounter so I will just go from 4 and I equal to 1 from 1 till n so I smaller than equal to n plus I and I'll just increment the count of each of the digit sums that I encounter in each of the numbers so you'll need another function to find that digit sums let's say we call this function big sum and we'll pass in the current number that we're looking at to that function this function will return the sum of the digits of that number and we increment the corresponding count in the count array right so we'll just do that and we need to define that is its sum function as well so all we need to do is simply define an integer function we'll call this the sum will accept an integer parameter and we define a variable called in some and we'll initialize that to 0 now this is a pretty easy problem to find the sum of the digits all you really need to do is open up a while loop while n is not equal to 0 just add the last digit of that number to the some variable so to get the last digit you will just do n more 10:00 right and to remove that last more 10:00 right and to remove that last more 10:00 right and to remove that last digit from this number because we move on to the next digit after this all we're going to do is divide n by 10 this will just keep adding all the digits to add values of all the digits to this sum variable and in the end all we really need to do is return there's some right so once you've done that you will have maintained a count for how many times each digit sum actually occurred and that will be present inside your count vector now we need to find which digit sum occurred the maximum number of times because that will mean that the most number of elements occurred in that particular digit sum category for instance one if there was let's say for instance in this example when we had an equal to 13 the number the digits some one occurred twice so the count for big sum of four the count of one would be two because two numbers are good with that digit sum right so similarly we'll need to find the maximum number that is present in this town directive because that will represent the particular digit sum which would have occurred the maximum number of times so to do that we can run another for loop and find the maximum element it's a pretty easy thing to do but I'll just rather do it inside this single for loop itself so that we don't have to iterate again so I will just define and a variable called max size and I'll initialize that with 0 now I'll just keep checking if the current count is ever greater than the current max size so I'll just write max size equal to max of max size and I'll just get this inside this function like this and this will just maintain the count the largest sound that we ever encounter in the array while we are building that on itself right so once you've done that all you need to do is define what variable which will count the number of times the maximum size occurred so we'll create a variable called result or res and we'll just iterate to this count vector again and just see how many times the max is occurred so what you to do is simply donate like this for it I equal to 0 y is smaller than the second yeah but is smaller than count dot size plus I and you just every time that the count of I is equal to the max size that is every time you encounter a group with the maximum size you just have to increment your rest counter and finally just return the result right so that is how you will solve this problem let's submit this and see if it runs and it does takes four milliseconds and that is pretty good so this is how you solve this problem so if you enjoy this video hit the like button down below and subscribe to the channel for more such videos and I will see you in the next one you
Count Largest Group
page-recommendations
You are given an integer `n`. Each number from `1` to `n` is grouped according to the sum of its digits. Return _the number of groups that have the largest size_. **Example 1:** **Input:** n = 13 **Output:** 4 **Explanation:** There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13: \[1,10\], \[2,11\], \[3,12\], \[4,13\], \[5\], \[6\], \[7\], \[8\], \[9\]. There are 4 groups with largest size. **Example 2:** **Input:** n = 2 **Output:** 2 **Explanation:** There are 2 groups \[1\], \[2\] of size 1. **Constraints:** * `1 <= n <= 104`
null
Database
Medium
2046,2097
349
Hello everyone welcome to my channel code story with mike so today we are going to do video number 27 of our lead code easy playlist, it is easy but it is a very good practice problem, we made it approachable and to a great extent from yesterday's question. Similar is lead code number 349 is easy marked by Microsoft and un asked this question you will be given two numbers, one numbers to return n are of the intersection means to return whatever is common in both but you will send the result in that. You have to keep all the elements unique, it is okay and you can send the result in any order. Look here, what are the common elements in numbers one and numbers two? One is two here and same here also two is one element. Common has come, here also there is a two, one more element has come common, so this is the intersection of these two, but we have to return unique elements, so we will send only one two, so our answer is this, okay. It is quite a simple approach and if seen, we already have approachability two in our mind. You will search whether it is here or not. If it is right, then you put two in the answer. Okay, then you see, now I have come here. Earlier it was here, now I have come. Came here, did you see that two are present here? Yes, two are present here, so you put two here, but you saw that both of them are duplicates, so you have to keep only one, then you can either do this or make a set. Keep putting the result in it because what happens in a set is that all the elements are stored unique, so look here I came here, I got two in this number one, so what I did was I created a set and put this result in it. Then I came here and then I searched 'to', then I searched 'to', then I searched 'to', then I put 'to' again, but only unique put 'to' again, but only unique put 'to' again, but only unique elements are stored in the set, so 'to' elements are stored in the set, so 'to' elements are stored in the set, so 'to' will be there only once, then I will put it in a result vector and return it, okay. But you notice one thing, what you are doing here is that you come to the element here and you are hitting this search here, okay so you are hitting search, so you are going to hit that linear search, okay, either you are sorting it into binary. You will hit search, but the worst case will be that you will hit linear search. Okay, so what is better than hitting linear search is that you should store it in some data structure where you can quickly check. Okay, where you can quickly check. You can check whether that element is present here or not, otherwise what will you do? Put numbers one in a set, right, you have put it in a separate set, let's name it ST, and in numbers one, you have put one, two, that's it. Only one and two will come, because look, duplicate elements do not come, so one came once, O came once, okay, now it will be very easy, in numbers two, you will go to each element and see whether yes brother is present or not. There is o off and in st1. You can do unordered set if you see that this two is present in it. So remember I had made another set, let's name it A2 in which I will keep adding the results, I will get two. If I went to 'to', will keep adding the results, I will get two. If I went to 'to', will keep adding the results, I will get two. If I went to 'to', I have added 'to', now my eye pointer has I have added 'to', now my eye pointer has I have added 'to', now my eye pointer has come here, is 'to' present in this set, yes, it is present in this set, then in come here, is 'to' present in this set, yes, it is present in this set, then in come here, is 'to' present in this set, yes, it is present in this set, then in my result, when I have added 'to' in the result my result, when I have added 'to' in the result my result, when I have added 'to' in the result set, then it is set, then only unique elements will remain added, only 'to' will remain. Only two is left, now only 'to' will remain. Only two is left, now only 'to' will remain. Only two is left, now I will put it in a vector and return it. Okay, so what we have done is that we have used two sets, we have put numbers one in one set so that we can quickly access it and find any element. Was it present in this numbers one or not and to avoid duplicate results in numbers two and the results we were bringing from numbers two, one more set was taken, so what did we do with the space complex o of m + n m if complex o of m + n m if complex o of m + n m if its length and its length if n was ok then what will happen in the worst case off m space we will take ok and you are competing for time right till now it is clear this is done our approach one now let's come to approach two now see Coming to approach two, see what I am saying in approach two, remember, we have put all the elements of numbers one in one set, right A1, in this set we have put all the elements of numbers one and two here. Both the unique elements will come in set one, why was it inserted because in numbers two, when we were checking all the elements one by one, we could check in over time whether they are present or not. It is ok in numbers one, but remember. For example, let us assume that if the eighth element of numbers two was present in A1, then we used to put the elements of numbers two in a separate set so that the unique elements are maintained because look, a two came here and then when i came again. This two is present here. A again we add two, that's why we had created a set. Okay, then I put this set in the result. But now there is no need to create another set. See, you can avoid it. Yes, look at that, how, let's say the current i is here that you checked whether this two is present here, did you see in set one, yes is present, then in your result, this time we took only the vector which is my result vector in that you This two has been added, okay now you will want it in the future, if two comes again, then you do not want to add, then what will you do, remove this two from this set one, so that in the future, you will never get this match. Not only me because look now this is mine, when I will move ahead here then I will see, okay is this two present in this set and not present, so I will not add it, okay, so here my answer is directly in the result. The answer has come, we do not need another set, so this time our space was taken a little space complex, we took o of m only to store the element of numbers one and yes further, you can also optimize it so that Whichever one has smaller size, put its elements in the set. Put the one whose size is smaller in the set so that fewer elements go in the set, but it is okay, it is not that big an optimization, but we have done one thing here. Instead of taking a set, now we are taking only one set. Okay, for time completion, you have to visit all the elements once or the other. There is still off m + n, we have saved a little space, still off m + n, we have saved a little space, still off m + n, we have saved a little space, okay now let's come to the fourth and better approach. Now look, we come to approach three and approach three. I will not say that it is better than approach two but it is an alternative approach. Remember. What was your main issue that you used to go to every element in numbers two and you had to search here in numbers one so to optimize that search remember we had used set ok now I am saying I am sure that you can also do this, how can you make its search better, what can you do for binary search by applying binary search, you can sort it, okay, so now if you sort it, what will happen? 1 2 Now you don't do anything, now you come here, you have a tena that is there two present in numbers one, then why do you hit binary search now, because brother it is sorted, now you hit binary search, so what is the reason for binary search? You will be able to find in the log of Is to present? Is it to present? Here we did binary search and found to but we have taken set here so to will not be added again. Now we will put this set in the vector named result and return to this. Will do, okay, it is clear till now look, now I am repeating the same thing again, as you noticed, now you have done binary search on this big one, it means you have sorted this big one, then you are doing one more optimization. You can do this by checking in the beginning which one is bigger. If number one is bigger or number two is bigger then sort the one which is smaller or not. Sort the one which is smaller. Neither and searching will be done faster in it because it is of small size, so this is a slight optimization, you can do it, okay, not a big deal but the main thing, what I had to tell you is that you can sort it, binary search is also applied here. You can do it, okay, if it is clear till now, then pay attention to its time complex. You are going to each element of n. Okay, and you are hitting binary search on numbers one. n * l of m. Okay, so this is n * l of m. Okay, so this is n * l of m. Okay, so this is its time complex. It is done but remember in the beginning you had sorted it too, then what will appear different, isn't this the overall time completion? What has to be done, you have to find the elements which are equal in both, you have to find the equal elements and then select the unique ones from them. If you want to select and put it in your result then why don't you sort it, see what will be the benefit if you sort both of them. One A 1 2 This first number one is mine and I have also sorted the number two. If given then Tomato is done, okay now look pay attention, here you can do it like this also, look, there is a way that you can apply binary search which I told you in approach three itself that you chose this one and binary in it. Hit search, okay, why because you had sorted it, but another advantage of sorting both is that you can use two point to pointers, I is here, J is here, now pay attention to one thing. Yesterday's question is similar to the one which was given yesterday, it was the same question which was on common value. I am doing exactly the same thing. Is the value with i pointer and zth pointer equal? Obviously, if you increase j then there will be no benefit because the elements may be bigger in the future because it is two, after that two can come, or three can come, or four can come, or five can come, then one. Can't match anyway, right because it is sorted so only bigger elements will come after two or equal element will come then one can't match at all so we should keep two and move one aa pointer then i Let me move forward here because hopefully two may match here somewhere, so let's see the eighth element and jet are not equal yet, a is still not equal, so which is smaller, the eighth value, this one is smaller. Okay, so I should increase A because it is possible that J might get a match and go ahead of someone. Okay, now look, A and J are equal. Okay, now both are equal, so we took one set in the result set and added two to it. Okay, now look, pay attention, since these two are sorted, now let's go by the value, do this, make this example bigger, this is A and take the value of 8 here, okay, look now, pay attention, Namas I and Namas are equal. You have also put two in the answer, good, now think for yourself, if it is sorted, then duplicate elements will be right around it, so skip it, look at it here. Nums 1 of i = Nums of 1 of i + 1. Is it look at it here. Nums 1 of i = Nums of 1 of i + 1. Is it look at it here. Nums 1 of i = Nums of 1 of i + 1. Is it yes? Move i forward. Okay, in similar numbers also move j forward because both j and j + 1 are equal. You have to because both j and j + 1 are equal. You have to insert some duplicate elements, so you put j here. Okay, so what will be the benefit to you from this? Now you will not need to use set because you are rejecting the duplicate element with the two pointer itself because it is sorted. Duplicate elements are shown to you, let's say you were here, you are shown duplicate elements, next one. You hit skip and you moved ahead. Okay, so now the 'j' has come here Okay, so now the 'j' has come here Okay, so now the 'j' has come here and remember in our result we had added 'to' and remember in our result we had added 'to' and remember in our result we had added 'to' when for the first time this 'i' and this 'j' matched, so when for the first time this 'i' and this 'j' matched, so when for the first time this 'i' and this 'j' matched, so I saw that i + 1 If both th I saw that i + 1 If both th I saw that i + 1 If both th value and th value are equal then I have moved i forward. j + if th value and then I have moved i forward. j + if th value and then I have moved i forward. j + if th value and j value both are equal then I have moved j forward also. Now let's see again whether i is the second value i.e. it is the second value of i. It is equal, no, it is second value i.e. it is the second value of i. It is equal, no, it is second value i.e. it is the second value of i. It is equal, no, it is not equal, no problem, okay, so what does it mean that till now my entire to was there, no problem, now if we come to the next element, i will come in front, similarly, j and j are equal. Is not equal, what does it mean that till here the value was two were duplicate elements. Now j will come next here. Okay, now let's see if i and j elements are equal. Yes is equal, so what we did is put 8 here. Now come. I will move ahead, I has moved ahead, J has moved ahead, okay, out of bounds, our answer has come here, okay, this is exactly the code of yesterday's problem, isn't it, as it is, you can paste that also, we have just given some Didn't sort both of them, are there duplicate elements? We have put the unique elements which are duplicate elements here in our result. Okay, it is quite simple, so its time is complete, think for yourself what will happen, see, at least once in all the com elements. If you have to visit then it will be of m + n visit then it will be of m + n visit then it will be of m + n plus if you have sorted both then o of m l m p o of n l n ok and what is the space complexity, you have not taken any extra space, you have taken it for the result, you have to take that. Take, I am excluding that extra space, if you have not taken anything then of course I am saying space complexity. Let's code this quickly but it was simple but try making small improvements like this. Such problems are very good for multiple approachability problems. It is easy, don't ignore such questions. It is good for your practice. The more you practice, the more you will become comfortable, the more confidence you will get. Code quickly and finish. So let's first finish approach one quickly. What did I tell you? We will put all the elements of number one in a set in an unordered set so that I can search it as quickly as possible at one time. Let's name it A1 and only yesterday I taught you how to search all the elements at once. If you want to enter then you can also enter like this, there is no need to follow, all the elements from start numbers one to end of numbers one will go in this set. Okay and I had created another set because I want to store unique results in it. Tha is ok for int and nam in nums two means nums two ke Now I will go to all the elements and see whether that nam is present or not in my av me ok if A1 find nam is not equal to A1 and means that we are in nums one. Only if it was present, if it is present in av then make A2 insert moist. Okay, and A2 is an unordered set, so only unique elements will be inserted in it. Okay, now what will I do, I will create a result vector of int. Okay, I will insert the elements of A2 in it. There is A2 and A2, you can put it in such a shortcut also, make a return region, either make it A2 or you can also put it in such a shortcut that put all the elements of A2 from beginning to end in the result and this is the result. It has been inserted, let's see after submitting it, after that we will come to its approach number two. Okay, it has been submitted. Now let's come to its approach number two. Look at approach number two. What did I tell you that ST One Numbers One K? Put all the elements in set one. Okay but you don't need to take another set. Right and why is there no need because see as soon as I got that number in A1 then what I did is I will put it in the result. Look result dot push underscore. I have put that number back but I will also erase it and erase it so that if I get a name again in the future, if I get the same number in numbers two, then I will not find it in one and if I don't get it then I will not add it again. Okay, so I will directly input the result here in the result and return it here. Okay, let's run it and see, we should be able to pass the cases, what's wrong, result dot push back, good result, we did not define it. Vector of int Result Let's C After this, we will come to our third approach, this is also passed, now let's come to its third approach, so what I taught you in the third approach, what we will do is to sort the first one. Why will we sort because I search the element in the first array only, so I will be able to do binary search, if I sort then we have sorted numbers one and as soon as for int and number in numbers two, whatever element in numbers two I Found through binary search. Binary search in this, what to find in numbers of one, who to find this number, who to find in numbers of one, who to find this number, if found, what will I do, an undo so that I can store unique element in it, unorder set, an integer set in it. I will insert add insert nam, I will not do anything else in the last, I will take a vector result, I will put all the elements of this set in it from the beginning till the end, ok, I will return the result in the last, now just want to write binary search, then binary search. So yesterday I had taught you what the meaning of binary is, it is quite simple that I will give you an integer and in it I will give a target which you have to search, so look at the same code, I am copying and pasting, here I have written binary search, passed the number. Target passed and simple binary search code is if found then I will return true if not found then I will return false as simple as that is ok so let's run it and see if we are able to pass all the test cases indeed Yes, let's submit and see, after this we will come to our two pointer approach. Okay, indeed, yes. Look, this too has passed. Okay, now let's come to our last approach. We have solved a lot of things here and solved it in many ways. Okay, so what we did in the last approach was to sort both of them, right, sort numbers two and numbers one also, after that nothing is simple, you take a pointer int a e 0 int j = 0 I will point to which Nums 0 int j = 0 I will point to which Nums 0 int j = 0 I will point to which Nums one, J will point to Nums two Okay, take a vector of ints in which you will keep adding the result and find out the size of both Int m Inums d Size Int n Inums t Dot size is fine, now the same code as yesterday, let's take a and j take a. Okay, now look, pay attention if the i element of numbers one is equal to the jth element of numbers two, it means that we have to add it to the result. Ok result of aa sorry result dr push under back put numbers one of aa or put numbers two of j if both the elements are equal then put them then put i+p and j+p then i+p and j+p then i+p and j+p then you will do but do not duplicate element again. How will we avoid that? I had told that we will keep increasing i until we get duplicates, meaning numbers and off aa, if numbers of and off come equal to i + 1, off aa, if numbers of and off come equal to i + 1, off aa, if numbers of and off come equal to i + 1, then we will keep doing i pps here, similarly numbers two off. If numbers two of j is equal to pw, then here we will do jps plus, then we will deal with the duplicate elements here itself, we will right skip them and why are we able to do this because both of ours are sorted, we have sorted both of them and yes j. If you are accessing pw here then check that ale m should be equal and j lesson m should be mive or it will be out of bounds. Here you are checking pw is ok and if both are not equal then Check this which is smaller else if numbers one of aa if smaller is found out of numbers off two of j then yes i is plus i will do plus and I have explained to you why we will do that also if numbers 2 of j is smaller then j p We will do ps right and in the end we will return nothing, here the return is ok and here look at what a small mistake I have done, j &lt; n - 1, it was what a small mistake I have done, j &lt; n - 1, it was what a small mistake I have done, j &lt; n - 1, it was ok, here I had just written m, here n I did more numbers. 2j = = numbers 2j here n I did more numbers. 2j = = numbers 2j here n I did more numbers. 2j = = numbers 2j + 1, here I have written numbers one by mistake. + 1, here I have written numbers one by mistake. + 1, here I have written numbers one by mistake. Okay, after submitting, we should be able to pass all the test cases. Let's see if there is any doubt in the comment section. Try to help you out. See you next video thank you
Intersection of Two Arrays
intersection-of-two-arrays
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**. **Example 1:** **Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\] **Output:** \[2\] **Example 2:** **Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\] **Output:** \[9,4\] **Explanation:** \[4,9\] is also accepted. **Constraints:** * `1 <= nums1.length, nums2.length <= 1000` * `0 <= nums1[i], nums2[i] <= 1000`
null
Array,Hash Table,Two Pointers,Binary Search,Sorting
Easy
350,1149,1392,2190,2282
965
hello welcome to my channel i'm here to do my 100 lego challenge now today we have leeco 965 unit valued binary tree so a binary tree is unique value if every node in the tree has the same value return true if and only if the given tree is unit value now it's really uh intuitive looking at this chart there's only one value in this tree and here that this node is fine so it's false and think about this question is i will use a helper function that take in this original root node and the root dot value so the value and the root note and compare if the null value equal to the root nodes value and that will bring that value down to recursive function of every letter node to compare the node to the value of the root that's it for this question let's see now we have let's build the helper function first that will return boolean and we take in a node and also a value so if the no equal to no at that time will return true so if no dot value equal to no oh sorry equal to value that we put in then we'll return oh sorry it's not equal to so we eliminated cases first if that's not equal so return false so now it's not done yet so we need to check the bottom for the left and right so what we can do as you a recursive helper function of no dot left and also checking left nodes equal to the values and also the right node have to be true too in the same value of a recursion function so this is a help function what we can take in is return root oh sorry help a function root we put in the root node and also root dot value to compare all the value is true or not usually in this case we will have to check root is equal to no or not if equal to no then we turn true but yeah we see here's all done let's take a look now it pass the case submit it okay 100 pass and yeah that's it for this question so if you have any doubt question please let me know and i will explain as soon as possible um then i will see you in the next video bye
Univalued Binary Tree
unique-email-addresses
A binary tree is **uni-valued** if every node in the tree has the same value. Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._ **Example 1:** **Input:** root = \[1,1,1,1,1,null,1\] **Output:** true **Example 2:** **Input:** root = \[2,2,2,5,2\] **Output:** false **Constraints:** * The number of nodes in the tree is in the range `[1, 100]`. * `0 <= Node.val < 100`
null
Array,Hash Table,String
Easy
null
324
yo what's going on guys uh today we're gonna take a look at question number 324 wiggle sword 2. so let's uh first make sure that we understand the question we are given an Integrity nums and the question requires us to reorder it such that the zeroth index smaller than the first index and first and next is bigger than the second index and then it's smaller than a turtle next so basically it says that um the greater sign or the smaller than sign changes in every index and it says that we may assume that this nons array that we are given as always and a well dancer so first intuition that comes to mind is that what if we sold it the number and then since it wants us to First get a small number and then a big number and a small number again and a big number again we can always take the numbers from the beginning and the end of the third array so that they're guaranteed to be small and guaranteed to be big so that's the first intuition and actually let's try that in example two let's first get sorry and sorted so yeah this is the sorted array so we're gonna put our markers in the beginning and in the end first we're gonna take a small number that means we're going to take it from the beginning one and move this marker here then we're gonna take a big number from this marker there three and move it here then we're gonna take one move it there and take three hold it here we're going to take two and we're gonna take the other two so as you can see our approach worked quite well in the beginning like these are in the correct order but in the end it made a mistake and uh the mistake here is that the question wants us to reorder them such that numbers next to each other are greater than the other number or smaller than the other number but they cannot be equal to each other so that's the problem here with this approach now how to fix this what we can do is begin the left marker from the beginning and the end marker from the middle of the source array so the intuition behind this is like you can see when we have these duplicate numbers in the middle we don't want them to getting to the answer the end array next to each other so we're gonna take one of them first and then the other through the end so that will help us overcome this problem so then let's take a look at another example and this example is going to be four five six so let's take a look at this one with our new approach left pointer begins here right pointer begins here first we put four then we put five and move those here then we put five and then we put six as you can see this approach did not work and we have two of the same numbers in the middle and actually way to solve this is to ensure one of those numbers in the middle goes into the beginning so the correct way to solve this problem would be five six four and five as you can see the duplicate number in the middle goes in the first place and the way that we can actually ensure this is happening so start the left pointer in the middle and move to the left and right pointer in the end and move to the left again the way this works is as we first the number we put on the answer first is going to be from the left pointer and we want to lift and we have the left pointer pointed one of the duplicate numbers in the middle so this ensures that we put onto the numbers as the first place in our render array so let's try this approach with our example again four five six left pointer rules here right pointer goes here firstly take one from the left pointer and move left five that I take from the right pointer or left six let me take this one for let me take this one five and this approach worked well in this example as you can see and turns out that this is the uh actual solution to this problem so we don't have to worry about anything else and one thing that I'm gonna mention before getting into the coding Parts is that let's take a look at the constraints so the length of the numbers can be quite big as because 10 to the power of 4 times 5. so this approach as you can remember first regardless as the sort the array and normally that would take and Logan time if you use the default sorting algorithms of our program languages but as you can see the numbers in this array are restrained to be bigger than 0 and smaller than 5000. so actually there is another algorithm sorting algorithm that we can use to speed up our sorting quite a lot and it is count it is called Counting sorts which will take one time let's get to calling hey guys so let's get into coding first thing we will do is to apply the counting sort algorithm sort sorry the way we're gonna do it is create account array which is all zeros 5001 times and then we're gonna exactly count these numbers that are in this nums array we're going to increase the count of that number by one and then we're going to create a new array that is sorted an empty array and then for each number this is in our country we're gonna append uh the frequency I mean the number of times that it occurred in numbers lumps uh we're gonna find that many of that number in our source array so the way to do it is uh foreign range blank counts we're gonna depend into the source array exactly the number of times that number appeared in this laundry so let's what we're gonna do 4G in range counts I simple number of times that I appeared in lumps we're gonna append it to sword notes I okay so now we have sorted our numbers which is now in Sword numbers so the next thing we're gonna do is create the two indices which is the left one and the right one is obviously going to be starting at the end of the array minus one then left one is going to be starting at playing sort items divided by two but actually it turns out that this only yields the correct index half of the time so what we're gonna do is do this uh length of the array minus one divide by two and this is gonna give us correct index then what we're gonna do is um modify and I'm sorry index by index so let's say 4i in range loans if the index were currently at is an even one then we're gonna have to choose a small number therefore William choose from the left index so let's write it if I is divisible by 2 and we're gonna put num's eye as sort of Thumbs left and then we're gonna decrease the left point for one and we're gonna do the opposite thing if the index is odd alarms I so it comes right and then again we're gonna decrease right I won and actually it turns out that this is all the code we need to write let's copy and paste this into our vehicles run it yes and submit it now and yeah it worked pretty well I don't know why it's this long now so last time I tried it was much faster than that one see yeah the last time I tried it's it beat it 92 percent of the other codes but now it says only 44.7 I don't know why but 44.7 I don't know why but 44.7 I don't know why but I think this is as efficient as you can get and there we go that's how we solve this problem thanks for watching and I'll catch you guys next time
Wiggle Sort II
wiggle-sort-ii
Given an integer array `nums`, reorder it such that `nums[0] < nums[1] > nums[2] < nums[3]...`. You may assume the input array always has a valid answer. **Example 1:** **Input:** nums = \[1,5,1,1,6,4\] **Output:** \[1,6,1,5,1,4\] **Explanation:** \[1,4,1,5,1,6\] is also accepted. **Example 2:** **Input:** nums = \[1,3,2,2,3,1\] **Output:** \[2,3,1,3,1,2\] **Constraints:** * `1 <= nums.length <= 5 * 104` * `0 <= nums[i] <= 5000` * It is guaranteed that there will be an answer for the given input `nums`. **Follow Up:** Can you do it in `O(n)` time and/or **in-place** with `O(1)` extra space?
null
Array,Divide and Conquer,Sorting,Quickselect
Medium
75,215,280,2085
279
in this video we're going to take a look at a legal problem called perfect squares so um basically we're given an integer n return the least number of perfect square numbers that sum to n so in this case you can see we have a so perfect square is an integer that is a square of an integer so in other words uh it is the product of some integer with itself right so for example 1 4 9 16 they're all perfect squares because you can see here one right in this case one times one is one right two or in this case four is two times two right that's a perfect square and we also have nine and nine is three times three right and we also have 16 which is a 4 times 4 which is a perfect square right but 3 and 11 they're not because in this case you can see we if we have 1 times or 3 times 1 right in this case it's not a perfect square right same thing for 11 as well so in this case we want to find the least number of perfect squares that add up to n right so in this case let's say n is equal to 12 in this case the least number of squares that we can add is basically four plus four which is three right so in this case we have three uh perfect squares that add up to uh 12 which is the least number of perfect squares numbers right we can of course we can have like 12 is equal to like 1 plus 1 right dot we can also have like you know 4 plus 8 but 8 is not a perfect square right we can also perhaps have like four plus nine right so that's 13 so that's bigger than 12 so that's not gonna work so in this case we can also have like four plus one right so there are a bunch of ones but in this case the minimum right the minimum uh perfect squares that we can add up to 12 is basically three right we can have four plus four so that's basically the shortest uh so that's what we're going to return which is 3 right and then let's say if we have 13 which is the example that we just looked at right so for example 13 if n is equal to 13 we have you know like usual we have one plus one dot the dot right we can also have like four plus four which would give us 12 plus one that will give us 13. or in this case another way we can do is we can basically have uh four plus nine right this will give us 13 which is basically the minimum number of square values that add up to n which is you know in this case it's just going to two it's gonna be two right um so in this case you can see uh the constraints is that n is between 1 to 10 to the power 4 right so in this case how can we solve this problem so to solve this problem we know that uh in this case we have to try with all the combinations right like let's say if n is like equal to 13 in this case we want to see okay well let's try with all the square numbers maybe like we just like how we did it in the integer break problem right maybe we can try to you know decrease the n by one or by four right we can try was decrease you know dfs by decreasing 13 by four or by one but nine right by 16 in this case we realize that 16 is bigger than 13 so we don't do that right so what we do is maybe we can you know dfs right like for example for our first dfs function like maybe we can have like a function right we want to figure out the minimum uh square values right so in this case what we can do is we can have like maybe one plus fn 12 right we can do that we can also do for example uh you know four right four plus fn of cert fn of nine right and we can also have in this case uh let's see we can also have 9 right plus fn of 4 right so in this case here is minus 4 here is minus 9 here's minus one right we can try with all those you know path that we can go down to and then for function nine right in this case we wanna get the total num perfect squares for uh make up to nine right the minimum perfect squares to make us to make up the sum for nine in this case we can also have like you know minus one we can have like one plus f n of eight right we can also have um in this case we can also have let's see four right we can also have like minus four so four plus fn five right or we can also have like minus nine like we can have like nine plus fn of zero and we know that f of zero is going to be what is going to be zero right because in this case we pretty much at the bottom of our recursion stack so we can say that safe to say that these ones they're not gonna work because here we have one because the minimum number to make up uh you know for uh square or in this case if n is nine the minimum number to make up this value is just one right because it's just not itself so maybe we can just backtrack to this function right in this case you can see of course we will also have a cache as we go right of course like we will cache the value right in this case you can see function nine this will give us one right the minimum number to make up nine right is one right it's just the minimum is just one and then for the minimum for making this value we know that four plus nine is going to be thirteen so there's only two values so one plus you know the extra four there so it's two values so we're going to return back you know two right there's the minimum uh perfect squares to make up this thirteen is two of course we also have to do a dfs down to this path as you can see for example maybe like one plus fn of 11 right or one or maybe like four plus uh fn of eight right so you can see we have to do a dfs all the path but in this case you can see like maybe eight or maybe four it was already computed before then maybe we can use some kind of dp caching to cache this right so that's what we're gonna do is we basically gonna cache the data as we go right if we already compute four right if we already uh know what's the minimum right minimum number of uh what's the minimum number of uh square values to add up to n now we're current in right if we can be able to cache this as we go we can basically improve the time complexity right so you can see here this is basically how we did it we bought a top-down approach that i did we bought a top-down approach that i did we bought a top-down approach that i did and you can see here this is our cache is equal to new integer n plus one we do a dfs to figure out what's the minimum you know minimum uh right the minimum perfect square numbers that sum to n right in this case what we're going to do is that this is our base case if n is equal to zero we just return zero if it's not if it's already cached before we can just return a cache value otherwise what we're going to do is we're going to calculate it right in this case you can see i is equal to one right so i times i is less than or equal to n right so we starting from one uh we work in our way uh in this case if i times i right is less than or equal to n then we're going to continue right so 2 times 2 right 3 times 3 4 times 4 and so on and so forth right so in this case we're basically just going to loop through for each and every single iteration we're going to see what's the minimum number of you know what's the minimum number of perfect squares that you know add up to n right so what we're going to do is that is either going to be you know max value that we have so far or it's going to be you know we're going to do a dfs function try to figure out you know what's the perfect number of squares for you know for this right if we can be able to get the minimum number of perfect squares for this plus one if it's smaller than what we have so far then we then in this case the minimum number of perfect squares going to be you know what we have here right so we're going to continue to iterate through try with all the combinations um cache the value as we go and then at the end we're just going to cache the value for you know current uh n right and then we're going to return that and then back to the main function that's what we're going to return at the end so you can see this will give us a time complexity right of n times uh square root of n right because in this case you can see we're iterating uh square root n number of times right we what let's if n is let's say is equal to 12 uh so we're going to have one four right so in this case we have one we have four we have nine right we have uh the next iteration is going to be 16 but 16 is bigger than 12. so you can see that the this iteration right here is basically just going to be in uh in square root of power of n sorry square root of n right and then we also have to you know do this iteration right try to find the uh try to find all that single each and every single value right and cache that so that will also you know from one to n so that will be uh n times square root of n right so that's going to be the time complexity and then space complexity is basically just going to be uh big of n right so that's the top down approach and then the bottom approach basically what we're going to do is we're going to work from the bottom to the top right so you can see here we're starting defining our base case right if it's 0 it's going to be zero and then we're going to iterate from 1 to n and then basically for each and every single iteration we're going to say cash at num is the max value and we're going to try with all the single combination right we're starting at one num is equal to one and what we do is that if i times i is equal to you know num we're going to continue right we're going to try with each and every single combination right if num is one then what's gonna happen is we're gonna say num one minus one right we already cached that so if it's zero is zero right plus one so we're basically saying we're trying to retrieve the computer value and we use that computer value to compare you know what's up with the current uh you know the minimum number of square perfect square values right to make up the current value right so that's what we're basically trying to do and the time complexity here is basically just going to be linear right and then here you can see clearly that the time complexity here is basically linear right we go from 1 to n and then here we're going from in this case it's going to be square root of n right so it's going to time complexity is going to be n times square root of n and then space complexity is also going to be big o of n so there you have it and thank you for watching
Perfect Squares
perfect-squares
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`. A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not. **Example 1:** **Input:** n = 12 **Output:** 3 **Explanation:** 12 = 4 + 4 + 4. **Example 2:** **Input:** n = 13 **Output:** 2 **Explanation:** 13 = 4 + 9. **Constraints:** * `1 <= n <= 104`
null
Math,Dynamic Programming,Breadth-First Search
Medium
204,264
1,018
yeahyeah Hi Hi Hi everyone, I'm a programmer. Today I'll introduce to you a math problem with the following pronouns. The binary prefix can be divided by 5. What problem do we have? The details as follows give us an array of large integers a including only the numbers 0 and 1. We consider n at final position y with y at final position y as a sub-array from A minor zero to a sub-array from A minor zero to a sub-array from A minor zero to A What y represents is a pool of numbers in a binary representation. Our task is to return a list of Polish logical arguments so or phone is a piece or phone is called answer A and under the condition that he is afraid at the final position y is Chu If and only if n at the final position kill the y can be divisible by 5 Question We will go into example one to better understand the requirements of the question lesson for example one We have three have a version A consisting of three integers 011 Now we will start to find its n's, first we have n00 then we will calculate n0t automatically to see if there is anyone When there is only one number N 0 which is 0 then we have N1 then we will meet N0 and N1 i.e. n a at N1 then we will meet N0 and N1 i.e. n a at N1 then we will meet N0 and N1 i.e. n a at position Not to A at position 1 which is 01 this is n1 and N2 will be a at position no one Find the 1st position and a at the 2nd position which happens to be 011 Okay so we have these three binary numbers which are equivalent to N0 n1 and N2 now we will change three If this binary number becomes three numbers in the decimal system, it will be 0, 1 and 3 respectively. We see nothing for 5, so in the return table we have the first value at Nth zero which is Cycle 10 is divisible by 5, so the value at N1 in the given table is phone 3, which is not divisible by 5, so we return the value of Phone at position N2 so the resulting piece is Chu for. Phone generation is similar, you can do for example 2, example 3 and example 4, we also find N0 N1 N2. Then we check each of these debtors in turn and divide even by 520. If paying for 5, then position N does not give you the position I woke up in the results table, it will be Chu. If it is not divisible, it will be phone similarly for example Khoa and example 4 only you think you guys Having grasped the requirements of this problem, now I will enter the part of thinking about the algorithm to solve the problem. The algorithm for this problem is quite simple. We will have a loop when we will have a The loop has a cursor y starting from the first position of the array going to the last position of the end and we have a way to calculate O the number at position à The binary number at final position y We convert the number to decimal form with the formula: suppose we the formula: suppose we the formula: suppose we have the number 0111 as in example one, then we want to convert these numbers from the binary system to the decimal system. We change from left to right, we change from left to right, not from right to left, so how do we pour it? We just need to take it, we just need to take it without creating a good cause and then we Let's add to get a set. Let's solve this cluster again. Then we add weight to one, then we're sure it will come out that not adding 1 is 11 + powder but two is two. Two plus one not adding 1 is 11 + powder but two is two. Two plus one not adding 1 is 11 + powder but two is two. Two plus one is equal. You see, every time like that, we will have a birth cake. I called and read the birth change, then I will add ginseng and fig for the two things plus the position at A consciousness to multiply fig for If the two objects are added to A at the position of let it be zero then we will have let's say at the final position y then we will have the decimal value of it will be the sum but two and plus A at the previous position go They Yes then the You can apply this formula to some other cases such as example 2 and example 3, then this formula will be accurate. Now I will install these programs in this language. In programming Gold, first I will declare a variable that includes the piece of bulan, then I will return the variable from veg and now I will proceed to review and record the video. I don't know if it was born the day before. No, then turn on the bridge and declare a loop to set up Y when starting from zero when smaller than the led of a big ha and then y + y skip the increase by 1 unit and then y + y skip the increase by 1 unit and then y + y skip the increase by 1 unit and then as we said we will recalculate This sum, that is, this yard will be the number representing the decimal fractions of the binary number at position A, then the tattoo will be equal to the sum multiplied or added to a, y Yes. Then we We will have a variable with zezo. Understand what I'm saying. Let's check if this yard is divisible by 5 or not. If it's divisible by 5, then say he puts you in Chu and the one he doesn't dare give you five, you say Panda. phone, let's try to test this solution with example 1 a hot. You see, we have successfully solved. For example, a returned result is Chu phone, then this sum the first time it is run will be this time y = 0 then this sum will be equal to zero y = 1 then = 0 then this sum will be equal to zero y = 1 then = 0 then this sum will be equal to zero y = 1 then sum will be equal to 1 and y = 2 then Sun will be equal to 3 sum will be equal to 1 and y = 2 then Sun will be equal to 3 sum will be equal to 1 and y = 2 then Sun will be equal to 3 equivalent to this in line with the results we did in this example Now I will try very little to solve the remaining examples, we have an error here so I can see if this chain is quite long to infer very large Tao pulses or I will try to check it. How big will our fig grow? I will output it to the screen and show 2 cars, where will our fig grow? Hi hi Duong we see it's our fig, you see the ginseng at the end. Hey, we see what negative numbers it has and why the reason people have ultrasound, you notice, is because the power of our formulas is always multiplication and addition, all of which is what we add at the moment. Everything is positive and increasing, but why is there a negative number? Being negative means it has been exceeded. The limits of the numbers are that I used the PIN tiger number which is a 32 bit integer and it has been exceeded. The number of Spades has just exceeded the number of bits 32, so if it exceeds this, it becomes some random number. If the Spade number exceeds the number of bits, please pray for these formulas, it will no longer be correct. More precisely, now to solve the problem of such a large number, I will have a plant that I can reduce with children. Because the purpose is that I don't need this exact river. I just need to keep that odd part. So if I divide by this number 5, it's 220, so I'll reduce this pulse value to 10A. If I divide it by 10, I'll just take the odd part and I've reduced it. And in the number 10 times the decrease many times we just take this part, look at the bird and divide it by 10 then it will actually let me say hello to the year. Let me try to divide it by 5. I just took the previous part and divided it by 5. I'll just give the number here, but if I sum it up, it will always be small from 123 to 01234, so that's all it is, I won't. I'll come this spring and it's too big, so you can see it and solve it successfully. Suppose if I put the number 10, it will be fine. If the number is 10, then this sim can be 0123456789 to show everyone that it also runs successfully. So let me analyze a little about the complexity of the algorithm. This math won't take me all night. Let's call N the number of elements in array A, then its complexity will increase and the complexity of the storage space, I can only use this piece from here but Knowing this bride, it requires the problem, so we also have the complexity of the opponent's creation of the citizen, which is just one and this is the structure of Math learning, sorry, this doesn't have Math practice, it's onl their complexity. It's a waste of storage space, but I'd like to end the video here. If you think it's good, please give me a like, sub, like and share the experience. If you have any questions or comments, I'm happy to help you. Please write in the comment section below the video. Thank you all. Goodbye and see you again. Yes.
Binary Prefix Divisible By 5
largest-perimeter-triangle
You are given a binary array `nums` (**0-indexed**). We define `xi` as the number whose binary representation is the subarray `nums[0..i]` (from most-significant-bit to least-significant-bit). * For example, if `nums = [1,0,1]`, then `x0 = 1`, `x1 = 2`, and `x2 = 5`. Return _an array of booleans_ `answer` _where_ `answer[i]` _is_ `true` _if_ `xi` _is divisible by_ `5`. **Example 1:** **Input:** nums = \[0,1,1\] **Output:** \[true,false,false\] **Explanation:** The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. Only the first number is divisible by 5, so answer\[0\] is true. **Example 2:** **Input:** nums = \[1,1,1\] **Output:** \[false,false,false\] **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`.
null
Array,Math,Greedy,Sorting
Easy
830
1,637
hi guys subi I hope that you guys are doing good uh you'll see widest vertical area between two points containing no points so it has been as by Microsoft not pretty much but yeah we can see the problem itself it just says that we have n points on a 2d plane and where every point is just given two coordinates x i comma Yi I have to return the widest vertical area now what this widest vertical area by them means is and for sure why is vertical area between two points because we have given n points a vertical area is an area fixed between the like of a fixed width extending infinitely along the Y AIS as you can see if I have two points so it's a vertical area between them but we want the widest vertical area is the one with the maximum width the one who has this as the maximum withd between the points although I can extend it infinitely in the length like in the y a axis but in the width it should be maximum possible so ultimately if I can just imagine this as with a few points itself so let's imagine I have these points so infinitely I can move them up so there is no point to make the vertical bar but the only thing which I want is what is the distance between these points what is the distance between this point and this point now shall I take this as a distance no I should not pick because I want the width maximum width is between this and this point if I extend this down then it will be the width okay I can just check the width between this point and what about this and this yeah if you go and check the width between these two points then it will be zero so I can just go and have like this width between the next two points and the width between these points so out of all these points which will give me the maximum width that will be the answer that will be the length which I wanted because ultimately I just wanted to return the widest vertical area that's it and which is the vertical why veral area is the one with the maximum width I just have to return that if you go in the example itself we have this all these as you can see are having one as div width so the answer is one itself cool uh so we'll just do one thing we have all these points we go on to all the points we know that if the point is this I let's say x comma Y and other point is x2a Y2 so I just know I just have to subtract X2 minus X1 to get this specific bid withd between X1 y1 and X2 Y2 and that's the only thing which I wanted so I'll just go andate on all of my points and get the answer and there's nothing which we did uh we just only wanted to get the width between every two consecutive points again we want consecutive points so first we will have to sort the points so what we will do is we will just um sort the points uh dot begin uh points. end now uh we want the maximum width which is the answer for us so I'll iterate on all of my points uh points do size and also i++ points uh points do size and also i++ points uh points do size and also i++ now I'll just say points is equal answer equal to maximum of answer of points of I minus points of IUS one but that's a coordinate so I just wanted only the zero which is the only X I wanted a difference of and then ultimately I can return my answer which is the answer which I want let's quickly see if you have not done any mistakes and now we can submit it so with this the time complexity of this will be as we are sorting because we want the difference between consecutive points and it is already not sorted so time complexity as you can see will be o of n login because of sting nothing much and space as we are not using any extra space but we are sorting and sorting internally takes a space of log in so the space will be o of log n but for python like for C++ in of log n but for python like for C++ in of log n but for python like for C++ in Java it will be login for python it will be o of n cool bye-bye
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
1,663
so lead code 1663 smallest string with a given numeric value so we defined the numeric value of a character as its position in the alphabet the numeric value of a string is just the sum of its character's numeric value and then you're given n and k two integers you need to return the lexicographically smallest string with the length of n and a numeric value of k so between amongst all of the strings that obey these constraints so the length needs to be n and the numeric value is to be k you need to return the one that is lexicographically smallest and what does it mean to be lexicographically smallest smaller than another string here you have the definition but the first part is completely useless in this problem because the length is fixed so there can never be a prefix of another string because to be a prefix of another string you need to have a length of less than the other string and here all of the strings have the same length so then the only thing that we care about is given the first position where we are different and we must be different because otherwise we are equal right and then we are not lexicographically smaller obviously so if in the first position where we differ if we come before if the character there is before in the alphabet then the other strings character then we are lexicographically smaller so what this is telling you is that you want all of the characters that are bigger that are later on in the alphabet you want to have them at the end because for example if instead of having a y we had something like y a then we could swap around those two characters so that y ends up at the end and that would be lexicographically smaller so yeah you just want to have all of the characters that come first in the alphabet you want to have them to the left of the string and then all the other characters to the right okay so the way i like to think about this problem is because we know the length that we need to return is start with something that you know is good and then work from there so we know that we like letters that come first in the alphabet for example if n is three and k is three then it's obvious that the solution is just a right so it's clear that we like a's and we especially like them at the start of our string right for example here in this pro in this example here n is three k is 27 we choose to put two a's at the beginning and then we have a leftover of 25 and so we just put that at the end okay so let's just start with an array of three a's and then work from there right because we know that the length is three and we like a's a lot so just fill an array with all a characters like this right start with an array of length n and fill it with the character a and now since you filled the array with the character a every a that you put is a numeric value of one so if before you needed like 27 then now you only need 24 more right we do not need 27 now because we have three a's already so we only need 24 more to reach the budget let's say right so remove from k the amount of a's that you've put in the array okay now we're going to start from the end of the array so we work from the back of our array and so we have our index that starts at the last position in our array and then we have a while loop that keeps going while k is greater than zero so when k reaches zero or even goes below zero we can stop already because we have nothing more to do because our array has been prepared for that okay so now what you can do is you can set the result at the current index and then after setting it you just want to decrement i so you can do it real quick here in one line or otherwise if you prefer you can put the i minus after it doesn't really matter so what do you want to assign to the position i in the result array you want to assign a number such that you decrees k the most possible right so for example if you can place a z then that's the best character that you can place because placing a z means that you have to replace less a's and having to replace less a's means that you'll end up with a string that has more a's and you want the most amount of a's possible so z is the best character for that so if k is greater than 25 then we want to place a z but if it is for example 16 then we just want to consume it obviously we cannot place a z because then we would go in the negative with k right like our numeric value would be too big and we can't do that obviously okay so what we can do is we can set the value at res of i to be the string from the character code and the base value is the character code at a right that's just our current value and then we add to that the minimum between 25 and k so this means that if k is greater than 25 then this is going to result in 25 but if k is for example like 16 then this is going to result in 16 which is exactly what we want if we have enough to make a z then we make a z otherwise we do not and we make the biggest character that we can make which is just k the character code from a's character code plus k which is the leftover that we have right perfect and yeah that's kind of it you just now need to remember to remove 25 from your budget this is like your numeric value budget once you finish this budget you're you can't do anything more so your job is finished right and the reason for which we always remove 25 is because this is either 25 this either results in 25 and so it's the correct value or if it's if it results in k then we don't really care we can just uh remove 25 because it's gonna be less than or equal to zero in the next iteration anyway so the value of k is not gonna matter really right and yeah at the end you just uh now you've assigned all of the correct values to your result array and so now you can just return the result joined and don't forget to put two empty apostrophes here or join will put commas between your characters okay and that's it the solution has o of n time complexity and o of one extra space complexity obviously we need oauth and space complexity for the string the result itself but i would say that's not a consumption of space it's just that the result needs o of n space so we use of one extra space right okay so that's it for me today thank you for watching and bye
Smallest String With A Given Numeric Value
detect-cycles-in-2d-grid
The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on. The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string `"abe "` is equal to `1 + 2 + 5 = 8`. You are given two integers `n` and `k`. Return _the **lexicographically smallest string** with **length** equal to `n` and **numeric value** equal to `k`._ Note that a string `x` is lexicographically smaller than string `y` if `x` comes before `y` in dictionary order, that is, either `x` is a prefix of `y`, or if `i` is the first position such that `x[i] != y[i]`, then `x[i]` comes before `y[i]` in alphabetic order. **Example 1:** **Input:** n = 3, k = 27 **Output:** "aay " **Explanation:** The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3. **Example 2:** **Input:** n = 5, k = 73 **Output:** "aaszz " **Constraints:** * `1 <= n <= 105` * `n <= k <= 26 * n`
Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
null
976
solving liquid problem number 976 largest parameter triangle so um what does a triangle mean by definition in a triangle the sum of two sides must always be greater than the other side for any sides of the triangle so if we have a triangle of side A B and C then the sum of sides a plus b is always greater than C sum of sides B plus C is always greater than a and some of sides a plus c is always greater than b so that is what we will be doing to see if it's a triangle or not and what is largest pyramid to mean largest Spirit meter means that all the three sides of the triangles are the largest one possible so um let's see here we are given two one two so these are only three of those so what does uh are these do they make a triangle uh two one and two so yeah two plus two is greater than one two plus one is greater than one and again two plus one is also greater than one so this is our triangle what if we have something like three four and a six so three plus four it's greater than six great is it Greater no it's not it's less than six so this will not make a triangle um but again here if we check um o plus um six it's greater than three right and I'll also um three plus six it's still greater than four but only shaking for uh keeping the largest one at one side and the second two largest are taking the sum of those we can know like if it would make a triangle or not so that is what we are going to do here so we are given nums and we know it's not sorted or at least it's not given in the question that it's certain so we will sort the Norms in a descending order from largest to smallest and then we'll perform our evaluation on if it is a triangle or not so sorting our array in a descending order now four numps um so for each of the values in nums we check the this condition so if nums I if okay so we need an I here okay so we only check for this one if this it's true then we return our parameter by adding all of the sides if not if for all of these if we did not even find our triangle so this will be until less than equals to 3. then return zero thanks for watching
Largest Perimeter Triangle
minimum-area-rectangle
Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`. **Example 1:** **Input:** nums = \[2,1,2\] **Output:** 5 **Explanation:** You can form a triangle with three side lengths: 1, 2, and 2. **Example 2:** **Input:** nums = \[1,2,1,10\] **Output:** 0 **Explanation:** You cannot use the side lengths 1, 1, and 2 to form a triangle. You cannot use the side lengths 1, 1, and 10 to form a triangle. You cannot use the side lengths 1, 2, and 10 to form a triangle. As we cannot use any three side lengths to form a triangle of non-zero area, we return 0. **Constraints:** * `3 <= nums.length <= 104` * `1 <= nums[i] <= 106`
null
Array,Hash Table,Math,Geometry,Sorting
Medium
null
328
Hello Various Welcome to the Second World Family Don't Turn On Paul Actress Time of Today's Question is Audible Inclination Meaning of All the Best Point in a Trader to Something on Point in a Trader to Something on Point in a Trader to Something on 10 Lines and Will Update It And Even It In It Movie World Recording Path Selfie Corner Keshav International Limited Update Old Steven Andar Update Old Steven Andar Update Old Steven Andar Update And Die Titu And Simply In Update And Die Titu And Simply In Update And Die Titu And Simply In Case What It Is Not Equal To In It Will It Dot dot expected time complexity of bubble sort complexity of things needed by
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
83
trust me nobody likes duplicates they cause so much redundancy and take up your so much disk space as well and they provide very little extra information correct so finding duplicates in any data structure becomes a very practical problem and that is why it is asked by so many tech companies so what can you do about it let's find it out Hello friends welcome back to my Channel first I will explain you the problem statement and we look at some sample test cases going forward we will try to come up with a Brute Force solution and see some of its limitations after that we will also come up with an efficient solution and then do dryer of the code so that you can understand and visualize how all of this is actually working in action without further Ado let's get started let us try to understand the problem statement first however if you're new to linked lists I would recommend you to go over my introductory video on linked list first in this problem you are given the input linked list that is sorted and it has some duplicate elements so if you see a link list we have the element one then we have the element 2 which is repeated next you have the element 3 and once again you have the element 4 which is repeated again note that this list is sorted so all of these repeating elements would occur one after the other right now what you need to do is you need to return me a new list that does not have any duplicates that means all the duplicates should exist only once so in my output list I have the elements 1 then 2 which is repeated only once then three and then the element 4 and then ultimately null so you can see that the size of your linked list could change is no elements are repeated then the size of your output linked list would be the same right however if you have a case something like this in this case you can see that the element 3 is repeated throughout so as per your output you would have only one node and this single node would be your answer now if you have understood the problem statement directly feel free to try it out on your own however if you are still facing difficulties let us dive into the solution a good developer always tries to come up with a Brute Force solution first that is because a Brute Force solution can guarantee you if a solution to a problem even exists so let us say you are given with the sample linked list and you have to remove duplicates from it you can see that the element 2 is duplicated over here and the element 4 is duplicated over here you need to find a way that in your output list you do not have any duplicates so what you can think of one way you can start to approach this problem is by using a set data structure the specialty of a set is that it will only have unique elements so what you can do is you can start iterating over this linked list and keep on adding all of these elements to a new set this new set will have only unique elements let me show you what I mean so starting with the first element I create my set I add the element one next I see the element 2 right this does not exist in the set so I add the element 2. then I see the element 2 again this exists in the set so we won't be doing anything once again we see the element two this still exists in the set so we just move ahead going forward we see the element three this does not exist in my set and hence 3 would be added to my set going forward I see the element 4 and I add it to my set then you have a 4 again this is duplicated so it won't be added to the set and ultimately we have the element files so this completes my set of all the unique elements right as a final step what you need to just do is use the elements of this set to create a new list so once I create a new list this would look something like so you see in our output list we have removed all the duplicates now this methods works perfectly and it will give you the correct solution but do you see the problem with this method if your link if is very large then it could be a case that you are creating a extra set of the same space so let us say you have a linked list of a thousand elements then there could be a case that you are creating a set of 800 elements so in a way you are wasting a lot of space so the space complexity of this solution turns out to be order of n and if you notice we never take any advantage of the fact that this is a linked list and it is also sorted to find an efficient solution let us try to take advantage of this fact how does that look let us have a look to come up with an efficient solution to this problem you need to take advantage of two factors number one that this is a linked list and in a linked list you can modify the pointers as per your wish right number two you need to take advantage of the fact that this list is already sorted that means that any of the duplicates that exist in the lift they would always be adjacent to each other right so keeping these two facts in mind we can come up with an efficient solution that can save us space and time as well I start off with my head value that is fine good right next what I will do is I will check my next file I see that my next value is 2 that is different from my previous value right so good enough I will advance my pointer one step ahead now I am at position number two once again we will check the next position I see that the next element 2 it is repeated we do not want to include that in a final list right so just skip this for a while move to the next pointer again I see two again which is pointing to my original value right and this value also matches so we will skip this value again I go on to my next value and I see the value 3. now this value is different from the value that I'm pointing to right so here we take advantage of the fact that this is the linked list I will remove this pointer what I will do is I will start a new pointer that starts from 2 and the next points at 3. so you see we have skipped some elements now two if taken care of that means I can advance my pointer to the next value now I am pointing at 3. I once again check the next value and this value is 4 right this is different from 3 that means once again I can advance my pointer I am now pointing at 4. check the next value again what is it the next value is 4 and it matches my original pointer correct hence we do not need to take it into consideration we can simply skip to the next value I see is 5. now 5 is different from the value that I am pointing to so once again I need to take advantage of linked list so I remove the next pointer from the node I am pointing to and I create a new link and now I can move my pointer to the value 5. the next of 5 is null and hence we need to stop now do you now feel that we have arrived at the solution let us have a look and we will try to iterate the lift from the starting position so starting from the head I see the value 1 right next I go on to my value 2. now when I will do a next I will go on to this path and I will see the value 3. next I see the value 4 and once again if I go on to my next PATH I will see the value 5 and then ultimately null so what just happened over here we didn't actually delete the values but the list we are returning has the pointer such that all the duplicates are now removed so now if someone will try to iterate over this list they will get the values 1 2 3 4 and 5. and hence you see we were able to remove all the duplicates from this sorted linked list now let us do a dry run of the code and see how this works in action on the left side of your screen you have the actual code to implement this solution and on the right we have a sample input test case that we will try to solve so we pass in the head pointer as a parameter to the function now this head pointer represents the entire link List Right Next what you do is you create a brief pointer that is pointing to head so brief pointer with point to head and over here we will see how print actually looks like and what happens over here so right now brief is pointing at head and it has the value 1 in it right going forward we also create a temporary variable and we point it to drift.next variable and we point it to drift.next variable and we point it to drift.next so that means m is pointing at 2. next you run a while loop now this while loop will run until we are at the end of the linked list correct do you remember how we were checking if it's a duplicate or not we were comparing it to the previous value and hence we called our pointer trip so what you do is you check if the value of temp is equal to the value of the previous node right now 1 is not equal to 2 that means what you simply do is you do a previous dot next equals to 10. that means I will create a next node to the previous and that will point to 2 right so it has 2 in it in the next step we point previous to the next node that is our temporary variable and we move M to our next value so now M will point at this next two this while loop will run again this time we check if m dot value equals previous dot value you see that previous is pointing at 2 and F is also pointing at 2. that means this is a duplicate and hence we just need to move ahead we don't have to do anything about it so I move my M pointer one step ahead and I do a continue this while loop will run again and this time my temp is pointing at the value 3. I check if temp dot value is equal to previous dot value no right that means we go over to our if section now we say that previous dot next equals to temp what this will do is previous.next Will point to our new previous.next Will point to our new previous.next Will point to our new value that is 10. so you can see how previous is forming a new list that is without duplicates once again we say previous equals to 10. so this will move the previous pointer to the next value and once again we move the temp to a new value and amp now moves to 4. this while loop runs again and this time we will add the value 4 to our left in one more iteration what will happen if we will again move our M value to the next pointer and previous will also point at 4. that means we are again encountering a duplicate we will again do a continuous statement and this Loop will eventually end so now we have reached the end of the linked list just as a sanitary measure what we will do is we will Mark the next of previous pointer To None such that if someone is traversing from the starting of the linked list they know that we have now reached the end of the list once all of this is done we will just return the head pointer do note that although you are returning the head pointer but what we have actually done is we have modified these original pointers so this pointer will now change and it will point to 3 and this pointer will now change and it will point to none so if someone will try to Traverse the list they will go like one two then 3 then 4 and then ultimately the time complexity of this solution is order of n and the space complexity of this solution is order of one that is because we do not create any new data structure we are just modifying the actual pointers of the link list I hope I was able to simplify the problem and its solution for you as per my final thoughts I just want to say that problems like these are very practical think about it if you're working in a very large organization where you have a lot of client data or a lot of logs indeed so what will you do you want to remove out all of these duplicates right so that you can look at the correct data duplicate data gives you wrong information as well right so interviewers will try to ask this question in a lot of different forms they will tell you that okay remove duplicate from this linked list remove duplicates from the SQL table remove duplicates from a binary tree because all of these are practical use cases so always keep these tips in mind and try to come up with a very efficient solution so while going through this video did you face any problems or have you seen any other problems which deal on duplicates tell me everything in the comment section below and it would be also helpful for anyone else who is watching this video as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also let me know what problems do you want me to follow next until then see ya
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,1,2\] **Output:** \[1,2\] **Example 2:** **Input:** head = \[1,1,2,3,3\] **Output:** \[1,2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List
Easy
82,1982
74
hey guys let's solve Le code 74 which is search a 2d Matrix so you're given an M byn integer Matrix and they're calling that Matrix and that has two different properties one each row is sorted in non-decreasing order so that's a way of non-decreasing order so that's a way of non-decreasing order so that's a way of saying it's increasing and there might be duplicates and the first integer of each row is greater than the last integer of the previous row so this is basically just a way of saying that it looks like this where it is increasing from left to right as we do this zigzag pattern down the array okay so given an integer Target we need to return true if the target is in The Matrix or false otherwise and you must write a solution in Big O of log of M * n if we say t is in Big O of log of M * n if we say t is in Big O of log of M * n if we say t is equal to M * n that's just the number of equal to M * n that's just the number of equal to M * n that's just the number of elements in The Matrix so it's Big O of log of T where T is the number of elements in The Matrix you need to make sure it runs in log time complexity okay so let's look at an example to make sure we understand given this Matrix right here which is represented by the 2D array the list of 1357 and the list of 101 1620 and 2330 34 60 we are looking for the target of three and we can see just from the picture that actually is in The Matrix so all we have to do is return true and in this example down here we have the same Matrix but we're looking for a target of 13 is not here where it should be is right here and we'll talk about that shortly but it's not there and so we just return false okay so I've just taken that same Matrix in the previous example and we'll say that the target we're looking for is 13 okay so that ultimately would return false because that doesn't exist now the easiest thing to do here is just forget about the fact that this is a 2d Matrix if we stretched it out into basically a long Vector these would be the different indices so if you flattened it out you'd have zero all the way up until the number of elements that we have minus one if we have m is the number of rows so that's equal to three and N is equal to the number of columns which is four we'd have I'll call it t is the total number of elements in The Matrix and so that is 3 * 4 which is equal to 12 so if that is 3 * 4 which is equal to 12 so if that is 3 * 4 which is equal to 12 so if we were to flatten it out we know the indices are just zero at the beginning up until the length minus 1 which is 12 - 1 which is 11 now we want to do a - 1 which is 11 now we want to do a - 1 which is 11 now we want to do a binary search and that's why I have kind of just written the indices like this these are not technically accurate for the Matrix it is accurate if you were to flatten it out and if you were to flatten it out doing a binary search is pretty easy if you haven't seen my video on binary search then you can check that out but here let's pretend for now that we could just do a binary search well what would we do well we'd start with a value L which is equal to zero the first thing we'd get a value R which is the last one so that is the length minus one which is 11 so we basically have an L here and an R over here and to get that log runtime we get the very clever M which is equal to l + r the integer which is equal to l + r the integer which is equal to l + r the integer division that by two that's how you get the middle and so in this example it would be 0 and 11 so that's just 11 integer division by two five rounded down which is just five so that's going to give you this number right here and since there's an even number of elements we have that the middle is kind of either two of these elements and we're going to get the left one so we have the index of five but we aren't able to access the actual value of this because this is a fake index okay this is just something we have in our mind where if they were flattened it out the index would be five but that's not what we need we actually need two indices we need its row index I and we also need its column index J well it turns out that given this index and these values over here we can actually deduce both the I and the J we can get the row and the column number from these three things how do we do that now these values are all row zero these are all Row one and these are all row two why is that the case well for 0 1 2 and three those all give a value of zero but then suddenly when we get to the value of four that is when four 5 6 and 7even those are all giving a value of one and then suddenly when we get to eight that is all giving a value of two so all of these are also giving a value of two now it turns out that if you take M which is really just our flattened index here and you do an integer division by the column number that is going to give you the row index okay so we'll write that as a formula here I the row index is m / n formula here I the row index is m / n formula here I the row index is m / n integer division take any example say that we took our five right here well we want that to give a value of one to get the row index of one if you have the M value of five and then we integer division that well we have four columns that is going to give one and something so we round down to get one if you were to take any of these examples here these would all give a value of zero if you were to take any of these those will all give you a value of two okay so that's the formula for the row index how do we get J well anything in this column is going to be zero anything in this will be one these will be twos and these will be threes and let me just kind of move that over here for a second it's really just m mod the number of columns n so if you took six for example well that we want to give a column index of two well that is the case if you take six and then you mod that by the number of columns that is going to give you the value of two so this is the formula for the row index and this is the formula for the column index so given an M we can get our row and column index and so we can get the value that we're actually trying to look at here that is simply The Matrix which I'll just call Matt here that is Matt at the row index I at the column index J and since we have index that value and we're actually implementing a traditional binary search here that's really all you have to do we just follow the same rules of binary search which is if you found what you're looking for in this case we would just end up returning true if we didn't find what we're looking for then we go to the right spot and I encourage you to watch the binary search video for that it's simply that if our value we're looking at is to small well then you would want to look in the right side if the value is too big you would want to look in the left side and we'll see in the code how to do that okay so let's write our code we' get M which is the number of rows we' get M which is the number of rows we' get M which is the number of rows that is equal to the length of The Matrix we would get n is equal to the number of columns which is the length of Matrix at zero is this actually guaranteed to be in bounds yes because M and N are both guaranteed to be at least one so if we access the first row and we get the number of values in it that is safe and it's going to be the number of columns that we have okay we'll get our value T which is simply the total number of elements in The Matrix that is going to be equal to M * n and then from that to be equal to M * n and then from that to be equal to M * n and then from that we can set up our binary search so we'll say l is equal to Z the position of the first element and R is the position of the last element which is T minus1 we're sticking with our flattened versions of the indexes and we'll just convert it inside of the while loop so in here we'll do while L is less than or equal to R we need the less than or equal to because we're saying while they haven't crisscrossed if we ever get to the point where Allen are crisscross then we couldn't find it so we'd return false and we do need the equals sign because we want to check when they are equal to each other we want to check the same element so while L is less than or equal to R we get our middle index m is equal to l + r integer division by 2 equal to l + r integer division by 2 equal to l + r integer division by 2 I'll get I which is the row index that is equal to M integer division by n and we get the column index J which is equal to M mod n and from there we're able to index and actually grab our value so we'll get I'll just call it the middle number the value at the middle index that is the Matrix at I and J then from here it's just the rules of binary search we have if the target is equal to the middle number that means we actually found it and therefore we'd return true if it wasn't well then we need to look in the right spot otherwise if the target is actually less than our middle number well that means our Target is to the left of where we're looking so we need to adjust our right index that means we want right to be m minus1 we search to the left side otherwise we want to search to the right side and that means setting L to be m + 1 that means setting L to be m + 1 that means setting L to be m + 1 that actually implements our binary search really the only difference is that to access our middle value we need to calculate our row and column index from that middle index we can access that and then we just do the normal binary search if we get out of here it means our L and R have crisscrossed as in we couldn't find the Target and we can return false if we were to run this we'll see that it works and zoomed out here is all of the code so complexities well the time complexity of this what are we doing we're doing a binary search that is over all of the elements and so that gives a log complexity of the number of elements there and that is equal to Big O of log of M * n or Big O of log of T and the of M * n or Big O of log of T and the of M * n or Big O of log of T and the space complexity here we're not really using any space here that is just a big O of one so constant space I think that's a really cool problem and a lot easier than it might seem drop a like if you found this helpful and have a great day guys bye-bye
Search a 2D Matrix
search-a-2d-matrix
You are given an `m x n` integer matrix `matrix` with the following two properties: * Each row is sorted in non-decreasing order. * The first integer of each row is greater than the last integer of the previous row. Given an integer `target`, return `true` _if_ `target` _is in_ `matrix` _or_ `false` _otherwise_. You must write a solution in `O(log(m * n))` time complexity. **Example 1:** **Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 3 **Output:** true **Example 2:** **Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 13 **Output:** false **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 100` * `-104 <= matrix[i][j], target <= 104`
null
Array,Binary Search,Matrix
Medium
240
152
hello everyone so today we will be doing lead code problem 142 that is maximum products are barry so we are given an integer array norms and we have to find a sub array that has got the largest product and we just have to return the product so here are few examples now let us try to understand the problem statement in mode depth we are given an integer array norms and we have to find the maximum products of array so we can do that by maintaining two variables that is maximum and minimum so in maximum we will store our maximum product for a sub array from its 0th to the current element now for the minimum we will keep the minimum product foreign from its 0th to the current now the logic to do this would be something like Let It Be we will hydrate through our array we will keep a tuple where we would check our current num like what whatever our number is like whatever the element is and we will keep our current Max multiplied by that number to keep a track of the maximum product and a current min into that number to keep a track of the minimum product now there must be a question that why do we need to keep track of the minimum product when the question is all about finding the maximum products of array now the reason behind this is in our array there must be some elements which can be negative so for those negative elements it is possible that the previous minimum possible product can turn the current product into a greater value for example if we see here like if we considered the sub array so it is 3 then it is minus 2 Let It Be we have got minus 6 as the minimum product and after that instead of 4 if we have got a minus 4 then what will happen our maximum can turn when we will multiply the like this minimum product if we multiply to our negative element then we will have a maximum product so it will turn something like 24 so if it were minus 4 this would have been our maximum product sub array so that is the reason why we need to maintain a current minimum where we will store our minimum products of array value so what we will do is after we have our Val we will check our current Max so that would be maximum of the Tuple Val like whatever like we will check uh that whatever out of these three like the current number or the current Max into this number or the current Min into this number like whichever is Max we will store that in our current Max in our current minimum whichever is minimum we will store it so that in the next iteration if we get a negative element that can turn uh into a positive greater value now in our result we will check the maximum of whatever we have in our current Max and itself of course and while this Loop ends we will just return our result now before this Loop we will initialize our current Max to 1 we will initialize current wind to 1 and we will initialize our result to Let It Be 0. so let's try out this and see how the dry run works so we will have a tuple for the first element that is 2 we will have 2 then current Max is our 1 so it will be 2 current Min will also be 2 so recurrent into our number current Max into a number will be 2 and 2. so this is the Tuple so for the current Max current maximum if we check the max of all these three values it Remains the Same current minimum it Remains the Same for result if we check our result of course it remains this like our result was zero so it will get updated to 2 because our current Max is greater so when we iterate uh through our second element now when we come here 3 what will happen our Val would be our value would be now it would be three now for the current ma now this is current Max into the present number if you do we would get six if you do current Min into the operation number we will get a 6. now what we will do we will see our current Max so it is the max of all these uh like it is a maximum of uh the value in our tuples so it will be six what will be our current Min it would be 3 because we are keeping the minimum value then if we check our result we will update it to 6 now because 6 is greater than 2. now if uh when we reach our third element that is my minus 2 then our balance minus 2 so we will do current Max into this number so it will be minus 12 now we will do current Min into this number so what will be current minimum into this number it will be minus 6 so we have got this Tuple now we will find our current Max so what is the maximum of all these three that is the number itself what is the minimum of all these three that would be minus 12. now as you can see that is the reason why we were maintaining the minimum value right so now we will check our result so our result would remain the same because minus 2 is smaller so it will remain the same now we have got two cases first case viewed be having the array that was given to us that is 2 3 minus 2 and 4. so 2 3 minus 2 and 4 we would also see one with two three minus 2 and let it be the array is minus 4. so we have reached till minus 2 now let's see in this case what will happen so our Val is now 4 now what will be our current Max into our present number that would be minus 8. now what would be our current min so that would be minus 12 into 4. would be minus 48 so this is something like when you reach the our end of the loop now let's find our current Max that would be 4 our current Min would be somewhere around minus 48. now our result will our result get updated no because 6 is still the greatest so we have found our output now this was asked in our lead code question so this part is done now this is an example which we are doing by ourselves to see what would be the maximum products of array so in this our Tuple would look something like minus 4 now our current Max was minus 2 so it would be plus like minus 4 into minus 2 so that would be plus 8 now if we do uh like minus 4 into our minimum like current minimum that we are maintaining now it has gone to somewhere around minus 12. so it would be plus 48 now like you can see here how that product turned into a larger value so this would be kind of like our maximum product we can already guess so when we see our current Max it is 48 right now out of all these three we have got 48 if we check our current minimum out of these three it is somewhere like minus 4 how did it how did the tables turn now if we see our result what would happen is the max we had was six now it is being updated to 48. now which should be our maximum product sub array it has now changed from like if it was the first question which is in our lead code so it was this but now our maximum product array has changed into this so this is how we would uh solve this question maximum products let's write up the code whatever we have understood so uh to start with we will check the length of our nums array so if it is equals to 1 then we will just return that element only whatever element is present and if not then let's write whatever we have understood so we will have two variables that is current Max and current minimum which would be representing the products of arrays then we will keep result as 0 now let's iterate through our array so for every number we will maintain a tuple which would have that number our current Max multiplied by that number to get the maximum products of array and our current min multiplied by that number for the minimum products of array now what we will do is we will update our current Max to the max value of any of the element present in this Tuple like we will check from these three which is the maximum value and we will update it to our current Max and in our current min we will update the minimum value from the Tuple so now we will just update our result to the maximum value of the result itself and between the current Max and we will be keep keeping on updating this after this we will just come out of the loop like we saw in the dry run and we will just return our result so for this the time complexity will be o of n as we are just looping through once so the test case has got accepted let us submit it yeah so that would be it for our maximum products or Barry and I'll see you in the next one thank you for watching
Maximum Product Subarray
maximum-product-subarray
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_. The test cases are generated so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[2,3,-2,4\] **Output:** 6 **Explanation:** \[2,3\] has the largest product 6. **Example 2:** **Input:** nums = \[-2,0,-1\] **Output:** 0 **Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray. **Constraints:** * `1 <= nums.length <= 2 * 104` * `-10 <= nums[i] <= 10` * The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
null
Array,Dynamic Programming
Medium
53,198,238,628,713
1,710
hey guys how's it going in this video i'm going to walk through this leeco 1710 maximum unit on the truck and this question was asked by amazon for 42 times in the past six months so it was quite popular in amazon interviews and luckily this question is kind of easy let's walk through so you are assigned to put some amount of boxes onto a one truck and even a two-dimensional array uh is even a two-dimensional array uh is even a two-dimensional array uh is called box type so the data looks like the first element is the number of boxes and the second element is the number of unique per box so uh we are also given a integer of truck size which is a maximum number of boxes that can be carried by the truck and we can choose any boxes to put on a truck as long as the number of boxes does not exceed the truck size and we need to return the maximum total number of units that can be put on a check so let's look at some example in here um we are given a data looks like this so it means uh we have one box of the first type which is this guy over here and that contains three units each box can contain three units okay and the second type is second type and if there's two boxes of the second type which is this guy over here and each box can contain two units and this is the third type okay so three boxes of the third type and each of the blocks can contain one unit and the truck size is four so the maximum unit that this truck can carry is equal to eight so the math works out to be the truck can finish all the boxes of the first and second types and one of the box in the third type so when the chalk comes in uh we always want to put on the box the boxes that contain the maximum the more units and by doing that we will make sure that the truck can carry the highest amount of units so and in this case uh the first type each box contains the three units which is the highest among the three that's why the truck can come in and pick up the first one first and then pick up the second one and the third one so uh one way to do this is to sort the data by number unit per box so um using a descending order so the chocolate will pick up that box first and then the second one and third one and that will work but it's kind of expensive because for each iteration for each of the tasks so we are guaranteed that we have to sort this list um so it's the time complexity is it must be n log n uh so a slightly optimized way to would be use a priority queue so in the case if there are more boxes than the chalk size we don't have to do and not get anymore and so the worst case is still the same in log game but in an average the um priority queue will be better than the um the sorting approach um i'm gonna export the party up sorting approach in this uh in this solution let's dive in so first we uh put all the box type uh into a um so basically we use the unit per box as a weight and because in python it's always a mean hip and to make it to turn around and make it a max heap we can put a negative sign in front of it so i call it a short weight so when we pop it off the one that has the highest unit of per box will comes out first because again i put a negative side in front of it and then i put it back with the box pipe by um by pushing the short weight it does the first element second element will be the same number of boxes and also the unit per box as before so essentially what i was doing in here is just i extract this information that allows me to sort it later on using the mean hip or uh now put a negative sign become a max heap and i use a uh hippie fly to uh to turn this list to be a heap while uh we still have room for the chalk and if there is some ball that can be put in on the chuck and then we heat pop the box types and this operation takes a bit of a lock in and if the available boxes is less than the chalk size and then we append the total number of units which is equal to the number of boxes times units per box to the answer and then now we put the box on the chart and then the available room will decrease by the number of boxes and else if the number of boxes is equal to the chalk size we append the number of boxes times the units per box to the answer and then we have to we don't have to do this while loop anymore because now the chart is four and then we just return the answer directly and else if the number of boxes available is more than the chuck so now the chart is full and we append the number the unit per box times the truck size to the running answer and again we don't have to do the right rest because the chuck is full and then we exit from the while loop and answer and then return the answer if the available boxes is less than the number for the number of available boxes less than the torque size this is where we will sorry this is the number of boxes is more than the truck size this is how we can we'll access this while loop and we will just directly and return the answer so let's run that to see how it works so as you can see uh it looks okay um i already analyzed the time complexity but i always just want to emphasize a little bit more so um the time complexity in the worst case scenario is a big over log n which is same as the sorting method but on average case we don't have to go through the entire box types if the chart size is bigger than the box types and we so in that case we don't have to go through the entire box types and this is where we can save some time compared to the uh the sorting method uh but this is talking about the worst case and also as a big over n so this is where we generate do some data manipulation in the box types so the sum of the two is still equal to the n log n which is the this is a dominated part and for space complexity vo and for the official solution actually we didn't use actual space in here i did everything in place so for me this solution is a little bit of one um yeah so this is so much uh in my solution i hope this is helpful if it is please like and subscribe and that would be a huge encouragement to uh for me to create future videos thank you so much for watching i will see you next video
Maximum Units on a Truck
find-servers-that-handled-most-number-of-requests
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`. Return _the **maximum** total number of **units** that can be put on the truck._ **Example 1:** **Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4 **Output:** 8 **Explanation:** There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8. **Example 2:** **Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10 **Output:** 91 **Constraints:** * `1 <= boxTypes.length <= 1000` * `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000` * `1 <= truckSize <= 106`
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
Array,Greedy,Heap (Priority Queue),Ordered Set
Hard
null
1,639
hmm hello guys so let's understand today question hi that uh see one two three four five six seven eight nine ten let's go hello guys so today we are going to understand you the question that we have is uh 1639 and this question has been asked in uh the topmost company like uh Microsoft Amazon and atlassian right so make sure that you will uh do Hands-On on this uh question okay so do Hands-On on this uh question okay so do Hands-On on this uh question okay so let's understand so we have given uh the statement that 1639 we have the question right so this is the liquid question we have 1639 number of P's to form a Target string given a dictionary right so you are given a list of what you have to do actually we have given number of uh we have a number of ways to form or Target string uh we have to from we have to form a Target string uh given a dictionary type so you are given a list of uh string of the same length right we have a given a list of string of the same length what and Target right string Target two things we have given your task is to form Target right we have to form a Target using the given words how like the target should be formed from left to right to form the eighth character of the target you can choose kit character of the j a string in the word and if the target of I equal to word of J and K once you use character of jth string you can no longer use the X character using the string right is less than x so in other words all characters to the left off or at the index K we come unusual for every string so we have to repeat the process until you form this target so notice that you use multiple characters from the same string in the word to provide it the condition that we are made and return the number of ways to form the target from words and since the answer may be too large right we have to take the modulus 10 to power 9 plus 7. so this is the word we have given these are the words we have given and Target we have given okay so let's understand how we'll do the implementation Okay so clean this one okay so coming back to here uh what are the things we have given here so there is a six way we can form the Target right how it is saying that uh first we uh what we are going to form that a b a right at index 0 what we have a b here right and no yeah and index B index one add here we also have B right here as you can see a is here B is here and index C that we have is a right a b a so this is the way we can form okay now similarly we have the another one in uh to form the ABA index 0 we can select a at index 2 we can select either one of these right and like this we will select so in this approach you will see we have six base how many ways six ways we have right so you can read these questions right explanations right so each way either of the given string guide word add some uh actually watts is nothing but our word what's is the string right here so each string will take an or a character at any of these slide correct right so uh each character right you can see it's a combination of string right so each string we will take and it sticks the character at that string and if the index is matching with the to forming the target we will say let's we can say that this is our ah B approach right now similarly we have this one right you can same thing we have it's not a big deal right as you can see we have to form b a b and we they have the string here given right so to make the ba we write the first what we will choose either we'll choose B so from b a b we will choose a b here and then uh we have index at B A we'll choose a and we'll choose uh b a b another one a from this one so we can form like this okay so total food approaches we have and that's why our output is 4. now what we have to understand we will use dynamic programming right that is called bottom of because if we have uh you can say n number of uh n is the number of elements in the word side if the words list is n number of words we have given right and M is nothing but our Target so if this is the length that we have of what's we have and M is the target length we have right and we can say k will K will be our length of a string that we have in the word right each word right in the words you can say so what we have to do if we will uh think that words we have given this words and words as a matrix containing n rows will take n rows and M sorry K column side K is the length of the word right that will take so this is our row and this is your column okay so the processing uh the process of Target processing ah thing how we will do that so the process of building Target is how we'll select this let's suppose give me one minute foreign okay so let's understand uh how we'll do the approach right so first of all the process of building the target is uh how we'll do that let's understand so we will itate over uh you can say we'll take a matrix right so we'll take uh we will it over Columns of a matrix from left to right will do and as we have here right so at each of them right we have two options to pick a character at the current column or to skip right other will select our will skip right okay so only two approaches we have Okay so let's understand first we will itate through here to here left to right and then we'll for each column right for each column you can say either will what we will do either will pick the character at the current column or what we will do either we'll skip okay so let's go to understand so first of all we have the this one column the First Column right ABC we have the data here so first we'll pick a because uh a is in the Target right as you can see so that's why we are we have to select this a because uh a is in the Target okay so we are taking as a now we will see uh that we will move to the next column and we'll check C B A right is it there right so if we have at this column then we will see yeah we have B right so we will select this B at this uh from this uh or you can say the index right and you will get the value now our we will form the Target because we are searching what B is now a is searched B search okay now the a we have to search right and we will Traverse to the next column right in the next column we'll check if a is there right so what we have seen we have a yes okay so in this way we'll try to form this you can say Target right and once we have our Target is ready we will uh we will store the you can say number of ways right so let's suppose we have uh here let's suppose what we are trying to see here so let's suppose we have a DP at I and J okay so DP of I and J is the uh you can say number of ways to build you can say the prefix of the Target right we have the we are building the you can say uh prefix right of prefix of Target okay and uh if we are using I and J that is uh our left most column that we will see later okay so how this will work and that how we're going to use right so first of all uh we know that if we are if we have right I and we are using J right so length is this is your length right this is your length for the uh Target right and J we will select our left most column that how we'll select that one right and that we will see okay so there are uh many means if J is our you can say column right then what we have to consider uh which uh character we are going to see okay so better let's go to the programming section and we'll do the implementation directly right so you will understand there okay let's go okay so we are here and we are going to do the implementation right so to do the implementation what we have to do first of all we have given uh what we have given and another we have given is Target right so first we'll take uh 26 Alpha Beta alphabet right so to get that alphabet let me check yeah in the full mode okay so first of all what we have given what's we have given and Target we have given so first we'll take int equal to uh I will take uh alphabet type so Alpha bits we have and this is about 26 letters okay and after this what we'll take we have given mode right to do find the mode what we want 10 to the power 9 plus 7 right 10 to the power like this where is that symbol 10 to the power 9 and plus 7 right we have given so either you will do this one or what you can do you can provide how many zeros right zero and uh I think it will come how many zero will come give me one second let me calculate it should come 10 to the power three and then we have to take three and nine right so 10 to the power 9 means nine zeros we have to take right so nine zero we have to take like this and then this side and then we'll do what plus seven so after doing the sum this will be convert 7 correct and then we will make like this yeah like this okay so 10 to the power 9 plus 7 we have right so we will take like this the mod right and after the Implement is right uh we'll uh if the value is coming more right we'll do the mode that's why we are taking okay now what we will take m is nothing whatever Target length our Target dot length will take and next what we have we'll take int K and K is nothing over what's of uh you can say one words right and for one Watts we'll take zero and we'll do length right and this is nothing but like this okay so we will have our M and K and we'll use one count to calculate all our number of ways right how we'll do that we'll take a uh you can say nothing but will take a current right and we'll store here right so I'll take our current and this current is nothing but our 2D array right and this 2D array will store what two things uh new int and it will take what first of all alphabet will take right alphabet let me cook it from here alphabet and another it will take what uh the another will take its uh value that is our we have is k okay I think you bought me next what we have to do we'll take uh we have to write it right over here 0 and J should go to its length that is K and G plus okay and after this what we will create we will make a for Loop and we'll say string W right string word is nothing but our words and from here what we'll do we have our current on the current what we will do we'll take what word and another will take uh what it's carrot overtight what's dot carrot Care at here and we'll pass what J and we'll do minus a to store its value and this is nothing whatever J and we'll do plus will increment each time okay so we'll store our current here value current value and we'll store all these values here okay now after completing this what we'll take a long and that is nothing but our DP this TP will take 2D array and this is nothing but our new and long we'll take m plus 1 and then K plus 1 this is our DP after forming this DP we'll take what DP at zero is nothing but our after forming this we'll go to uh i n j right so to go to will make for Loop and will Traverse in all I equal to 0 and I should be less than k and I plus okay now we'll go to four int J equal to 0 and J should be less than what k and J plus right then we'll do if I is less than m in that case what will happen DP at I Plus 1. and DP at J Plus 1. DP at I plus 1 and J plus 1 is nothing but what plus equal to current at V at what Target Dot carrot Target at will use um I write and we'll do what minus e okay you know this side and after making this we'll do J and we'll do star DP at I and J right now what we will do we'll do add I plus 1 J plus 1 I will take mod equal to mod right after this let me complete this one here and then we'll take DP at I J Plus 1. is what DP at I and J plus 1 is what will take plus equal to DP at what DP at I and J I guess right then we'll do DP at I plus d p at J plus 1 equal to what really again we have to move right so we'll do this mod after this be making mod we'll do return here right we'll complete this one then this one when then we'll return here return hint convert into int we put what DP add M and K now run it okay so understand what we are doing here right okay so first of all what we will do here we will declare uh our Matrix right we will declare our Matrix we will initialize it with zeros right and we'll itate over J we are what we are doing initialization right after initializing this we will take the The Matrix right and uh we initialize with all zeros and after that what we're doing here we will iterate J over uh from 0 to K minus 1 right we'll do and uh will aft while doing iterating we will itate word over words and will increment this uh value right uh when we are storing onto the Matrix side so the Matrix will store what uh word of CH I word of J and we'll do minus a right and we'll store uh at J right here so for each column we are getting our value and we are storing here right on the Matrix now we will declare a DP Matrix and this DB Matrix will initialize it with zeros right and will set DP at 0 and 0 is 1 because this is your base case of the DP right and then we'll itate I from 0 to M right so we are iterating from 0 to MH actually here okay so each time what will happen okay we are not streaming M it's K right so each time what will happen will iterate it with 0 to I equal to 0 to I should be less than equal to M right so let me do like this okay yeah so we'll start with i equal to 0 and I should we get a less than equal to M right will iterate like this will be iterating I from 0 to M and we'll itate J from 0 to K minus 1 right 0 to K minus 1 will itate right so once this iteration is uh happening at that time we will check if I is less than M right if I is less than M then what will happen here we will add uh we will add DPF I and J and we'll multiply this with this one right like this as you can see after once this is done right multiplying right we'll pick the character Target I and from the J jth column you can say so and will store the value right and if it is not happening right then if it is not less than M right then what we'll do we'll add on to the uh we'll add DPT I and J to D5 i j plus 1 we will escaping the column and we will moving to the next right so for only we have to check if I is less than M if it is I less than M then we'll store at this position right we will doing this one right we are selecting this target character we are stored in here right if not then we will move skip the column like this we'll do J2 J plus 1 from J we are going to J plus 1 and we in we are incrementing our you can say uh what we can say this column right so we'll here as you can see we are going to I plus 1 and J plus 1 but here we will only skipping a column so we'll day we'll say J plus 1 only okay and we'll return this one way to run this one is working fine so if we'll talk about the time complexity ah it will happen it will go to n into K and M into K right time complexity and this place is M into K only because see we are going uh we have our what we have we are we have having K and it is going to what's length right and similarly we are having uh here uh M and K right two times we are going so n into K and M into K will do we'll do the uh you can say complexity and for the space complexity we are storing onto here so we will take what M into K right M into Cube we are going right like this you can say okay thank you guys thank you for watching this video If you like this video please hit subscribe so that you will get more video like thank you so much for watching this one
Number of Ways to Form a Target String Given a Dictionary
friendly-movies-streamed-last-month
You are given a list of strings of the **same length** `words` and a string `target`. Your task is to form `target` using the given `words` under the following rules: * `target` should be formed from left to right. * To form the `ith` character (**0-indexed**) of `target`, you can choose the `kth` character of the `jth` string in `words` if `target[i] = words[j][k]`. * Once you use the `kth` character of the `jth` string of `words`, you **can no longer** use the `xth` character of any string in `words` where `x <= k`. In other words, all characters to the left of or at index `k` become unusuable for every string. * Repeat the process until you form the string `target`. **Notice** that you can use **multiple characters** from the **same string** in `words` provided the conditions above are met. Return _the number of ways to form `target` from `words`_. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** words = \[ "acca ", "bbbb ", "caca "\], target = "aba " **Output:** 6 **Explanation:** There are 6 ways to form target. "aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "caca ") "aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "caca ") "aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "acca ") "aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "acca ") "aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "acca ") "aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "caca ") **Example 2:** **Input:** words = \[ "abba ", "baab "\], target = "bab " **Output:** 4 **Explanation:** There are 4 ways to form target. "bab " -> index 0 ( "baab "), index 1 ( "baab "), index 2 ( "abba ") "bab " -> index 0 ( "baab "), index 1 ( "baab "), index 3 ( "baab ") "bab " -> index 0 ( "baab "), index 2 ( "baab "), index 3 ( "baab ") "bab " -> index 1 ( "abba "), index 2 ( "baab "), index 3 ( "baab ") **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 1000` * All strings in `words` have the same length. * `1 <= target.length <= 1000` * `words[i]` and `target` contain only lowercase English letters.
null
Database
Easy
null
3
hi my name is david today we're going to do number three longest substring without repeating characters we have a function here that takes an s and it wants us to return the length of the longest substring that doesn't repeat any characters so here we can see a substring is a b c and then there's a repeat so abc would be the longest substring it would be the substring here and that meant this three and then we keep going b c a and then it does a repeat so that length is three and then we keep doing that to find all the possible substrings that don't repeat and return the length of the longest one so there's a clever way of solving this problem and it's by using the sliding window technique where basically you have two pointers you have a left pointer that's going to keep track of the start of the substring where it doesn't repeat any characters and then the right pointer is going to iterate through s and then so the idea is that we're going to iterate through and then we're going to keep create a map that has the character and then the index value it occurs so here we have a and then we added a to our map and has an index of zero and then left for still our left point of zero and then b has an index of one and when we add it c has an index of two we add it and then here we see as a repeat and we save is within the left pointer so since this is a repeat within the starting left pointing we have we want to update this so we want to update it to the old one plus one so wherever where ever that unique character occurred before and we wanted to move that to the next one in this case would be b at index of one and then we're going to replace the map value with the index value at each iteration and also find the length of it then we're going to pair the length of it at each iteration compared to the longest one as a length of the outer loop and then we return that longest variable at the end so here first thing we want to create left pointer variable and assign it to 0 next we want to create longest length variable and assign it to zero now we want to create a map we'll create char map to keep track of characters and their index now we're going to loop through s with the right pointer and inside of this loop we can create a current char variable and that's going to be s index of right pointer and then we're going to compare that to the previous what we have in the map so create previous chart try index variable and that is going to be the chart map dot get current sure and the first time you do it's going to be undefined and that's going to be useful for our calculations so we know that we don't have to do the comparison the values so here we're going to compare the left pointer and the previous chart index if it's in there so if previous chart index is greater than or equal to left pointer so if it's within the left pointed range we want to update the left pointer to that previous chore index where it was before plus one and now if we don't have to update the left pointer regardless either way we update the chart map with current char and right pointer and we're going to have to find the length at each iteration and then we update longest of max current length and longest length and then after that we just return longest right so i know the logic is a little bit tricky but let's try to code it out so that left pointer equal to zero that longest length equal to zero cost char map equals new map now we loop through s for that and we can call it right pointer 0 right pointer rest in s dot length minus one right pointer plus now we can do cons current char equals s index or right pointer now we can do previous class previous chart index equals char map dot get current chart and now we're going to have to compare it if we see it before so if previous char index is greater than or equal to left pointer because if it's past it if it's left on the other side of it we already moved that left point so we don't include it so that's why we have to be greater than equal to we update the left pointer so left pointer equals previous char index plus one and either way we have to update our map so try map that set we set the current the character to the pointer and now we have to find the length so we can do let current left equals right pointer minus left pointer plus one so this we have to add one to final length so here's what i mean so we both start off at zero and then the right pointer is pointing at index of zero the left point is also again indexed to zero so it's going to happen after one because we're gonna have to add one to it to get the that entire length so then now we do longest length equals longest length return longest sorry left pointer here sorry and then we want to do you put your here too great we got it so then the time plus we the time complexity we're just doing o n as we're looping through s where n is the length of s space complexity will create a new map and that could be up to the length of s as well so it's going to be o of n so that's how you solve this problem thank you so much
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string `s`, find the length of the **longest** **substring** without repeating characters. **Example 1:** **Input:** s = "abcabcbb " **Output:** 3 **Explanation:** The answer is "abc ", with the length of 3. **Example 2:** **Input:** s = "bbbbb " **Output:** 1 **Explanation:** The answer is "b ", with the length of 1. **Example 3:** **Input:** s = "pwwkew " **Output:** 3 **Explanation:** The answer is "wke ", with the length of 3. Notice that the answer must be a substring, "pwke " is a subsequence and not a substring. **Constraints:** * `0 <= s.length <= 5 * 104` * `s` consists of English letters, digits, symbols and spaces.
null
Hash Table,String,Sliding Window
Medium
159,340,1034,1813,2209
280
Wiggles sort given an uncertain terrain nums reorder it in place such that numbers of zero is going to be less than or equal to members of one will she'll be greater than or equal to members of two which will be less than or equal to members of three etc so we basically want to create this pattern in the input array so our output has to follow this pattern so our input array is three five two one six four and we want our output to be three five one six two four I drew out the output so that the pattern is more obvious if you look at into c0 so nums of zero at index zero sorry nothing to see at index zero which is an even index 0 is an even number the element at the even index is going to be less than the adjacent element at the odd index 1 so 5 so 3 is going to be less than 5 yes keep going and then we see so this is the pattern so now 1 our output we want our even industry to always be less than the adjacent odd indicee and when we're at our odd indicee and odd index we want that element to be greater than its adjacent it's adjacent element in the even index so 5 we want that 5 to be greater than 1 etc so you basically want to create this pattern so we're just gonna go through the array and we're gonna swap according to if it violates this pattern so we're gonna go through the array if at even index so basically when I is 0 1 0 2 4 6 etc we're gonna swap if it violates this pattern this wave so we're going to swap if numbers of I remember I is even so if numbers of I is later than its adjacent odd indicee so if I is 0 if numbers of 0 is greater than numbers of 1 we know it violates this right so we need a swap so numbers of 0 is actually going to numbers of 0 can be less than thumbs of 1 so we can't get this pattern so we're basically swapping to correct it if it violates our pattern so if at odd index so when we're at an odd index so an eye is 1 3 5 etc we're going to only swap if nums of I is less than numbers of I plus 1 ok so that's basically what we're gonna do now I'm gonna cut it out so we're gonna have function legal sort taken numbs so I'm gonna just go through the array in one pass so for what I equals 0 I is less than stop length minus 1 because we don't want to go out of bounds because I'm going to check adjacent elements so I plus 1 so ok so if we're adding even into C so if I is even we're gonna swap if it violates our pattern so that's when numbers of I is greater than number of I plus 1 right we're always going to look at adjacent elements and then just swap else when we're at now we're at an odd index so we're the odd index and we're gonna swap if it violates our pattern at the odd index which would be when dumbs of I remember I is odd so is less than nums of I plus 1 so this violates our pattern so if it violates our pattern we're just gonna swap the adjacent elements okay so this is the case where it's we're at even index and this is when we're at odd index in the array okay so I'm just going to quickly write the swap function it's a function swap just numbs a be what temp equal numbers of a nums of a equal numbers at b and then x equals i'm sorry numbers of B equals temp okay so that's how we swap I'm gonna run it okay so just want to quickly go over the time complexity of this we owe N and the space will be of one right because we're doing this in one pass and yeah another way you could do this problem is you could just sort that you've initially just sort this array and then just swap adjacent like pairs just basically swap the pairs so if I sort this and then just swap the pairs it's gonna form this pattern or like this pattern right here actually but it's just easier drawn out to see what the pattern is but that would be oh and log n so this way would be better just checking if it violates the rule at the even index or if it violates the rule at the odd index and if it violates the rule we're going to swap yeah okay so I'm gonna submit it
Wiggle Sort
wiggle-sort
Given an integer array `nums`, reorder it such that `nums[0] <= nums[1] >= nums[2] <= nums[3]...`. You may assume the input array always has a valid answer. **Example 1:** **Input:** nums = \[3,5,2,1,6,4\] **Output:** \[3,5,1,6,2,4\] **Explanation:** \[1,6,2,5,3,4\] is also accepted. **Example 2:** **Input:** nums = \[6,6,5,6,3,8\] **Output:** \[6,6,5,6,3,8\] **Constraints:** * `1 <= nums.length <= 5 * 104` * `0 <= nums[i] <= 104` * It is guaranteed that there will be an answer for the given input `nums`. **Follow up:** Could you solve the problem in `O(n)` time complexity?
null
Array,Greedy,Sorting
Medium
75,324,2085
139
hey guys it's off by one here and today we're going to be solving word break in this problem we're given a string s and a dictionary of strings called word dict and the problem wants us to return true if s can be split up into the dictionary words so for example here we have the string lead code and we have the word dict with the words delete and code in them and obviously these two words make up this string so we will return true so I'm going to show you the Brute Force solution first and then we're going to work our way up to the best solution so let's see what is our Brute Force solution well we know we want to iterate through the whole string at one point because that's the only way to verify if the words can make it up so we can start just by iterating through L and seeing if this substring matches any of the words here and if it doesn't we just extend the substring to the next letter and then we check if this is in the word dict and if it's not we extend it again and if not we extend it again and then at this point we see that the word lead matches so what we want to do is now we want to start looking from here and seeing if any of those words match and then if we manage to get to the end then we return true otherwise we return false the problem with this solution though is that maybe we could find a string that matches just the lead part and then nothing else would work after that so we would need to go through every single combination possible so we would need 34 Loops there which would be n Cube time not only that but we actually need to iterate through every single word in the dictionary as well which we can say is just size m and additionally to compare strings it takes n time so the final time complexity for this Brute Force solution would be o of n to the fourth times M and if you show this to your interviewer they're probably going to laugh at you and walk out of the room so let's try and improve it I added this extra word here in the dictionary just to be able to explain the following examples better so a way to get rid of one of the ends is by instead of blindly iterating through the substrings and seeing if they match we can just instead iterate the word dict and just check if for example let's say we're starting here check if this substring here matches and if it does then we can move our pointer here and check again but like I said it still takes two pointers so it only gets rid of one of the ends and just to clarify the reason we need two pointers though is because let's say we do find Lee first well there's no word of the dictionary that has T code in it so we're going to find that and then we're going to have to return our pointer back to the original point and then we're going to find lead and then we're going to find code so now that we figured that out we can get rid of one of these ends so now our run time is going to be n cubed times m which is still terrible but at least we're making progress now so what other ways can we get rid of another end for these kind of problems there's normally a lot of repeated work and if you know by now repeated work probably means that you should use a dynamic programming approach so let me show you what I mean here I've added two extra words to our dictionary l and EE and I'm going to show you why we should use dynamic programming so I'm going to get rid of these two words because they're not really necessary for now and our algorithm currently is to have our word and use our words from the dictionary to see the first three strings so we would have Li e and l and from Li we see we have a match so we're going to be left with T code and then for ee there's no match and then for L there is a match because that is the first letter there and we're going to be left with eat code and now we can keep going so we see that if we Branch out from here and try Lee again e and l they're all going to return no match because obviously they don't match and now if you go to our e code here these two don't have a match but ee does and now we're going to be left with T code and as you can see we already calculated this over here so what we should do is store that value in an array and that way we don't have to use repeated calculations and I would get rid of another n so what we've done so far is instead of randomly making substrings here and then checking the word dict where instead going from the word dig directly to the string and seeing if they match so for example for Lee here we will take the first three of our string and see if they match and if they do then we continued looking for more matches after that and that got rid of one of the ends additionally we saw that there's a bunch of repeated work here not particularly for this example but if you go to other examples it'll come up and to get rid of an N we just use dynamic programming so that way if we ever go to this exact string here we know there's no matches in our word ticks so now we have a time of all then squared times M which is an acceptable solution depending on how you implement it because there's not really much else you can do here so now I'm going to show you how this dynamic programming solution can look so what we want to do is iterate through every word in word dictionary and iterate through every single character in the string so to start we want to initialize our I to zero so we can start at the L here and also here we're going to have we're going to call this word for now and what we want to do is check if this word starting from I equals 0 is in the string so let's see this word is a length of three so we want to check the first three characters of this and we can see that it does match so now we know that starting from T would be a valid position because we found a match for this part and we don't we no longer need to consider it so now we can check this next word which is lead and let's see starting from I equals zero to the length of this word which will be four so we consider these first four characters do these match yes so now we know in the future that starting from here would be a valid position so for example if we had a word t code in our word dictionary or if we had the word code in our dictionary we could return true at the end and now we go to the last word in our dictionary which is code and it is a length of four so we're going to check the first four characters starting from I equals zero and we're going to check if lead is equal to code and obviously it's not so now we can just go to the next iteration where I is equal to one so at this iteration we see that we don't have a valid starting position the reason is because we don't have an L in our dictionary if we did and we started again at I equals zero we would see that this and this match so we would have marked this as a valid starting position but since we don't then we can start here so now we would try and do I equals 2 and as you can see this is also not a valid starting position so we can just go on to three is three of valid starting position yes because it'll be marked it and we can see in the dictionary that there's no T code in there so we can just skip over it for now and we just go to four at four is also a starting value position and we can see that the word code is in the word dictionary so in the end what we would do is Mark this as a starting valid position and as you can see this is going to be outside of the string so if we ever get to this point we know we reached the end of the string and we found enough matches in our string using our word dictionary so how does this look with the actual dynamic programming array so this is what our array is going to look like as you can see I've moved this empty space here into the beginning because I'm going to be iterating going forwards you can leave it back here for iterating backwards but just make sure to account for that before I show you how it works I'm going to write some pseudocode out so you can see how we're going to iterate so we're going to iterate through the word dictionary and through the string so we're going to have a double for Loop so what do we want to do inside this double Loop well let's see let's start from I equals 0 here I'm pointing to the L there mess that up and let's point to this first word because we're doing it for every word so let's see this word is a length of three so we're going to check the first three characters and see if they match and they do so what do we want to happen well so we're doing dynamic programming we probably want to use our previous results somehow but this is our first iteration where we have to be found a result and that's what our base case is for so we want to set results at I plus the length of the word equal to result at I and currently you see our I is zero so if you go to I equals zero we get true and then the length of this word is three so I plus 3 would be three so we're going to set this equal to true and you can see that from our example I said that we're going to mark this as our valid starting position but instead it falls under this e here the reason for that is because this is shifted over by one to the right so now when we actually access results of three we see that here for I equals three it is a belly turning position so that's how it's going to be used so now we want to check our next word which is going to be lead and Lead is length four and let's see the first four characters of this starting at I equals zero are equal to lead so we're going to set I equals 4 to true and now we go into the last word code we know that's not the first four so we're not even going to entertain that and now we just go over to I equals one so if you go to I equals one here we see that there's no value here so we can just assume it's false and because it's false we know it's not a balanced starting position so we can just go on to the next one 2 and that's also not about a starting position so we can just Mark that as false as well so as you can see here we only want to do this if a condition is met where if results at I is true then we want to do this so let me edit the pseudo code so it looks a little neater so now the if statement is if our results at our current iteration is true and the word is equal to the string then we want to set the result at I plus the length of the word we looked up equal to true and the reason we just set it equal to True is because resulted I is already going to be true so I feel like it's a little redundant to set it to that might as well just do it directly so now let's continue so we go to I equals three so now we're starting from this point and as we can see I equals 3 has a true meaning that this gives us a valid starting position so if we look here at the third index of this string we could start at T and see if t c or t code is in our word dictionary and if they were then we would update the array accordingly but as you can see we don't have any matches so I'm just going to go to I equals four so now we check our index 4 at our array and we see that it's true so we could start searching for a word that fits the rest of the string and as you can see we have code here so what we want to do is update our result array at I plus length of w which would be 4 plus 4 since the length of code is 4 and then set that equal to true so what we're going to do is set index 8 to true and then now we can just quickly iterate to the rest of it so I can show you what's going to happen so for I equals 5 it's not a valid because there's nothing here we can just say it's false same thing for I equals six and seven these are both going to be false because we didn't find any matches for those indexes and then at the end we can just return our result array at the last index and that's basically it as far as this code goes so I'm just going to clean it up one more time and then we can talk about the complexities so the titanflexity for this algorithm is going to be o of N squared times m and M is for iterating through every word in dictionary and one of the ends is by iterating through the whole string and the last n is from comparing the strings and our space complexity would be o of n but actually there's a different solution that doesn't require much changing and it actually makes the time algorithm o of n but the space would be o of n plus m and what the solution is to put this whole array into a hash set so that way whenever you look up a word you can look it up as a key in the hash set and then that only takes constant time and I'll just do that in the code so let's get into it so I'm going to start by having a variable to keep track of r string length so I'm going to call it a length of string and set it equal to the length of the string and then from here we want to initialize our set so the way it works on python is all you do is do set and then we're digged so now we can just look up the wording constant time without having to iterate through every single character and now we want to initialize our array where we're going to store our values so I want it to be 0 for a length of string plus one and the reason I want to do plus one is because we want to set a space for the base case and then now we initialize our base case to be true and actually this is supposed to be false not zero and then now we want to iterate through the string so I'm going to do 4i in range of length of string plus one and same reason here we're doing that because we want to iterate through the array and then now we want to iterate for every word in word set and then now we just do our if statement so our if statement is pretty long so I'm going to try and go through it slowly so there's three things we want to check here first we want to check if the words or if the word equals the substring additionally we don't want to get any out of bounds errors so we want to check that I plus the length of the word is not greater than the length of the string because then that would just give us an out of bound error and also we want to check if result of I is equal to true because that will tell us that this is a valid starting position so the way it's going to look is if resulted I equals true and you don't actually need this part so I'm just going to delete it to save some space and I plus the length of the word is greater than or equal to or if you need less than or equal to the length of s and if our substring which starts at I and ends at I plus the length of the word is equal to the word but this will compare the strings and we don't want that so we want to do is check if it's in the actual set and then from here what we want to do is well actually this is not supposed to be in there it's supposed to be out here okay and then now all we want to do is set results at I plus length of the word equal to true and that's basically our whole code after that we can just return result array at the end and we can just do negative one for that in Python and the code should work and as you can see the code is pretty efficient so now I'll go through the code manually to start I've used the same example we've been using so far just delete code one because I feel like it's the simplest to understand and I've also initialized the word thick to be the same and now let's start so in the code we initialized our length s to be the length of string so this is going to be equal to 8 and we can just keep track of it here so it's not going to change and I've also initialized the word set down here and this is supposed to be a hash set and the reason we used it is because to look up a key in this it takes all of one time compared to if you're comparing a string to another string that takes o of n time next we're going to initialize our dynamic programming array so I just called it result and I set defaults for a length of length to string plus one and as you can see here this is length nine and they're not all initialized defaults because I'm going to write in them and I don't want to make it look messy but we can just assume these other ones that are blank are false and then our base case is true here as you can see and then now we want to iterate through the length of string plus one so our I is going to start at zero and I've already done that here now we want to look at every key in the word set but as you call the word here so for every word in word set what we want to do is check if this condition is true so we know that for I equals 0 resulted I is going to be true so that's checked off and then we know that I plus the length of the word both these are four so we don't have to worry about that so that's checked off as well and now let's see our string at position zero all the way through I plus the length of word which is going to be 4 in this case we want to check if that is in our hash set so let's see the first word is going to be lead and that is the first four characters here so that will be true and what we want to do at that point is update result at I plus the length of word which would be zero plus four so we want to update index four to be true so let me do that here and we could also look at code but that won't change because it won't match so I'm just going to go to the next iteration so let's go to I equals 1. and at this point we see that results at I is not true because it's empty so I'm just going to say it's false here and then we go to I equals 2 because that condition is never going to change so for I equals 2 same thing it'll be false because resulted I is initialized to false here and when we first look through lead and code we didn't find anything that ended at the second index here and so now we go to I equals 3. same thing for I equals three so we're just going to say it's false again and now for I equals four it is true again so let me just do that and now we see that I plus the length of the word so let's see four plus four that is equal to the length of the string so we're still okay here and then now we want to check our substring so starting from the C let's see if any of these match well we can see already that code matches so I'm not going to go individually line by line and we can just see that it matches here so we want to do is set result at I plus the length of word equal to true so I is currently 4 and the length of the word is four so for index 8 we want to set that equal to true and then now we would iterate through five six and seven but you already know that these are initially set to false so we're not even going to go to this if statement ever and now at the end we want to return the last index which is true and we know because we went over the example like 20 times so this is correct if this video helped in any way please leave a like And subscribe thanks for watching and I'll see you in the next video
Word Break
word-break
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\] **Output:** true **Explanation:** Return true because "leetcode " can be segmented as "leet code ". **Example 2:** **Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\] **Output:** true **Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ". Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** false **Constraints:** * `1 <= s.length <= 300` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 20` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**.
null
Hash Table,String,Dynamic Programming,Trie,Memoization
Medium
140
69
hello everyone so in this video we'll talk about the problem from lead code the problem name is square root function so you have to implement actually a square root function in which you are given a non-negative integer as an input given a non-negative integer as an input given a non-negative integer as an input and you have to compute the square root of that particular number now the problem also says that return the like the return touch would be an integer because it should not be like a double if it has decimal digits you have to truncate them trunk it means you have to just ignore them so you have to find out the closest integer to the particular number that you are given that is the square root of that so if you are let's say given 4 it is like the square root of 4 is 2 but if a given let's say 8 the square root of 8 is 2.82 something like that but you have is 2.82 something like that but you have is 2.82 something like that but you have to like truncate out the decimal parts with only two so it's only two that's returned so that's overall problem you can pause this video try to think of it of your own but uh what you could have done in this problem in success problems is that what you could have seen is like there can be multiple ways to solve this problem as well like you can do an improved force way as well like you can just do from one till let's say very large number let's say 10 to 6 and then for every number just find out that whether a partial number is the square root of that particular number like whatever number you have and if it is then this is we don't know the answer and that's it so that also brought pretty well but if the number is too large like the number is tender 18 then that particular method will not work okay but for smaller numbers it will perfectly work out but for large numbers what you could have done is that so let's say that if you have a number that is equal to let's say or let's try to find out the like the square root of different numbers and just say what is the number like what is the particular pattern you can absorb so you will start let's say from 2 then 3 4 5 6 7 8 9 10. okay the square root of 2 is somewhat close to 1 point something so i will just write down one now for square root of three is also one point something i will write down one then first two like four the square will become two then for this it will become that two point something so it's two then two and then it becomes three then 3 and so on so what you have seen is that it is like a slowly increasing function and whenever i see like an increasing function whenever increasing functions or decreasing functions you can do and if you find out a specific value you want to find out you can very easily use binary search there and that is one of the tricks i have made a complete season binary search if you want to learn all of those tricks out and you can go out check out this video will also be there also only but if you want to check out all other techniques and how to solve different problems in many search you can check out that particular uh place i will link that in the description of this video so cool now if you can directly use binary source like how will you solve like this problem using mining source so what you can do is that you will say that okay the minimum i can get is one okay like the square root i want to find out like what is the square root okay the minimum square root i can get is one because i cannot let zero okay because zero into zero is like something like not like value but like but let's say that i'll start from one only and the maximum values let's say that you can get is let's say x by x that means whatever number that you are given so if you want to find out the square root let's say 15 obviously the value of square root cannot be more than 15. so which means that the value of square root of 15 lies between 1 and 50 on a safe note like obviously it is not 15 as well but unsafe note because let's say the answer is one and the square root of one is actually one so it means that the value of that number can be equal to that number as well so on a safe note and take that the square root of a portal number will be on the range from one till the number itself and thus you can do binary search on that particular age now how you can do that you can just go to the middle of this range so let's say the range is 15 so i'll just go to the middle of that 15 divided by 2 is equal to 7 like 7.5 so divided by 2 is equal to 7 like 7.5 so divided by 2 is equal to 7 like 7.5 so we'll go to 7 and then what you'll do okay you're not saying that the square root of 15 is 7 so how you can check it out with the square root of 15 7 so if you know that the square root of 15 7 so if i do 7 into 7 it will be equal to 15 okay and it is equal to 49 but i'm looking for 15 which actually means that 7 gives me a larger square root like the value that i'm getting is larger and i want to look for a smaller number so which means that i have to go on the left side so i will now make my pointer to this point now it is let us seven so obviously the square root now comes down to one and seven so i will go to the middle of one and seven so it will become like equal to like four now i will check for four and four so it will become four into four which is equal to 16 and 16 is still greater than 15 so it will always be not equal to four so i will now go and make my window from one till four so it would be like between one and four uh so not including four actually so obviously now i go to the middle selector equal to two now two and two it will become like 4 so it will obviously be greater than 4 because i want to look for 15 so greater than 4 so i'll just move on the right hand side and so on and like you can do minuses with that and that's a particular solution so i'll go down to code part now i've taken the range l and r so it's like l is one and r is equal to x like the number you're looking for then it is the answer is that whatever answer you're looking for while l is less than equal to r you just find out the middle and whatever middle number you have if it is equal to x that you're looking for just return the answer break out that particular point okay if it is less than a number looking for you will just make your left equal to mid plus one but before that you will make your answer is equal to mid so why i'm actually doing this because the number that you're looking for can be smaller than the like the answer can be smaller so what i'm trying to say here is let's say that uh you look for like you're looking for 8 okay you're looking for a number that is equal to the answer will you get to 8. okay but the answer for eight is actually two okay so when you got boils down to two like when you are doing a binary search over this range and you come down to two into two will become equal to four and does you always know that you have to go on the right hand side but the answer is actually two so what actually means that if you get a smaller number than the number you're looking for it can be a possible answer you should not be ignoring that because the smaller answer can be always equal to like it's not actually equal to 8 but the answer is equal to 2 so it shouldn't be ignoring that so whenever i go to a smaller number like whenever made into mat is smaller than x i will make my answer equal to mid but i will not like ignore that number because that can be a particular answer but i will make my left equal to mid plus one when i go to a larger side if i let's say i want to write like find out the under root of 15 but i got 16 so that's obviously not the answer so i'll just make my right equal to mid minus one and in the end if i can directly find out a boom answer means that perfect answer then i just return that particular answer and just break out but if i cannot this while loop will actually terminate at any point and at any point whenever i stop whatever my answer will be stored because the smaller answer i will only take so and the smaller answer will be stored in answer and that's the answer actually eventually and you will learn all of that in the binding source series cool so that's our logic and good part for this video thank you for watching this video till then i'll see you next time keep coding and bye
Sqrt(x)
sqrtx
Given a non-negative integer `x`, return _the square root of_ `x` _rounded down to the nearest integer_. The returned integer should be **non-negative** as well. You **must not use** any built-in exponent function or operator. * For example, do not use `pow(x, 0.5)` in c++ or `x ** 0.5` in python. **Example 1:** **Input:** x = 4 **Output:** 2 **Explanation:** The square root of 4 is 2, so we return 2. **Example 2:** **Input:** x = 8 **Output:** 2 **Explanation:** The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned. **Constraints:** * `0 <= x <= 231 - 1`
Try exploring all integers. (Credits: @annujoshi) Use the sorted property of integers to reduced the search space. (Credits: @annujoshi)
Math,Binary Search
Easy
50,367
1,624
Hello everyone welcome back today we are going to talk about lead question number 1624 whose name is Largest sub string between two equal characters let's know what this problem is saying see this problem basically what is it that we have to give two characters Finding the string between two equal characters. Finding the length of the sub string. How long is the sub string between two equal characters? Let's read the sentence. Look, given a string, return the length of the longest sub string between two equal characters. There is a The importance point is two equal characters i.e. there must be two point is two equal characters i.e. there must be two point is two equal characters i.e. there must be two characters which will be equal i.e. AA can be A, the first digit and i.e. AA can be A, the first digit and i.e. AA can be A, the first digit and last digit can be BB or CC can also be C, there can be any character but they must be equal. Which starting and ending should have those same characters OK now let's read further what is saying that excluding the two character if there is a no true sub string if see we will exclude if the two character what is a sub string If it is not there then what will we do, we will return -1 here. Ok, if it contains sub string, -1 here. Ok, if it contains sub string, -1 here. Ok, if it contains sub string, ok if the longest character is string, then we will return the entire string, that is, if we talk as an example. We have starting character A and the last character is also A and in between it is b CD e so what will we return this, how will we return this, see our starting character is A and our ending character is also A so How many four characters are left in between, then what will be our output? It will be four. Okay, and suppose there is an example, the example is AB, CD, okay, how many substrings are there in it, there is no substring in it because the starting and ending are not the same, so in this What will we return? We will return -1. in this What will we return? We will return -1. in this What will we return? We will return -1. Well, if as an example, if the equal character is A and let's say the example number is AA then what will we return is zero because both are equal if there is no string in between. So what will we return for this? We will return it as zero. If we talk about example number two, if we have B in this, then see it has equal character. Suppose our starting is fine and the equal character in the last which is adding equal correct. How many 's' should come, in the last which is adding equal correct. How many 's' should come, in the last which is adding equal correct. How many 's' should come, then what will be its answer, what will come, 'one' will come, now they know how to solve it, they will see what is there come, 'one' will come, now they know how to solve it, they will see what is there come, 'one' will come, now they know how to solve it, they will see what is there in it, example number, after seeing the example number, first of all, see the apple, what is it saying, example number one. Let's talk about example number one is saying that we have a string s in which our input is A OK that means starting and ending is our A any sub string can come in between it OK but here what is any The sub string has not come in it, so it means that we have two equal characters but there is no string between the two equal characters, which means that what will be our output will be zero, it is written here in the explanation that the optimal sub string is Here is an MT substring between two A, that is, there is no string between two A, that is, it is empty, that is why our output is zero, exactly the same, if we talk about example number two, we have a string. It is A B C A, OK, starting and ending are same and our two equal strings are same, starting and ending, how many characters are there between them, how many sub strings do we have, so see, two sub strings are b and c, so what will be our output? Will come to the output, ours is ok, so the explanation here is also saying that the optimal sub string here is b. Okay, now let's talk about example number three. What is example number three, what is our sub string? What is given? c b. z aqua ok see starting and ending are not the same ok so we don't have two equal characters in this it means whenever there are not two equal characters in this then see what we have here if there is no true sub string return -1 then What will be the answer to this - 1, sub string return -1 then What will be the answer to this - 1, sub string return -1 then What will be the answer to this - 1, we will do it, we will get it returned, okay now we have to write this concept in coding form, so today we will use c + p and use c + p and use c + p and see how we can use it in c + p, okay see how we can use it in c + p, okay see how we can use it in c + p, okay first of all We will create a function. We will have already created the function. Okay, we are left to work on this part. The lead code will automatically generate here and give it. Okay, now first of all, what will we do, whatever will be our answer, we will ease it. What will we give, we will divide it by -1, ease it. What will we give, we will divide it by -1, ease it. What will we give, we will divide it by -1, exactly because when we do not have any sub string then what will we do, we will return only the answer. Lastly, if there is no sub string and there are no two equal characters, then what will we do? Answer Like we did here, okay, let's understand the code, what is the code, first of all, what have we done, what have we kept as my answer, which is a variable, we will call it - which is a variable, we will call it - which is a variable, we will call it - 1 because it has been simplified to the answer - 1. Right after that we have put a loop. answer - 1. Right after that we have put a loop. answer - 1. Right after that we have put a loop. Now see there are two loops in it. A nested loop is there. Okay, what will happen in this? One is going on for the left and one is going on for the right. Why is it running for because just now I told you that one on the left should be equal, there should be equal characters on the right too, there should be exactly two equal characters, so the one that will run for us first will run for the left, what is left starting, left zero. From where will it go till the size, look at the size, s is the dot size written, that is, our string is s, already here in the question it is also written, what is our string, s, so here we have s, the dot size is written. Right after that, we will do increment, then once we have checked the left side, now we will check the right side also, how to check, here is the code, it is written here that why should we put this nature loop because we We have to check for equal matching because we need two characters to be equal, that is why we have used two loops, we have used nature loop, one for left, one for right, so now we will check the right one also because why light is the right one? Will check because the curve on the left is also there on the right, if it is the last one then it is matching, then what about us is that if we move this and what will we do in this main second nest loom. The string which is moving towards the right will be A B C D A, it will start right from here it is written that it will start from left plus one i.e. left plus one and it will keep moving start from left plus one i.e. left plus one and it will keep moving start from left plus one i.e. left plus one and it will keep moving right and in the end it will reach where If we go there then what will we check that which is our which is S left i.e. is it S left i.e. is it S left i.e. is it matching with this right with S right and here the condition is written if A left is equal to S right i.e. which F On the left, to S right i.e. which F On the left, to S right i.e. which F On the left, it is matching with the character S. On the right, if so, then what will we return in the answer? It is written here that in the answer, we will return that. We will update the value. What will we update here? We will take the maximum answer right minus left minus and i.e. right and i.e. right and i.e. right and minus left i.e. whatever character is right, we will minus left i.e. whatever character is right, we will minus left i.e. whatever character is right, we will make it minus and then whatever substring of it will be displayed to us in the middle, it will be stored in the disk. It will be stored in the answer. Okay, it will be stored in the answer. If it is not equal. Okay, if we assume that this condition is not equal, then what will we do. Look, when we do not have this match, let us assume that this match of ours is not done. Okay, if we don't have a match on the left and right side, if this condition fails then it will go inside otherwise it will go out, right after that we are not matching because we have to return -1 because we have to return -1 because we have to return -1 because Already, what we have done is initialize the answer with -1, so our answer initialize the answer with -1, so our answer initialize the answer with -1, so our answer -1 will be returned here. Okay, -1 will be returned here. Okay, -1 will be returned here. Okay, if it is matching then we will check how many substrings are there in between. For that, we have a condition here, what will we do, we will update A which is the maximum distance between equal characters, so the formula for that is right minus left - 1, we will is right minus left - 1, we will is right minus left - 1, we will use it and our maximum will be displayed here. What is our maximum till now -1 is -1 is comma What is our maximum till now -1 is -1 is comma What is our maximum till now -1 is -1 is comma and this is our formula which will come out right -1 i.e. whatever is on the right i.e. if we -1 i.e. whatever is on the right i.e. if we -1 i.e. whatever is on the right i.e. if we do right minus left minus and then our maximum will come out of this. It will be fine, that is, if we talk about it now, our answer has come to -1 and it has come to two, then the our answer has come to -1 and it has come to two, then the our answer has come to -1 and it has come to two, then the maximum is which of these? What is our maximum? It will be returned, this will display our output, if this condition is not matching, okay, this is the condition left and right, the condition is not matching, which is already maximum, which was max maximum, the answer was -1, here was max maximum, the answer was -1, here was max maximum, the answer was -1, here we have I had kept the answer as -1, we have I had kept the answer as -1, we have I had kept the answer as -1, this will be printed, this will be our output, this is how it will work, thank you everyone.
Largest Substring Between Two Equal Characters
clone-binary-tree-with-random-pointer
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
133,138,1634
4
for median of two sort of the ways there are two sorted arrays number one thumbs to of size M in and respectively finding me I'm too - so anyways overall one time me I'm too - so anyways overall one time me I'm too - so anyways overall one time compacting should be or log M plus n they'd have one in time you may assume that numbers one and dimes - cannot both that numbers one and dimes - cannot both that numbers one and dimes - cannot both be empty okay um yeah I mean I think it's just excuse me this is a kind of a very standard ish problem for better for worse so there is some like we it's just a lot of not like that a couple of edge cases to consider which is like you know the definition medium I don't know an even number of elements in their way but otherwise well yeah let's start one away where it's sorted then well it's just a medium element but now you could kind of do like a thing where you like almost binary search e and try to divider and my watches always tell me to stand up to a binary search thing you need to be like okay so this is my frame where is it in the other way and then kind of a two-finger it's so the algorithm is so two-finger it's so the algorithm is so two-finger it's so the algorithm is so that's like you know you find the two end points and so forth oh yeah if you don't have time for heaps because so the suggestion is that we think of heaps I mean you kind of like in a way of you because the array is already sorted so the reason why that you don't have time for heaps is because you have to put everything in a heap and that's at least off well just reading the inputs of anyway so you actually don't even have I mean if you put it in heaps an OB and again which is already stored and this the thing that you can take advantage of this is that both their ways are already sorted so you don't need to read the entire way so you don't need to take that off and penalty and you could oh yeah and penalty you know because you could own you could randomly access certain points of it so yeah when my watch is Tommy died already stood up even though I clearly did not stand up maybe my hand waving it's enough exercise for the put an hour yeah are these or integers yeah I guess so I guess the double is just for these cases so that's one way to do it I was you could actually just probably binary search or not binary search but I was it called bisection yeah maybe I'll do that because I like to do it that way so this education may be tough that's the way out so the way that I'm thinking of is data you know in order to suffer by net by layer by section which is similar to binary search but it's more of a numerical analysis thing is that I mean maybe it's just the same thing it's didn't even do it maybe it's a new anything I don't know but uh but yeah we have some function f of X that is what for bisection it just has to be monotonically something like monotonically increasing or decreasing and then you could kind of because you know that is either increasing or decreasing in this case it's increasing I don't know I always don't know which way the camera is on my hand making may be moving but uh yeah you could kind of divide your search space in half every time and therefore by sectioning the plane oh yeah and so forth in this case you're f of X you can you just do like some K amount of those each fifties probe and each of these probes can for X it could that we turn say the number that is number of numbers number numbers that is smaller than then X and then you kind of do this k times and then eventually just get the median because and this function cost log of M plus log of n times yeah which is like us which is like this equivalent ish maybe technically lightly fast typically how they want to find yeah so that's pretty much it and then once you kind of do that we cleanly then you could kind of that's it yeah and you can find it because two arrays of numbers one and I'm still assorted you could do that in log and times because that's just nature a binary search on the bisection I guess there's too many researches but in this case you can only you only need to do a fixed number of binary searches so that's why it ends up being KT times this thing of log n plus log n where K is some constant which is related to your word size which in this case is like it was an integer that she's 32 it so yeah and may have the special case a little bit for so an even number of elements but should be true real like we could cross that bridge when we get there so okay are you score these habits and actually technically main argument could be negative up when we put it past them to be negative yeah okay mm-hmm it's like I distracted by pain mm-hmm it's like I distracted by pain mm-hmm it's like I distracted by pain and kind of turned off screens focus mm it's quite bad for now so point one a helpless function anyway yes what so now if this so median should be roughly what might have to play around with a little bit okay so this number is bigger than your our target them we were just a median and tell me to wait so you want to move you want it to be smaller so you want me to tell okay this is not the answer it's just a placeholder so don't think and double check some stuff but okay in the color so every hmm okay oh this is also a time for me to maybe use also learning C++ STL a little bit so I was I learning C++ STL a little bit so I was I learning C++ STL a little bit so I was I think lower bail I know how do you slow a bank IRA but does that also give you the index then I don't have to do it manually and for you just joining I'm just going now as I mentioned before I try not to I mean I don't I'm not ashamed to Google because I don't want for on screen because then sometimes I have sensitive stuff that Google research oh yeah okay so it does actually behave what I expect what - top actually behave what I expect what - top actually behave what I expect what - top again okay and at this stage I'm just gonna try to get something up and running do I know just maybe way pong to up I once perhaps I guess for this example statics I'm interesting now oh yeah I guess this one that will converge for some whatever but I but actually the cool thing you could do here it's knowing that if you do it just like a hundred times it should be okay because afterwards you're be on top of anyway decided that I just have something really walk so well like I've just signed flipped which happens sometimes it that's fine because you could fix that pretty easily okay having to think that odd case hmm I don't know if still I convinced actually because like I said well yeah try to be a little deliberate around off by once which I'm just bad and general and this could be just be a number between 2 and where doesn't have to be 2.5 I don't where doesn't have to be 2.5 I don't where doesn't have to be 2.5 I don't think okay which is roughly maybe expected first it took one time you too okay so we have two numbers that I'm roughly like I guess my question is I'm just put like more numbers just for just to know these are sorted so I can't just provide them thanks well it's not to random things in the increasing order nothing about tubes okay and one of them could be empty even there roughly right I've tendered an even case we just fine okay how do I pick up questions how do I want to handle the even in case it's just excuse the other way make sense because it wants the number that is strictly higher than the median which in this case is 4 so 2 so once the first number the tightest on this second we could do it twice once looking for the nth number and once looking for the video number and what's looking for the medium minus one number yeah is that cool okay but if I do that it's mostly out of laziness to be honest because they're definitely cleaner ways to do it but actually this is where you should be right for part number of things but okay how can I clean yourself or even number elements my daddy yeah I'm just gonna run a trace don't know by Chad also decide if ya like I was in the interview and I'm doing this what would the end of us die and you can go into one loop but then like I think computationally you do the same just to trice as much work in wonder which point then like ya don't know just saving something I don't know I guess I'm doing it kind of clean and then average it's over - ha to there we go mm-hmm we did fix that one there we go mm-hmm we did fix that one there we go mm-hmm we did fix that one thought why not have more even-numbered thought why not have more even-numbered thought why not have more even-numbered cases it's just random oh okay it's we pass all these let's try another one just for kicks this one does not between one over there should be like what you've never been and a half or something not eight and a half me yep okay let's just see what a die he dies okay cool oh man I'm way good I remember your search down by the time that I mean 44 millisecond I'm not gonna stress it to be honest but because you know maybe I would have to take it no to see if they you could do anything clever I mean yeah there's tell me you're clever of their way with just like moving around or ways to get the median but I think this one is also kind of cool the way I did it even though I don't know how to turn anywhere oh yeah that's let's go kind of retro this farm a little bit actually I end up with my cobras Queen ish I mean they're minor things I could clean up like there's some stuff that to live and magic constants all over the place so that's something I'd have a common item until ETS but um so definitely I could clean up stuff like this is not even use anymore and stuff like that nothing my focus is cherry just to get it out but um oh yeah so there's definite lab Queen code a code I could clean up a little bit but in general maybe but structurally I think everything's okay I have good modernization I think like I quit crank out into components then I don't really read use anything everybody gives everything I don't really have much copy and paste which I'm happy excuse me yeah I'm okay with that excuse me yeah in terms of complexity as I said it is K in this case caping 100 200 which is good enough for you know binary search because you know you / - binary search because you know you / - binary search because you know you / - every time the size of the search space times like M plus log n which is the cost of one of these things which is this cost really this is a lot this is large Empress like anyway you know really actually straight forward kind of way but that was a happy that I learned this cuz I should I got been meaning to learn though event and use the library more and stuff writing my own code for binary search for stuff like this or just I might do too much or used to but of course an individual nd weird what they prefer it's nice to compacted a space I don't use any extra space other than constant number of space or cost an amount of space more which I guess matches with the memory usage yeah I might reveal just later for the other solution but in general I'm happy with this I think I mean these are I think you know these are problems that are you know low numbers because they're early and the coast because existence I think these are yeah and this is a problem done like I've heard about before I haven't seen in interview personally but every heard of other people giving it so I think like you know you should know it just because it's something that people will ask I think there's some like the only thing I would say is maybe some kind of I don't know some kind of game for you reverse psychology thing is like we don't want to study this because a lot of people are like oh we've given this way too often so we don't get this problem anymore kind of thing then like maybe you don't have to study it but that's up to you I mean I think it thank you login yeah that's true that log n plus log n is greater than M plus and so yeah I think yet to do something with doing away it's pretty good over here - Chris yeah yes what good over here - Chris yeah yes what good over here - Chris yeah yes what Marjorie bigger for sure so in terms of kind of optimal code it's not but it's just so I don't know I think at some point I mean and this is kind of me trying to figure out climatic things in general like you know log of 2 to the 64 is 64 right which is know by definition so like the difference between log n plus log N and log M plus n is like fractions of a constant dad like I January inferior and that's like you could really justify the difference then you know but in terms of like complexity right and you have to do that other thing that was so involved with too like an interview maybe you pointed out just to kind of have that conversation going on I maybe as a good organization but uh yeah because you'd ever have to do like they're like okay let's take the an element in numbers 1 and then kind of like you know figure out how many know where does it fit in dumps 2 and then kind of work backwards and then kind of do it that way it was just kind of a little awkward for it uh maybe I should've practiced an X we
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
408
hello today we're going to be doing lead code problem number 408 which is valid word abbreviation so this problem States a string can be abbreviated by replacing any number of non-adjacent non-empty any number of non-adjacent non-empty any number of non-adjacent non-empty substrings with their lengths the links should not have leading zeros so for example the word substitution so in this first case the abbreviation is s1n so we have the S and then basically it's taking the next 10 characters and replacing that with the number 10 so substitution so that's 10 characters and then we have an N so this is according to lead code this is a valid abbreviation the second one is also valid we have the word sub then we're going to take away four characters we have a u and we take away another four characters in this third example we're taking all 12 characters so it's a valid substring or a valid abbreviation okay so here s u and then we take away three and then we have an I so this is this example is explaining how it's it can't be adjacent the numbers can't be adjacent to each other but they can have as little as one character in between them so L U or I'm sorry that's a one then U then two then o and n so there's a number between each character there and then substitution is the replacement for itself so not valid abbreviation here these two are adjacent so we can't have that no leading zeros and in this case the zero is just going to return an empty string and so how are we going to do this all right so the first thing we're going to do we're basically going to have two pointers so we're going to have one pointer that will go through the word and we're going to have another pointer that's going to go through the abbreviation so I'll just call those I and J and I'll initialize them to zero space this out looks better okay so now we need to Loop through and we're only going to do this while I so I has to be less than the word length that if it's less than the word length means we haven't gone through the whole word yet and abbreviation the past in parameter length I'm sorry j which is our pointer for the abbreviation parameter it also has to be shorter than that too all right so what do what are we going to do in here all right so the first thing we're going to do is compare the first character in word here with the first character in abbreviation so let's do that so if word do Char at I equals abbreviation J okay then what do we do well then if those two are equal they're valid so then we're just going to go to the next character so we just increase both I and J and then continue all right so that takes care of the characters but what happens if we come to a number so we need to capture that so it's if it's not a word or not a character it's going to be a number so let's look at abbreviation we'll grab this again charart at J okay is less than or equal to the character Zero or abbreviation Char at J is greater than the character nine then we just need to return false meaning the character in there is not it's not a it doesn't match word doesn't match abbreviation and the character is not a number and so we're just going to well no good there so here is how we deal with the numbers we do int I'm going to call this start equals J now so while J is less than abbreviation length we got to make sure we're always less than the length to make it ble oops water was blocking the keyboard all right and abbreviation Char at J so now this is going to capture the numbers and revation chart at J is less than equal to nine oops nine Scott nine all right so that will grab all the numbers so now what we're going to do is just increase J so in the case of substitution back over here we have the one so to capture that by incrementing J and then it'll capture the Zero by incrementing J again so basically all we've done is move the pointer we haven't actually captured the number so let's do that now so intn equals and we're going to parse this integer parse int so we're going to do a substring of the abbreviation we're going to use the starting position which is J that we've incremented and then we're going to go for J characters and that will grab the number so now what we're going to do with that number is add it to I so that means so in other words we have a 10 so now we can move the I pointer which is in the word we can move that 10 places num and that is it for the wild Loop all right so now if we get all the way through that and we've gone through the word length and gone through the deviation what we're going to do is return true or false so we're going to return I equals word length which means we'll made it all the way through the word and J equals revation link so we have to make it through both I and J both the I'm sorry the word and the abbreviation for it to be true so we'll run this it is successful we'll submit it woo faster than 92% n uses less it woo faster than 92% n uses less it woo faster than 92% n uses less memory than 90% okay now let's 90% okay now let's 90% okay now let's try running this through the debugger so I used the first example in lead code which is the word internationalization and this is the abbreviation and this should return true so initialize I and J to zero and I is less than word length J is less than abbreviation so word character at I is equal to abbreviation that is true so the i in internationalization we also have an i in the abbreviation so we're going to increment I in J and continue we're still within the parameters however now we're moving on to the 12 so abbreviation is not less than zero greater than 9 so it doesn't return false so now we're going to start iterating through the 12 here and so abbreviation less than length and abbreviation chart it's greater than Zer so it is in fact a number and so we're going to increment J and we do that twice for the 12 so now we have uh J equal to three and so we've got to grab the number out of this we're going to parse it and you can see the number is 12 so we just parsed starting at the start variable and going J position so now we're just going to increment I to 13 and so now we are at the second I here and those are in fact the same so we continue on and when I we at the Z it is also the same so continue on now we're at the four and we get down here and we've got to go through this um to get the number out of there so Char is our abbreviation is greater than zero less than equal to 9 and so increment J and we only do that once and then we run this again this par in to get the number out which is four so now we have to increment I by that amount so I becomes 19 and now we're at the n and the N which is at the end those are in fact equal so continue so now the we are not less than the word link so we're going to break out of that Loop but J equals the abbrevation length and word equals or I equals the word length and so this does in fact return true finally let's go through the time and space complexity so the time complexity is O of n um as we increment the parameter the input parameters it's just more times we have to go through those Loops same thing with space complexity uses more space the more the larger the input parameter and that's it so thanks for watching let me know if you have questions and we'll see you next time
Valid Word Abbreviation
valid-word-abbreviation
A string can be **abbreviated** by replacing any number of **non-adjacent**, **non-empty** substrings with their lengths. The lengths **should not** have leading zeros. For example, a string such as `"substitution "` could be abbreviated as (but not limited to): * `"s10n "` ( `"s ubstitutio n "`) * `"sub4u4 "` ( `"sub stit u tion "`) * `"12 "` ( `"substitution "`) * `"su3i1u2on "` ( `"su bst i t u ti on "`) * `"substitution "` (no substrings replaced) The following are **not valid** abbreviations: * `"s55n "` ( `"s ubsti tutio n "`, the replaced substrings are adjacent) * `"s010n "` (has leading zeros) * `"s0ubstitution "` (replaces an empty substring) Given a string `word` and an abbreviation `abbr`, return _whether the string **matches** the given abbreviation_. A **substring** is a contiguous **non-empty** sequence of characters within a string. **Example 1:** **Input:** word = "internationalization ", abbr = "i12iz4n " **Output:** true **Explanation:** The word "internationalization " can be abbreviated as "i12iz4n " ( "i nternational iz atio n "). **Example 2:** **Input:** word = "apple ", abbr = "a2e " **Output:** false **Explanation:** The word "apple " cannot be abbreviated as "a2e ". **Constraints:** * `1 <= word.length <= 20` * `word` consists of only lowercase English letters. * `1 <= abbr.length <= 10` * `abbr` consists of lowercase English letters and digits. * All the integers in `abbr` will fit in a 32-bit integer.
null
Two Pointers,String
Easy
411,527,2184
991
hey everyone hope you're doing well so let's start with the question so the question is broken calculator okay so there is a broken calculator that has an integer start value on its display initially in one operation you can basically multiply the number on the display by 2 or you can perform an operation of subtract 1 from the number on display got it so you have given a start value and you are given a target what you have to do you have to return the minimum number of operation needed to display target on the calculator okay so there is a start value that is given in the calculator and you can only perform two operation either you can multiply it by two or you can just subtract it by one and you have to make the start value equal to target in the minimum number of operation okay let's understand with an example so let's take this example so we have two as a start value and we have to make three as a target so what we can do is we can either multiply it by two or we can like subtract it let's say we subtract it so this will become one okay again we have either two operation multiply or subtract it so let's say here we multiply now it's become again two uh here again i have option two multiply or minus y one so let's say operate two this will become four then again i have an option two or less than one so i can do a three holes subtract okay so if you count like i got the target now if you count the operation this is uh you can say one two three and four so i like i take the four operation but i can also do is it like after two i can multiply it by two so it will become four and after this i can deduct it so this will come my target and this is take only two operations so i need to give in the minimum operation that is two let's take this example also so we have five and we have to make it eight okay so what we can do let's say we multiply it so this will become 10 into 2 again we have two operations so now 10 is bigger than 8 so let's say we deduct it by 1 so this will become 9 again this is greater so let's say we are directed by one so this will become eight okay so by this we are taking the three steps but we have one more approach let's say we deduct at start like minus 1 we make it 4 and then we just multiply it so this will become 8 okay so if you notice like this is an odd number uh like this 5 is a old number and we just deduct it by minus one this will become even and after this we just multiply it by two so we will take the advantage of this okay so let's see how we can take the advantage of this like if it is uh old number then we do subtract and if it is a even number then we do multiply it because it will keep us to reach to the nearest location okay so let's understand how we can use the like we need a minus one for out so let's see okay so let's understand with this example the flow which we understand in previous like if the number is even we can multiply it by two if the number is odd then we can basically subtract it okay so let's say this is the number so this is five and like we say like this is odd so what we can do we will subtract it will become four now this will become even so we will multiply it and this will become it okay so for this case it just work but let's give you other so let's take an example of start as three and target as 10 okay so let's say this number is old so we will subtract it this will become 2 now this number is even so you will multiply it so this will become 4 again this is even so it will multiply it then it will become eight and again this is even so this is 16 okay so now you can say like we haven't reached our target but now our current number is greater than target so we can't go with this because from the start we can't identify whether even number multiplied by 2 will give us the target or odd multiplier because uh if you multiply even number with 2 this is also an even and if you multiply a old number sorry this is a old number so this is also even if you take a even number so this will also even so from the start we can't identify whether we are going in the correct direction or not but from the target we can identify so what we will do we will go from here so we will make target equal to start okay so what we will do we will reverse our operation so for multiply we will reverse it to divide and because we are making a bigger number to a smaller number and for subtraction this will become addition okay so we'll go with the same flow we will start from here so now our target is eight and we have to make start as five so what we will do first step if number is even then this is like we can get the minimum step by dividing it by two okay so this will become eight divided by two so this will become four now i can again reduce it so this become four and i take the operation as one at here now like before going to reduce it like my target is right now is four whenever my start value is greater equal to target what i will do i will just return from here so what i will do i will return start minus target okay whenever you are you can say your start is greater equal to target so as you can see 5 is greater equal to 4 so this will return 1 from here and you have one from here so 1 plus 1 equal to 2 so you got the operation in 2 let's take this example okay so we have 10 and we have to make three okay so first step this is even number what we will do we will divide it by two so this will become five after this is the one operation now the number is ode uh like by multiply or dividing i can't make a odd number so if it is an odd number we just make it a even number how can i make it i will add a number to it so this will become six and this will have one cost to it now this is the even number and the best i can got the like i can reduce it dividing it by two so i will divide it by two so this will become three and i got the one operation so this is one two three so these are the three steps i hope you got why we are going from target to start because if we go from the start and if we say like this is a odd number we will just reduce it and we will like we can't reach to an infinite in the negative way so that's why we are going from target to start and solving a bigger problem to a smaller problem so let's write the code for this okay so what we will do if our target modulus to like it's even number what you have to do you have to just add one to it and call the function broken kelsey give the start value and reduce your target by 2 divided by 2 if it is odd number what you have to do return 1 plus broken klc so we have reversed the operation for multiply it will be divided and for subtraction it will be a addition target plus 1 okay so we have created our you can say recursive case but we have to write our base condition also base condition is if your start value is greater or equal to target you don't have to go further you just return from a start value minus target uh like this is the reason we are going from target to start value because from the start if we multiply even number also it's become even and if we multiply our number that is also even so we can't identify whether which number we have to take so that's why we are reducing our target okay so let's run it so as you can see this is accepted let's submit it up it will run so our code is submitted uh the time complexity for this is we are like if it is a even number what we are doing we are dividing a number by two so we are solving a bigger problem and then we divide every time we do the half of the problem and if it is a odd we what we are doing we just make it a one plus one and it's become even so this is our order of one of constant but this you can say every time you are dividing a number every time you do it so this will cause you an order of log n and the space is just a stack space so if you neglect that so it's a order of one approach hope you like it thank you for watching my video and do join the telegram group if you have any doubt and any concern thank you
Broken Calculator
array-of-doubled-pairs
There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can: * multiply the number on display by `2`, or * subtract `1` from the number on display. Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `target` _on the calculator_. **Example 1:** **Input:** startValue = 2, target = 3 **Output:** 2 **Explanation:** Use double operation and then decrement operation {2 -> 4 -> 3}. **Example 2:** **Input:** startValue = 5, target = 8 **Output:** 2 **Explanation:** Use decrement and then double {5 -> 4 -> 8}. **Example 3:** **Input:** startValue = 3, target = 10 **Output:** 3 **Explanation:** Use double, decrement and double {3 -> 6 -> 5 -> 10}. **Constraints:** * `1 <= startValue, target <= 109`
null
Array,Hash Table,Greedy,Sorting
Medium
2117
269
hello and welcome back to the cracking Fang YouTube channel it has been many months since I've made a lead code video but more people are watching the channel now so I figured I would just make some more videos and what better way to start then with my favorite problem of all time lead code 269 alien dictionary let's read the question prompt there is a new alien language that uses the English alphabet however the order of the letters is unknown to you were given a list of strings words from the alien languages dictionary now they just claim that the words are sorted lexicographically by the rules of this new language if this claim is incorrect and the given arrangement of words the string and words cannot be uh cannot correspond to any order of letters than return an empty string otherwise return a string of the unique letters in the new alien language sorted in lexicographically increasing order by the language's new rules if there are multiple Solutions return any of them okay that one is quite the mouthful let's look at two very basic examples before we get into uh the more concrete one because it is actually kind of hard to um go over so let's look at example three which is the easiest one which is that we're given that these words uh z x and z and essentially what we want to do here is we know that assuming the order is Right Z will come first in the dictionary then X then we actually get another Z which means that this order is not possible because we already know that Z comes before X but now if Z is coming after X then this isn't possible so that's why the solution here is actually a empty string because we have this weird kind of dependency that X comes after Z but it also comes before Z so this is the case where it's actually invalid so that's why it's empty uh here we have uh Z first and X second and this one's fine um we know that X must come before Z so the order is just uh ZX now let's actually look at you know a more complex example we won't go through the whole one because it will take way too long to write out but we'll get the general gist and we'll talk about the actual intuition to this problem so let me wipe away all of this text and now let's kind of just look into example number one test okay so we read the question prompt and we looked at two very basic examples to kind of set um the theory but let's look at the actual more detailed example to figure out how we might want to approach this problem now we know that the ordering here is a assumed to be lexicographically sorted of course we saw previously where it wasn't in which case we needed to return an empty string but we need to go forward um through this problem with the assumption that actually the strings are lexicographically sorted and if that's true then we can actually use the position uh within each of the words um to figure out the letter ordering and instead of looking at this jumbled mess here uh let's look at the English language and see how we can do this so let's take two different words the first one will be adapt and the second one will be adult right so adult so they're both the same length and what you'll notice is they actually start with the same uh characters so we can actually kind of mirror the logic of our example here so if we were trying to derive the order of our characters in the English language obviously Tred to forget that you actually know the order of the English characters um and we were told that adapt comes before adult well how can we figure out um some things here well obviously the first two characters aren't going to tell us anything because they're the same character so if they're the same we can't tell which one comes before it obviously we know that adapt comes first adult comes afterwards right so then we would compare these two but we don't get anything out of that because they're the same character and we're actually going to be able to use the same logic in our jumbled characters because if they're the same character we can't derive in order ordering here so for the D's also this is the case because they're the same character we don't know what comes before so basically we want to look for the very first uh Divergence here which is this a and this U right this is the first point where the characters are not the same similar how T and F here are the First characters in these two that aren't the same in adapt and adult a um and U are not the same now we know that adapt comes with for adult right so if this is guaranteed to be first and this is guaranteed to be second in the dictionary then we know that a comes before you right in the English language and obviously this is true and for our example here with WT and wrf what we would derive from doing the same exercise so w wrt and WF sorry for the terrible writing is that t comes before F in our dictionary right so what we can do is we can build this uh comparison for basically every single um pair of words in our dictionary here so what we could do is we can compare wrt with wrf and then wrf with ER and then ER with ET and basically try to derive all of these mappings so what you'll notice is there's actually a graph that's going to be built here which is going to take a character and we're going to map it to all of the characters um that come after it now this is a hard problem and you've probably seen that it's tagged as a graph problem so this is where I'm kind of going to break the fourth wall and tell you that to solve this we're going to need to one build a graph which is what we've already started to do here uh and the second is we need to Traverse this graph with a DFS and we're going to use a topological sort here um because we actually need to detect Cycles you could do it with a BFS my solution just uses topological sort if you don't know what that is they I have some videos on topological sort on my channel look for course schedule one or course schedule 2 they explain how to do this really easily and what this uh DFS is going to allow us to do once we have the graph we can actually Traverse um starting from each word and we can actually build our graph now one important thing to note here is that if we build our graph in the way that we just did where each character we keep a list of all of the characters that come after it if you think about how topological sort works and this is the point where you want to pause the video and watch the other videos if you don't actually know how topological sort Works remember that we're dsing and if we DFS starting from a the end point will be the last kind of like character in the graph for a right however we Traverse the graph and that will actually be the first solution we reach so say for example in the English language it's Z we would actually return Z before we return a because remember in topological sort it's a DFS so you'll go all the way down until you can't go any further and you get to Z and then you'll start going back up the chain and eventually you would return a which would mean that our order is actually going to be reversed right we'd return Z first and we' get a right we'd return Z first and we' get a right we'd return Z first and we' get a last which is not correct because actually a comes before Z so what we actually want to do is instead of building our graph you know with all the characters that come after a character we actually want to do it in reverse so instead of storing for a that U comes for after it we're actually going to store all of the characters that come before uh that second character so for you we're actually going to store that a comes before it that way when we do our um topological sort DFS then we're actually going to get the correct order and it saves us having to reverse our result string in the end Okay so this is where I want to stop I'm not going to go through the entire example because it's going to take me forever to write it out and it's just not clear I'm probably going to trip up it's easier to really just look at this in code this is a hard level problem you ideally should be able to just follow the code at this point if you're solving this one it's a lot easier than you might think the code is not that hard it's really the same topological sort template we've used in other videos so basically what you need to get at this point is that we're going to build a graph and it's going to be such that the character um is going to be in Reverse right so when a character is determined that you know a is comes before you we're actually going to store in the graph that for you uh a comes before it instead of storing that a u comes after it so we're going to reverse our kind of adjacency list here such that when we do our DFS it will return things in the correct order now if you don't believe me then please by all means do it the other way and then when you see it you submit your solution you're actually going to get your answer in reverse and it's not going to be accepted and you need to reverse the string you can do it either way I just prefer to just build it uh and not have to reverse it later anyway that is enough rambling this problem is hard enough as it is let's now go to the code editor and actually type this bit up so I will see you there okay we are in the code editor let's now type this up so what is the first thing that we want to do we want to build our graph here and remember that we want to build this for each of the characters in our words so what we're going to do is we're just going to initialize our graph so we're going to say Char and it's just going to be an empty list um for all of the characters in our words so we're going to say for word in words for Char in sorry for Char in word right so this will just create our empty graph and we're going to need to populate it so what we're going to do is we're going to say for word one word two IN Zip uh words of oops words one so what this is basically going to do is it's going to um compare pairwise words right so if we have like word one word two word three word four this is going to compare word one and word two and word three and word four and so on right because they're already assumed to be sorted so we just compare um pairwise ones we don't actually need to do word one with word two and then word three and word four uh we just need to basically just zip pairwise ones so that's what we're going to do here so for each uh pair of words we want to take the um the shorter word that's basically what we're going to go for um and the reason for this is obviously app will come before Apple in the dictionary even though they have the F the same starting um because app ends first it's actually comes before it in the dictionary right um and this holds true you know for English and also in our new language here so we want to use make sure we're traversing over the shorter word obviously if we used Apple then we could have an outof balance index um when we try to look in that index for app so that's why we do the shorter word so let's see uh for I in range of whatever the minimum of length of word one and the length of w 2 is um we want to basically go index by index remember we're comparing if the two letters at those indexes are the same then we don't really do anything we just continue because we don't get any information from that otherwise um what we want to do um is that we just want to get the ordering from when those two um uh diverge so for example remember we had adapt and adult you know the fact that A and D are the same doesn't tell us anything but the fact that a comes before U does um so that's how we're going to derive the order so we're going to say if word one of I does not equal to oops does not equal to word two of I when we have a Divergence um we basically want to say self. graph of remember we're going to do it in reverse so it's going to be word two of I we're actually going to append uh word one of I so this is the point where we're actually building for that letter so remember in our examp example adapt an adult we know that a comes before U but we this would give us the reverse order when we DFS because remember DFS you'll go all the way down and then come back up again so we actually want to say that a comes before you so we're going to store for you here uh that a comes before it instead of for a that U comes after it so that is what happens as soon as we find our first Divergence we break because after this point there's no guarantee that the words after it um are going to be uh are going to give us any information so it's only at the first Divergence that we actually get um something so we want to break here now what we want to do is we want to in this for Loop we want to have a check here for an edge case and in this Edge case um for each of these um words if actually the length of word one somehow is longer than the length of word two so for example this would be the case that you get apple coming before app which shouldn't happen because apple is actually going to come after app um of course this is in the English dictionary um but you cannot have this so This actually means that our words which are not guaranteed to be sorted this is a case where they're not so we just break because the words were not given to us in the correct order so if the length of word one is actually greater than the length of word two we're going to return um an empty string now you want to do this at the end of the for Loop in Python you can actually throw an else at the end of four uh in other languages actually don't exactly know how to do this but basically as soon as this four uh ends then you want to check that this word uh one is not actually longer than word two because in this case your um words aren't actually sorted so your assumption is broken okay so this actually builds the graph now what we want to do is we want to just do our topological sort and remember that typically the way that we do this is we have a white set which represents the nodes that we haven't visited yet we have a gray set which Vis um denotes the nodes that we're currently visiting and we have a black set which defines the nodes that we've already visited and this is the way that we actually keep track of whether or not we have Cycles if something's in the gray set and we visit it again then that means that we have a cycle in our graph which means that we just exit because we can't do anything with a cycle so we're going to say that the white set is actually just going to equal to a set of self. graph. keys so we're going to put all of those um starting nodes the black set is going to be empty and our gray set is just going to be an empty set as well we want our result which is going to be a list here which we're going to pen the characters to and now what we want to do is we want to say while there's something in the white set we want to get the next value out of it so we're going to say next iter white so this will get us the next value in our white set um now what we want to do is for each node we want to basically run the DFS to figure out the order so we're going to define the DFS function in a second but we're going to say if not and this DFS function is going to return true if um something was actually able to get you were able to derive something out of it and false if there's a cycle um so if not DFS so basically if this part returns false then we want to return an empty string so we're going to say we're going to pass the white set the black set the gray set the current node and the current result and if our DFS function actually throws a false then we want to return an empty string because that means that we found a cycle and it's not possible uh the last thing we're going to want to do is just join our result together and that should be the end of it okay so pretty simple now we just need to define the DFS function so we're going to say def the fs and this is going to take self white black gray node and res right okay so the first thing that we want to do is actually move our current node that we're working with from the white set into the gray set to indicate that we are um basically visiting it so let's just quickly Define a move vertex um or move node um function so we're going to say move node this is going to take the node we want to move the current set and the target set so what we're going to do is we're going to say current. discard the node um and we're going to say target. add the node so we're going to remove um the node from the current set which is usually going to be the white set adding it to the gray Set uh and then we'll also do the same we do it for the um the gray set and the black set so this is just a helper functions so we don't have to write this code uh multiple times so anyway back to the DFS the first thing we want to do is actually move the vertex so we're going to say self sorry move the node um from the white set into the gray set to indicate that we are visiting this node at the moment so remember the gray set stores the nodes that are currently being visited and this is how we're going to detect Cycles so now we want to do so for each uh node so we'll call it for parent in self. graph of the current node so basically for each of the characters that come before our current character we're going to say if the parent is in the black set that means that it's actually been fully explored the black set in a topological sort defines nodes which have been fully uh DFS already so we actually don't need to do anything there so we can just say continue we're good to go we can move on to the next one in our for loop we're going to say if the parent is actually in the gray set that means that we've hit a cycle because if a node is in the gray set that means that it's currently being visited and if we return to that node that means that we've hit a cycle so at this point we can return false otherwise we want to just run the DFS and again we need to watch out for Cycles so we're going to call it in exactly the same way that we did um here so we're going to say if not um self. DFS of the white set the black set the gray Set uh we want to pass in the parent this time and the current result so if this returns false then this if statement will trip and we want to return false because that means that we found um a cycle later on in the DFS so uh the last thing we need to do is once our for Loop ends and we have successfully gone through our DFS uh we need to move the current Vortex that sorry the current node why do I keep saying vertex the current node that we're visiting we need to now move it from the gray set into the black set to indicate that it's been fully explored so we're going to say self. move node and it's going to be from the gray set this time into the black set and we want to now append um the current node that we just visited um because you know we need to actually add it to our result and obviously this will have been done in the children which means that you know it's now time for this one to be added to our results so the last thing we want to do is just return true uh because we were able to go through the DFS without any problems and that's it so uh that's this is a lot of code let me just double check I didn't make any syntax DFS where is it oh self. DFS because it is a method on the class here okay cool so this should be fine let's submit it uh what happened submissions okay accepted perfect now let me just close this and we can talk about our time and space complexity test okay so let's now look at the time complexity so there's two parts to our solution and the first part was actually building the graph and the second part was traversing it so if we look at the time complexity of building the graph let's kind of go back and look at what we did so we essentially went through for each pairwise word and compared every character by character and we did this for whatever the minimum length was so the total number of operations across our entire um body of words will actually be just the sum of each of the words because remember we do them um pairwise so we'll just compare um the words as we go along and this is actually just going to come out to be um Big O of C where um C is the length of all strings in words added together right because that's the total number of characters we're actually going to need to compare because we just do it index by index so we need to do that for all of them and we just add them all together so in the worst case that is what's going to happen so that is for the actual graph building part and then we have the traversal which is just a standard um topological sort and remember this is V plus e um where V is the number of vertexes uh and E is the number of edges in the graph so that gives us a total time complexity of um so big O of C plus V plus e so that is going to be the time complexity there and for the space complexity the graph is what really takes up um the most time complexity here uh sorry space complexity so remember to build the graph um we need basically it's similar to the time we have V vertexes and E edges uh we also have these gray sets here um but the space complexity from building the graph will actually be much higher um ASM totically than these sets that we use and whatever we need for the solution so the space complexity is really bounded by the size of the graph so that is lead code 269 alien dictionary one of my favorite problems to do um once it kind of clicks it's a really cool problem I enjoy topological sorts a bit complicated to explain hopefully I did a pretty decent job uh of explaining it I think the code is a lot easier to read and understand than you know just looking at um me trying to explain it anyway hopefully that helped you hopefully I didn't ramble too much it's my first video back in a long time so I am very Rusty at lead coding and explaining these things but hopefully you find this helpful if you did why not leave a like And subscribe to the channel otherwise thank you so much for watching and have a great rest of your day bye
Alien Dictionary
alien-dictionary
There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you. You are given a list of strings `words` from the alien language's dictionary, where the strings in `words` are **sorted lexicographically** by the rules of this new language. Return _a string of the unique letters in the new alien language sorted in **lexicographically increasing order** by the new language's rules._ If there is no solution, return `" "`_._ If there are multiple solutions, return _**any of them**_. **Example 1:** **Input:** words = \[ "wrt ", "wrf ", "er ", "ett ", "rftt "\] **Output:** "wertf " **Example 2:** **Input:** words = \[ "z ", "x "\] **Output:** "zx " **Example 3:** **Input:** words = \[ "z ", "x ", "z "\] **Output:** " " **Explanation:** The order is invalid, so return ` " "`. **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 100` * `words[i]` consists of only lowercase English letters.
null
Array,String,Depth-First Search,Breadth-First Search,Graph,Topological Sort
Hard
210
1,595
hey everybody this is larry this is me going with q4 of the leeco daily weekly contest 207 uh minimum cost to connect to a group of points so this is a very tricky problem let's see uh how many people solved it as of right now about 114 um yeah so i think the first thing to notice is that n is less than is equal to 12 um on both sides so for me i just did this with a sort of brute force but a tricky brute force with dynamic programming memorization uh and that you could probably convert it to bottoms up and it took me a long time to get it even though the code is really short relatively but i'm going to explain the states so states is that basically for each you know index is equal to uh the current processing index on the left side uh used is equal whether index was used on the left side because you want to force it at least once uh index two point variable name is current processing index on the right side and mask is equal to um whether the bit mask of what was used on the right side right and so those are the states and i it took me a long time to come up with this so it's so sometimes when you watch other people do this video like it's going to look like magic right uh but so if you watch me solve this uh after the explanation uh you can kind of see my thought process as i go on hopefully um but you know and i did get a wrong answer submission but the idea is that uh and there is a progression that i made during the contest uh and you know i had some mistake but this is the states right and the thing that i would think about is that okay indexes you go to 12 uh or like the 12 possible index uses you know 2 times index 2 is 12 times mask which is uh you know 2 to the 12th power and then you know i put this in a calculator it seems fast enough so that's how i was able to kind of that's the kind of math that i would do during a contest to figure out whether it's worth to or it's able to do it um and basically given these inputs the question is uh what is the main cost of connecting two groups given that we my computer is lagging a little bit given that we reduced uh we use index minus one on the left side hmm sorry computer slow so i'm trying to see what's up uh index one on the use side index being used or not uh index two on the um index two in this case uh on the right side for the current index test and the bit mask of what has been used right so what i mean by this is and uh give me a second i'm gonna pull out the good old paint brush i'm trying to be a little bit more visual because people seems to like it um sure yeah so basically you have some nodes on the left side and basically our idea and the right side say is that we want to process the left side one by one right so we're gonna start drawing lines okay let's say for the first one the one on the left uh we draw let me choose another color we draw okay richard this is good okay good uh we draw this is good okay right and then we you know this is a brute force right so then the index two in this case would indicate for example let's say we're on to here uh and we don't keep states between index different index ones but it's basically a for loop of okay for index one for the sub problem of one um the each node on the left side do we use a note on the right side right so that's kind of the question uh for this problem and for example here um let's say you have some cost already and we want to go okay so in this case uh the bit mask would look you know on the right side would be like okay we used the first note on the right side and the second note on the right side so this is our state and we're on to the third note and now the we will go through you know it's index one connected uh index one connected to index two uh do you want it to uh and then we blue force that let's say yes uh in our current recursion then we tried the next one uh or not you know we have different choices but basically this is a way to enumerate or possibilities uh and that's kind of the way that i would think about it uh hopefully that was a little bit clearer but we'll go through the code together uh given this definition of the problem um so given this definition of the problem uh then if index is on the left side that means that we've done everything on the left side but we have to check if we've done everything on the right side if we don't have it on the right side that means that there's no additional cost then it's zero otherwise we return an infinite value because well because that means that the current configuration is not legit we did not use everything on the right side of the list um and then we go through if indexed two that means that we've used everything on the right side then we check whether we use the in the current index right because every index on the left side has to be used at least once and if this is used and that's good we just go to the next index on the left side we start over with not being used we start the first index on the right side and then we pass along the mask however we don't used it well we haven't used the left side node yet then we convert this into infinity right because that's not a valid configuration uh and again the default configuration would be infinity i don't know why i keep i need to just write infinity for this but yeah and the cost of course this is the cost of connecting the left and the right of the index left and index right and if it's used then we can also skip the rest of the um the index 2 as a possible path it doesn't have to be a path but it's a possible path and i think technically speaking this doesn't matter because eventually um eventually one of these two paths would go here but i just wanted to put it in i think uh and this path is okay whether this is used or not let's just skip this is uh not using uh the current index on this on the right side that means that given the given these two nodes i don't want to use this one on the right side uh and this path is okay given these two nodes i do want to use the this current node on the right side so then that what does that mean right um because this one is pretty straightforward just move the index by one but in this case it means that okay use is true that means that your you used the index on the left side so we want to switch that state uh index two plus one is still straight forward and also the mask which keeps track of stuff that you've used on the right side but we flipped that bit so that it shows that we used that bit on the right side and then we add the cost because this is the cost of connecting um index one and index two on the left and the right respectively so that's kind of the algorithm once you're able to get the hard part obviously it's not you know the coding it's kind of phrasing this question and coming up with these states it was pretty tricky for me uh so definitely it's not you know symbol so what is the complexity of this i think i alluded to it earlier so index is going to be o of n1 where n1 is the left and n2 is the right times 2 times index 2 which is n2 times 2 to the n2 right so this reduces to you know n1 times n2 times 2 to the n2 so this is the number of possible states um or possible inputs to possible input and for each one against uh if you look at the complexity of the code this is just all one because we do all one operations everywhere so uh work per input is equal to o of one so the total time complexity would be o of n1 times n2 times two to the n2 uh and total space complexity is just you go to the number uh so it also takes one space per input so it means the entire thing will be of n1 times n2 times two to the n to the two um or two to the n2 i don't know if i said that right but yeah so that's the time space come practicing uh cool uh that's all i have oh i didn't put take remove this so you could see the code a little bit better i think i hope i didn't block too much of it uh sorry about that but yeah take a look at this code and yeah let me know what you think hit the like button hit the subscribe button uh watch me solve it live next see ya really slow day today okay seven people have finished seems like maximum bipartite matching uh except for that things are 12 so you can do main course masks min course max 4 is there always a solution i guess so because it's a full graph oh do you have to choose the point oh no that's not oh still min quartz maxwell but i don't have that coded okay so what do you need to do more better something uh is it symmetric i guess it's not so much because it doesn't make any sense still any mods long answer on this one okay because i have to go the other way how did i clear the cash on this one actually i don't know oh this assumes that one on the left so 12 times is that too slow maybe 200 million operations would have totally submitted something quiet to this case was here don't tell me it's max for i have to take a minute that have been funny this max for work maybe not because it's not a bipartite i mean it's my part of it this is not maximum bypass matching because one edge can be unmuteable me okay so is it greedy no well this so time question questions this is too slow though if this is fast enough i'm gonna be a little bit sad to be honest all right swim better than expected i guess because it can be zero it's probably too slow even this is too slow to be honest uh it's fast enough at least though it's wrong why is this actually weird it's actually really weird this is saying this happens all the time oh maybe i just miscounted yeah okay so there's one there's more of one than the other that's okay that's what i was expecting that means that it's even slower and then we want to want something that's 1000 store i don't know even if it's in order of 10 operations it's too slow pissed off okay actually i love you a little bit slow let's yellow this hmm i think i was close down really depends the number of test cases which is why it's weird oh and i don't need to do this maybe i just need to do another fingerprint so that's not good now you need to so what's up do is that the right answer nope oh this is pretty slow but why he has a million states come on so uh hey uh yeah so that was the end of me solving this problem during the contest uh thanks for watching hit the like button hit the subscribe button join me on discord ask me questions let me know how you did how you feel and i will see you during the next problem bye
Minimum Cost to Connect Two Groups of Points
minimum-cost-to-connect-two-groups-of-points
You are given two groups of points where the first group has `size1` points, the second group has `size2` points, and `size1 >= size2`. The `cost` of the connection between any two points are given in an `size1 x size2` matrix where `cost[i][j]` is the cost of connecting point `i` of the first group and point `j` of the second group. The groups are connected if **each point in both groups is connected to one or more points in the opposite group**. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group. Return _the minimum cost it takes to connect the two groups_. **Example 1:** **Input:** cost = \[\[15, 96\], \[36, 2\]\] **Output:** 17 **Explanation**: The optimal way of connecting the groups is: 1--A 2--B This results in a total cost of 17. **Example 2:** **Input:** cost = \[\[1, 3, 5\], \[4, 1, 1\], \[1, 5, 3\]\] **Output:** 4 **Explanation**: The optimal way of connecting the groups is: 1--A 2--B 2--C 3--A This results in a total cost of 4. Note that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost. **Example 3:** **Input:** cost = \[\[2, 5, 1\], \[3, 4, 7\], \[8, 1, 2\], \[6, 2, 4\], \[3, 8, 8\]\] **Output:** 10 **Constraints:** * `size1 == cost.length` * `size2 == cost[i].length` * `1 <= size1, size2 <= 12` * `size1 >= size2` * `0 <= cost[i][j] <= 100`
null
null
Hard
null
211
hey so welcome back and this is another daily code problem so today's March 19th and it was another try question actually so let's take a peek at it so yesterday was also a try question but it was actually about creating the data structure itself it wasn't really much of a an algorithm or a liquid problem behind it was just knowing how to produce that data structure and so it's kind of like having to implement like a linked list class using some nodes and so because the tri data structure is very similar to a linked list you do actually have to have like kind of nodes and chains um but just let's quickly overview what a dry data structure looks like and so what we'll do is we'll kind of use some of this example so they have our root at the top so a tri data structure always has like a root at the beginning and then from there it has some nodes kind of in the first level below it and so it has B here and then this letter starts d and then we'll just add the third one M for mad and then so from here they kind of have chains that go down each path and so what you see here is because all these have different kind of first letters they don't really kind of reuse any of their kind of paths so all this all these characters here they're all repeating but they all share a kind of different prefixes or different first letters and so what's nice about a tri data structure is you can actually reuse it in some cases where say like we want to spell Bob we would then reuse this B since it's already at the very start and then we'll just put b o and then B and so the other thing is that you actually have to mark kind of the end of each word and so that's another attribute that you have is like we say okay this is the end of that bad word this is the end of that word name Bob this is for Dad and this is for mad and that's useful because what if you have a kind of what if Bob is the prefix of another word like Bobby in this case then you can kind of put Bobby here and then just Mark its ending like that so this is a try is very popular data structure for like uh completing words like autocomplete or for searching you know your history or you know on Google or whatever so um very useful data structure not that common in uh like interviews or in competitions but it's very good practice and helps you work with like depth first search and linked lists so yeah so let's go ahead and solve this question so there's only one difference between kind of creating the data structure itself like you normally do in this problem and that's that you have to deal with these kind of stars or it's a dot in this case usually it's represented as a star and like SQL or um and like rejects it kind of means like anything um so this caviar is that say we have a root again and we have like um B then a and then we have like C and then whatever like d e and then f and so this works so that's if we have like we're trying to match and see if we have a word like dot e f that dot kind of means that okay we can kind of go down any of the paths at the beginning so any of these first words is an eligible candidate and so what you do here is you would say okay is there anything basically that has some letter and then ends with e f and so would say okay this is a letter does it end with ef no it doesn't Okay well with this one does it end with ef no it doesn't and does this one end with ef and then yes it does and so that's the only difference is you kind of have to have like a second Loop to be able to check not just like kind of first character but say okay does this work no this one no and then this one okay yes it works so we'll go ahead and solve that at the very end we'll first kind of implement it how you normally do with a try of just searching without this Dot and then we'll end by okay let's add this Dot and see what the difference is so first what we're going to do is we're going to create our node and this is going to be kind of each character on that chain we're going to specify as a node in our class here and we're just going to grab our Constructor and it's going to have two attributes the first one is the children so that's like the eligible kind of Branch it's got Branch off from that current node and so it's going to be hashmap um like this and we're then going to have another attribute that says like is ending and this initial would be false and that's used just like I was showing so you can kind of Mark as like okay this is the end of a particular word okay and so to initialize it we just create a root and we call that node that's the root I was kind of keep showing there and that's all you need for adding a word this is the exact same way as how you would add a word for a dry data structure if you're implementing kind of the try class and so you just grab our root and we'll mark that as like our current node if we just want to say okay for every letter in our word go through our word and just say okay if our current node has a child with that letter then we just want to kind of continue down that chain because we don't want to kind of add an extra node in that row if it already exists we just kind of reuse it kind of like we did with Bobby and Bob okay and so we just set our current node equal to that child node otherwise we're going to have to create that node and so that's done just by saying okay our current node dot children at that index in our hash map is going to be a new node and then because we want to kind of continue down this chain we just set our current node equal to that what we just made awesome and then finally we had to make use of this is ending so we just want to Mark our current node as the ending for a particular word great and that's all to add a word to our Tri data structure so to search in it what we're going to do is just kind of implement the easy way of just searching and not having to handle with this Dot and then we're going to look at okay how do we handle that case so we once again just grab our root and we set our current node and we just want to Loop through every letter in our word and once again we just check okay is there a current node or is there a child at our current node with this letter that we want and if so we just kind of continue down this path otherwise we're actually going to return false immediately because well if there's no kind of character that we need in that chain then we know that it breaks the chain and there's no sense searching anymore because there's no words with that prefix okay and so next at the end of this we're just going to return true only if our current node is an ending of a word because maybe like yeah we didn't actually insert this word yet and Mark it as the end of a word right it could just be like the prefix of an existing word um I'll just move me over here great and so from there let's see short word we look through every letter there are children we didn't grab our current node if it's there otherwise return false that looks good and so now we need to like enrich this method so that we can handle these kind of dot cases and so once again we kind of have to do this recursively we're going to pass in our kind of current node and we're going to pass in the string that we're looking at and so we're going to return the result of this step first search function okay and so the reason why we want to put this in a function now is that we're going to have to reuse a lot of this object if when we're looking at those dot cases because you can kind of go down any of the paths in our kind of chains that are eligible our eligible chains and so we're going to need another case here that checks okay if this letter like is equal to our Dot case so then we're going to want to kind of recall this depth for search method again or function and kind of recursively be checking all the different chains that are eligible and so what you do is you just want to get the eligible change you just look at our children hash map and so because our hash map is kind of designed in a way that it's um the letter corresponding with the node so then you just say okay we'll iterate through for every um node in our current nodes kind of children hashmap once we get all the values makes sense and then we just want to adapt for search on that and so now that we have to pass in the word again because we already pre-processed a lot of the letters that pre-processed a lot of the letters that pre-processed a lot of the letters that came before it we don't want to have to kind of rerun those again and so we want to actually slice our string so we just say Okay s at the current index that we're looking at plus one since we don't want to include the kind of dot words since you can pretty much ignore it and then you just kind of recursively um check it so to get that I we actually have to enumerate this and I think that's it oh no so we want to return true if any of these chains turn out to be like positive or this is a positive path for what we're looking for and so we return true otherwise if we iterate through our eligible chains and you can actually um create it they're all our eligible chains are false then we want to return false in that case oh I just forgot that and I can't see that error yes needs a colon oh and someone's hammering next to me I don't know if you hear it um key error B okay for every l o we want to say Okay if that letter is in our hash map I think same thing here if our letter is in our hash map oh and these are all falls when they should be true um let's see here if our depth first search had our node oh because you have to mark this as true for a current ending yeah accepted takes a while to judge it and success and it's a pretty good performance so yeah that's pretty much it same thing as kind of creating your own tri-node data structure or your Tri own tri-node data structure or your Tri own tri-node data structure or your Tri data structure except there's this one caveat with a DOT and you just have to recursively go down every single path to see if any of the chains are eligible and naturally if none of the chains are kind of working for what you're looking for then you just return false immediately and the only other trick I think is just you need to kind of slice it so that anything that you kind of were checking down the chains before it to get to that place you don't want to process those letters again because you already got there so you just kind of minimize your word going into the next recursive call so yeah I hope that helped and um good luck with the rest your algorithms thanks
Design Add and Search Words Data Structure
design-add-and-search-words-data-structure
Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the `WordDictionary` class: * `WordDictionary()` Initializes the object. * `void addWord(word)` Adds `word` to the data structure, it can be matched later. * `bool search(word)` Returns `true` if there is any string in the data structure that matches `word` or `false` otherwise. `word` may contain dots `'.'` where dots can be matched with any letter. **Example:** **Input** \[ "WordDictionary ", "addWord ", "addWord ", "addWord ", "search ", "search ", "search ", "search "\] \[\[\],\[ "bad "\],\[ "dad "\],\[ "mad "\],\[ "pad "\],\[ "bad "\],\[ ".ad "\],\[ "b.. "\]\] **Output** \[null,null,null,null,false,true,true,true\] **Explanation** WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord( "bad "); wordDictionary.addWord( "dad "); wordDictionary.addWord( "mad "); wordDictionary.search( "pad "); // return False wordDictionary.search( "bad "); // return True wordDictionary.search( ".ad "); // return True wordDictionary.search( "b.. "); // return True **Constraints:** * `1 <= word.length <= 25` * `word` in `addWord` consists of lowercase English letters. * `word` in `search` consist of `'.'` or lowercase English letters. * There will be at most `2` dots in `word` for `search` queries. * At most `104` calls will be made to `addWord` and `search`.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
String,Depth-First Search,Design,Trie
Medium
208,746
482
hey guys welcome to the hub today we're going to talk about our third LICO algorithm problem the code number 482 license key formatting so it's a very basic problem but it's very popular recently it got frequently asked by some companies so as always I'm gonna provide not only the solution but more importantly what are the interviewers looking for when it give you this problem so let's get started so the problem is you're giving a license key represented as a string s which consists only ever numeric character and dashes the string is separated into n plus 1 groups by n dashes giving a number K we would want to reformat the string such that each group contains exactly K captors except for the first group which could be shorter than ki but still must contain at least one character furthermore there must be a dash inserted between two groups and all lowercase letters should be converted to our keys so let's see the example the inputted is doing v f3 z - e - 9 - w and inputted is doing v f3 z - e - 9 - w and inputted is doing v f3 z - e - 9 - w and a kiss for so the output is Phi L 3 D + a kiss for so the output is Phi L 3 D + a kiss for so the output is Phi L 3 D + 1 - and to e9 w because the case for so 1 - and to e9 w because the case for so 1 - and to e9 w because the case for so every our key every four characters we won't have a - in 38 but characters we won't have a - in 38 but characters we won't have a - in 38 but we don't want any dashes any - in the in we don't want any dashes any - in the in we don't want any dashes any - in the in front of the string or at the end of string so the example - 2 - 5 g - 3 - g string so the example - 2 - 5 g - 3 - g string so the example - 2 - 5 g - 3 - g case - and here it is output well that's case - and here it is output well that's case - and here it is output well that's problem so first I want to discuss the most popular solution under the discussion board the basic idea is to simplify the string first and then insert dashes as we want because we don't care about the dashes in the original string and we want all the characters to be upper cases so we simply remove all the dashes can make the string all our cases first for a task is just on five f3z to uppercase e9 uppercase W and then we insert the dashes from the back at every K position for example case war we go from the back one two three four insert - the solution is very straightforward let's see how to implement it in Java first replace all the dashes in original string was empty string to remove the dashes and then make them all upper cases second make string as stream beuter SB lens is the lens of distributor then the most important part in 13 dashes from back at every key position so loop from is lens minus k2 is bigger than the room and I add K for every round we do it from I is a lens minus K instead of dance because we don't want a dashed at the end of the string if we do it from thence there will be a dash at the end of the string we iterate I to bigger than zero not to do because if we iterate I to zero there will be a dash at the beginning of the string and we don't want that so inside the loop just insert a dash to index I don't forget to convert the string butor to a string before returning it did we forget something very important time complexity and space complexity so space complexity is very straightforward just o n because we used a size in stream butor how about the time complexity so I went over the comments in lico discussion board apparently a lot of people just assume the time complexity is o n but let's walk through the code first as the repeats and asked our arrow keys ideally the time complexity here is all in and then creating a stream viewer where string s o N and then looking the stream builder at every key position o and divided by K however inside the loop stream Puterbaugh insert is actually taking o n time not a one so the time complexity for the loop is n divided by K times n equals who one kiss times N squared so the overall time complexity is absolutely bigger than Oh n for coding interviews interviewers do not care about what programming language you use but whichever language you choose you have to know the performance of the libraries you use now let me explain to you why Java stream beuter insert takes o n time stream pewters in Java are implemented by charter race for example let's initialize a stream booter somewhere deeply in Java is a char array like this now the tail is indexed 0 if we start a pen capture the suit array the tail pointer moves accordingly so stream builder append only takes time or 1 however when we want to insert a dash in the middle what Java does is for us it makes a copy of the second half and then add the dash and then copy them back after the dash because array is not a linked list we can never do inserting with a one time so the time complexity for stream builder insert is Oh n remember we mentioned in previous episode that when we try to find the optimal solution try to think that what's the lowest time complexity possible for this problem it's usually our goal so the lowest time complexity possible is o in here I think it's very obvious so how can we achieve that o in time complexity let me share with you my own solution it's also very straightforward we can simply iterate the string from back to front if we run into a - just ignore it otherwise we'll into a - just ignore it otherwise we'll into a - just ignore it otherwise we'll make the chapter abacus and in the meanwhile what I want to have a variable to count where our way in size K section so when account that one account rich K we can add the dash for the task case we go from the back and we have the stringbuilder SP and then the count first we have a character lowercase W make it uppercase and add to the stream builder the count was 0 and now is 1 and - in the original string just skip it - in the original string just skip it - in the original string just skip it and then number 9 add to the stream buter and the count was one now - and buter and the count was one now - and buter and the count was one now - and then another - skip and lowercase e then another - skip and lowercase e then another - skip and lowercase e making a purchase additive - distributor making a purchase additive - distributor making a purchase additive - distributor the count is three now and then the number two at table distributor the count becomes two to four notice that away rich k now we need a dash here so add the - the count is back to zero add the - the count is back to zero add the - the count is back to zero and then similarly - skip it ibaka state and then similarly - skip it ibaka state and then similarly - skip it ibaka state a distributor count plus number three a distributor count as class then uppercase F a distributor count as fast finally a number five a distributor count plus the count is four again so add an - to our stream builder and so add an - to our stream builder and so add an - to our stream builder and set count back to zero well after the loop it's possible that we will have an actual - at the end that we actual - at the end that we actual - at the end that we don't want so check if the character at the end is a - if it is remove it don't the end is a - if it is remove it don't the end is a - if it is remove it don't forget to check if the string builder is empty before you do that because it's if it's empty there will be no character at the end the last step for the solution will be reverse the stream beuter and return it as string let's discuss the time and space complexity for the solution space is o n because we used a size n distributor how about the time complexity so the loop takes o n time and inside the loop stream beuter the append takes o 1 so overall Oh N for round 1 for round 2 stringbuilder reverse actually text o and the to string also takes o n so the overall time conductive for the solution is Oh N let's try the two solutions in the code to see if the performance of solution to is truly better than solution one wrong solution one the run time is 244 millisecond it only beats about 28 percent of Java online submissions but if we run solution to the burn time is only 24 minute second and it beats 88 percent of Java online solutions if you wonder well you're our solution to only B's 88% you're our solution to only B's 88% you're our solution to only B's 88% what kind of solution can have the best performance let me show you something from a little discussion board this solution uses char array instead of string builder the time complexity is also om but technically lower than our solution to and this solution is 98% of solution to and this solution is 98% of solution to and this solution is 98% of Java online submissions as we can see it is a relatively competitive complicated solution for an easy level problem like license key formatting we typically target to solve it within 15 minutes because interviewers probably prepare more problems for you to solve for the rest of the time I personally don't think a solution optimal like this is necessary during interviews if you are not confident solving the problem using the optimal solution within your intern time just go with the solution that you are most comfortable with remember any solution is better than no solution the same logic applies to real world problems too in industry we do pick here about the performance of the code however we hear about effort engineers put just the same or even more FS the people value done is better than perfect we can see this poster everywhere in a company I believe is also the weight goal for coding interviews unless interviewers specifically asks you to find the optimal solution which is not very common done is always better than perfect do what you feel confident first and then optimize that if there is time left well that's all about our early code number 482 license key formatting I hope you have a better understanding for what interviewers are looking for in a coding interview after this video programming languages do not matter whichever language you use own it like a pro know the performance of the libraries thanks for watching if you like my video please subscribe like and comment this is the code I'll see you next time
License Key Formatting
license-key-formatting
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first group, which could be shorter than `k` but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. Return _the reformatted license key_. **Example 1:** **Input:** s = "5F3Z-2e-9-w ", k = 4 **Output:** "5F3Z-2E9W " **Explanation:** The string s has been split into two parts, each part has 4 characters. Note that the two extra dashes are not needed and can be removed. **Example 2:** **Input:** s = "2-5g-3-J ", k = 2 **Output:** "2-5G-3J " **Explanation:** The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above. **Constraints:** * `1 <= s.length <= 105` * `s` consists of English letters, digits, and dashes `'-'`. * `1 <= k <= 104`
null
String
Easy
null