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
92
okay hello so today we're looking at question 92 reverse linked list given the head of a singly linked list and two integers left and right where left is less than or equal to right reverse the notes of the list from position left to position right and return the reversed linked list here we're given two examples uh example one we're given the linked list one two three four five with the left position at node two and right now at node four so they want us to reverse the sub link this uh of notes two to four so as a result we get one four three two five example two we're given the a linked list with just one element one note in it so the left position we're given one and right we're given one as well so output is just the same linked list here are some constraints the number of nodes in the list is n and the it ranges from 1 to 500 and the note values can range from 500 to 500 and lastly uh the positions of the left and right are given are accu like valid so left is at least one in above and right is either equal the value of right is either equal or more than left and right is definitely less than or equals to the number of nodes in the linked list and here we're given like a follow-up or and here we're given like a follow-up or and here we're given like a follow-up or like a hint suggesting that we can have a solution that does it in one pass so before we continue i think we can already isolate the cases where left and right values are the same we can just directly return the linked list it doesn't really matter if the link place has one or more nodes because if they are the same we're just you know they're just telling us to reverse that same note so we can just directly return it so if right and then we return hit okay with that out of the way let us start drawing for the um cases like example one get out my drawing tablet okay um maybe we can expand this a little bit for more space okay so let's try it out oh okay we need to go into drawing mode one two three four five ugly arrow let's fix that okay then um we somehow need to manipulate it into this form right one four three two five okay this is really ugly but you know i guess it's fine right let's mark out the l position and the r position okay so let's think about this we kind of have to get to the last stage like step by step right so to do that we need um a pointer pointing to the note that we like are trying to uh let's change colors maybe blue we need a pointer like denoting where like we want to do the manipulate it's dot next so use the current pointed point to that and then we need a next pointer to well keep track of it because once we break this we don't want to lose our linked list right so we break that and we point this to like a none maybe we can have pref uh initiated to none first and so it points to this pref for now right so this is step one uh we have that down once that step one is done we would basically want to step our current pointer up right okay so now current pointer we assign it to position three and next pointer we assign it to the next uh position four okay so we have that down this is now maybe i should draw this in pink yes points none and then um again we break this and we point this to the pref oh i forgot to mention that we have now shifted pref one step up to the previous uh current position which is n which is note two yeah okay once that's done okay so this is step two then we do this again ah i keep drawing the arrows weird so this is not like that right a little odd but bear with me uh foreign five none so now um this note is pointing to this oh i should draw it in blue okay get away blue and our current is pointing to this and our next is now this okay um what oh prep previous okay so now at this point in time we're not exactly done yet because we're kind of close right but we can see that the note number one note with value one is not pointing to four like it should and two is not pointing to five uh as it should so the last very last step is to let's draw it in a different color what color is this oh no yellow red green oh no okay green to kind of like denote something else a little bit different at the end of this reversal we don't really want to reverse anymore right so at the end of this uh reversal we want to make sure that it one is pointing to next to current one is pointing to four which is current and two is pointing to 5. in other words we want we need some pointer to kind of like know where this um uh note is right because right now we don't have any so let's just initiate it as maybe um before l we point it to this is we keep track of it with this uh before l so at this point in time we have our before l and before l will now before else will not help us relink like the last step to get our final links list so before else dot next uh if you look at my cursor before else dot next wait no sorry this is before else dot next should point to five so assign it this next p and then maybe we should use a different color right oh how about what color is this oh it's still red green um before l dot next should point to this so this is gone and lastly but not least um before dot next should point to current which is four okay so that is pretty much it the last thing we have to um add in to this solution is imagine if our left in integer given to us is one then in that case we can our before l has to be like one before this first note number one right so to kind of solve that problem what we can do is oh yeah we have perp so what we can do is have a dummy note dummy and initialize before l to this first yeah and at the end of everything you know we just return dummy.next dummy.next dummy.next and you know make sure that well maybe i should draw it here to show how it's supposed to be initialized early initialize it to before l stop next is this okay what else are we missing nothing else right i think so oh yes okay so the last thing to know is it is a little confusing because the index is the indexes are not really like what we're used to you know how like it's always starts from zero but in this case it actually starts from one so when we are writing the while or for like the loop to traverse to the position l and r we have to be mindful of that yeah that's like the last point i wanted to add before we try to code out the solution okay so just clear the drawing board okay it's not heavy it's just um okay uh yeah so initializing right i forgot what okay so first off dummy note no it's stummy oh okay so we need our before l as well tell me before okay dummy dot next and you point it to the head okay now we want our while loop to help us get to the correct note off l left i'm like when i say l i meant like left um yeah sorry about that i in range left but remember it's like one off so we have to minus one to get to the right spot we do before l equals before l dot next oops okay so we have before l now current is takes the position like one note after before l so current is before l dot next okay great so we have we now have our um before l and current in the correct position so the next step will be to um do the shift the reversal right but before that we have to remember to initialize the pref um equals none the thing so we have something to point to for our like first um assigning yes so press none okay so oh sorry if there's some background noise uh while okay no let's just use four for consistency sake range right minus left well is this right let's see so we can see that we want three operations in this case right so it's four minus two uh we get two um which is the for loop is zero one so that's only two because um python's range is like one less than that number you um argument you pass in so we have to add one to it okay so with that done uh i mean we just have our follow but you know temp is let's call it next p next is current.next right yeah let's place current.next like that yeah let's place current.next like that yeah let's place current.next like that keeps track of the rest of our linked list so it doesn't get lost uh current here we have currents.next is prev and then okay so we have that down uh now we have to remember to update the positions of pref and current so pref equals to current and current equals to next p is that right um okay so once this for loop is done um we would reach the state where the notes are in the correct positions but the before l and the next p is not isn't in the correct position right so we have to do something about that like we outlined earlier we just have to set before else dot next to next p and then before else dot next to wait two oh what is hang on let's take current right dot next to current okay let's try that oh how do i okay before else dot next is what did we say just now next p and in the end we return dummy dot next okay let's see if this works i don't know oh no okay oh something is wrong obviously uh let's try to figure out what is wrong one five we are given one five hmm okay i'm gonna pause the video real quick to like try debugging it um give me one minute okay sorry about that um i finally figured out what the problem is it's because uh if we look at this diagram um we i forgot that like after this iteration current uh current's position would already be pointing to five and um the current and pref's position would then be the correct one so technically i should assign that to before else.next instead before else.next instead before else.next instead so this is wrong it should be pref instead let's try again okay um and then like submitting it okay great so that is it for today's tutori well video walkthrough um so thanks for watching
Reverse Linked List II
reverse-linked-list-ii
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_. **Example 1:** **Input:** head = \[1,2,3,4,5\], left = 2, right = 4 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[5\], left = 1, right = 1 **Output:** \[5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 500` * `-500 <= Node.val <= 500` * `1 <= left <= right <= n` **Follow up:** Could you do it in one pass?
null
Linked List
Medium
206
865
Quick Profit Loot See The Question Select With All The Best Phone In This Question Mez Pe What Is This What Is Distance To Must Subscribe Now To Subscribe My Channel Subscribe subscribe The Channel and subscribe the two Note 4 Do Which Contents All The Subscribe The Channel A Supposed to give one and me to find the tree with all the best wishes Notes Subscribe Must Thursday Subscribe Indian Every Day in the History and Tree to Avoid You a Bride of Loot 0123 Latest Freelance and 323 Labs Ki Mej Pe Subscribe Button Adhir Video then subscribe to the Key Value Which Will Initially Be Minus One Is Waiting For Issuing Notice Updates Reviews &amp; References Result Not For Loot Reviews &amp; References Result Not For Loot Reviews &amp; References Result Not For Loot Thursday Open One Takes Death In The Armitage Bill Most Of These Divisional Simply Subscribe To Return Tips To these sites came increasing the day when ever were falling leaves method because 0f will get increase notification love android user kunthu if then update amazed with a just half the fuel the best result two 's note husband has been discussed with no the 's note husband has been discussed with no the 's note husband has been discussed with no the height of the Tree of Life not last right result related subscribe The Amazing and notes and also requested video
Smallest Subtree with all the Deepest Nodes
robot-room-cleaner
Given the `root` of a binary tree, the depth of each node is **the shortest distance to the root**. Return _the smallest subtree_ such that it contains **all the deepest nodes** in the original tree. A node is called **the deepest** if it has the largest depth possible among any node in the entire tree. The **subtree** of a node is a tree consisting of that node, plus the set of all descendants of that node. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\] **Output:** \[2,7,4\] **Explanation:** We return the node with value 2, colored in yellow in the diagram. The nodes coloured in blue are the deepest nodes of the tree. Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it. **Example 2:** **Input:** root = \[1\] **Output:** \[1\] **Explanation:** The root is the deepest node in the tree. **Example 3:** **Input:** root = \[0,1,3,null,2\] **Output:** \[2\] **Explanation:** The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest. **Constraints:** * The number of nodes in the tree will be in the range `[1, 500]`. * `0 <= Node.val <= 500` * The values of the nodes in the tree are **unique**. **Note:** This question is the same as 1123: [https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/](https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/)
null
Backtracking,Interactive
Hard
286,1931,1959,2203
1,749
what's up guys welcome it's uh day 47 of the 100 days elite code um we got a good problem here it's a medium problem it's maximum absolute sum of mne sub array let's get right to it so it's a medium problem uh you're given an integer array nums the absolute sum of a sub array uh num and it basically just uh puts in mathematical notation is the absolute value of the sum right so you can think of it of just getting the sum and then putting absolute value basically what this means is that if the sum is negative so say you got a bunch of negative values here and it makes this whole um equation negative well we take the absolute value which is of course always positive um it defines it here for those of you who don't know the math but it's pretty simple if x is negative integer then abs x equals negative x non-negative and it's still negative x non-negative and it's still negative x non-negative and it's still you know the absolute value doesn't do anything um here are some examples so here the subarray two three has the absolute sum five two plus three is five that's pretty easy but here we have an example um that's a little bit more intricate so this sub array negative 5 1 negative 4 has a sum of this which is negative 8 but if we take the absolute value of negative 8 we get 8 so that's why we output 8. okay so let's solve this problem um to start we are going to be uh defining some variables let's say the max or the min the max whatever we can set those to zero uh we're going to be setting current min curt max to zero as well and we're gonna define an answer variable and we can just call it or we can just set it to um the absolute value of the first index of the array so these two values are going to keep track of the current minimum value and the current maximum value okay these two values are going to keep track of the minimum subarray value that we've encountered throughout all of our previous iterations and the maximum subarray value that we've encountered throughout all our previous iterations um it'll make a little bit more sense when i implemented so we're just going to do 4i and nums kermin we're going to add i to it same thing with curmax we're going to add i to it and now we're going to do another operation with kermit we're going to say kermin equals the minimum of um i or kermin okay so i mean you could put this all in one line you could say uh kermin equals um yeah i mean you could do that um if you wanted to let's actually just do that's um looks better okay and then curmax equals max of i plus curve max okay so basically what we're doing here is we're getting our new current minimum um if we have a negative i well um i mean it still could be either way we still could have a minimum value of i or the minimum value of i plus kermit um but basically the reason why we need to check this is because we need to know whether or not we're still going to keep our current minimum value because our current minimum value could still be zero right or whether or not we are going to um add uh i to that one um or just keep i same thing with curmax that's why we're doing this okay because sometimes um the current maximum value could theoretically just be i okay so now what we want to do is we want to say the min is equal to the minimum of um kermin the min the max is equal to the maximum of curmax the max okay so the minimum maximum these are the total maximums um we are basically going to um check whether or not our current max and our current minimums are smaller than or bigger than our existing ones and if they are we need to update these values because as you'll see we're going to set answer to the max of the max or the absolute value of the min and then we're just going to return answer and we'll be good and i just ran that i didn't submit it there you go that's how you solve that one if you guys enjoyed that video um please like subscribe today was day 47 we got another day uh 53 days ago so i'll see you guys tomorrow
Maximum Absolute Sum of Any Subarray
sellers-with-no-sales
You are given an integer array `nums`. The **absolute sum** of a subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is `abs(numsl + numsl+1 + ... + numsr-1 + numsr)`. Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums`. Note that `abs(x)` is defined as follows: * If `x` is a negative integer, then `abs(x) = -x`. * If `x` is a non-negative integer, then `abs(x) = x`. **Example 1:** **Input:** nums = \[1,-3,2,3,-4\] **Output:** 5 **Explanation:** The subarray \[2,3\] has absolute sum = abs(2+3) = abs(5) = 5. **Example 2:** **Input:** nums = \[2,-5,1,-4,3,-2\] **Output:** 8 **Explanation:** The subarray \[-5,1,-4\] has absolute sum = abs(-5+1-4) = abs(-8) = 8. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Database
Easy
1724
290
everyone welcome back and let's write some more neat code today so today let's solve the problem word pattern we're given a pattern and a string s and we want to know if s follows the same pattern what do they mean by follows the same pattern well let's take a look at an example a pattern in this case is just going to be a series of characters where each character should map to a word in the string s and a word in the string s is defined by basically uh these spaces right these spaces separate each word so dog is a separate word which is followed by a space and then cat is another word and then another cat and then dog and this part is a little bit confusing because they don't explicitly state it but i guess that's what they imply by bijection but basically each character so in this case a has to map to a single word right only a single word and every word in the string s has to map to a single character so it has to go both ways there has to be a single mapping for each character and each word so in this case a is the first character and dog is the first word so that must mean a has to map to uh the word dog okay and then we get to another character b that must mean b has to map to the character or the word cat and it also goes both ways right dog has to map to the character a cat has to map to the character b now we get to our second b so since we've already seen a b before that must mean that this next word has to be cat and it is cat also since we've already seen the word cat before it must mean that cat or it must mean the character here has to be b and it is a b so everything is good we don't really add anything here and then we see our last character which is a lowercase a and then we see the word dog that's also consistent a maps to dog maps to a so you can see that this is mostly straightforward but it's really about the edge cases here first thing we want to talk about though is the data structure we're going to be using here while we're mapping characters to words and words to characters it makes sense to probably use a hashmap in this case that's really what it's designed for and it's the most efficient data structure we could use in this case because each mapping like this is going to be an o of one operation okay but one of the edge cases here is well in both of these examples we have the same number of words as we have characters in the pattern but is that always going to be the case well nowhere in the problem description do they say that they do say below in the problem description that there are you know each word is defined as being separated by spaces but they don't say how many words we're going to have and how many characters we're going to have in the pattern so if possibly we have more words here than we have characters here or maybe we have more characters here than we have words here then that's not going to work so in that case we would return false because then the patterns don't match each other now how are we going to do that well just to get the list of words we could literally just call a built in function called split and split this string based on the space character which would give us a list of the four words that are contained here now maybe your interviewer doesn't want you to use the built-in one well that's okay because built-in one well that's okay because built-in one well that's okay because it's not super difficult to write our own split function but that would be something to talk about with your interviewer right basically what we would do in that case is just keep reading characters until we reached a space and then say okay this is one word and then we'd start again at the beginning here keep reading characters until we see a space and then say okay this is one word and then you know put those words inside of a list of some kind okay let's take another example just to illustrate why we need to have our mapping go both ways right from a character to a word and from a word to a character that's why we're going to be needing two hash maps and i just want to show you exactly why let's take an example like this one suppose we were only mapping from uh character to the word then we would say okay a maps to cat that's perfectly fine a maps to cat then we'd say okay b also maps to cat even though that's not allowed remember a word has to map to a single uh character but in that case clearly that's not true how can two characters map to the same word that shouldn't be possible but in this case it is and then we'd say okay this last a also maps to cat well that's perfectly fine uh but remember this doesn't work we can't have that so what we would do in this case also when we get to this b character uh well first when we get to this a character we'd say okay a maps to cat maps to a then we'd say okay b maps to cat well that's fine because b doesn't already map to a different character but then we'd say okay cat maps to be well take a look in our hash map we'd say that well before we even do this cat already maps to a different character so therefore we can't have it be reassigned to a different character so in this case we would immediately return false this doesn't work so that's pretty much what i wanted to cover and by the way what is going to be the time complexity of this solution well we're going to have to go through every character in the pattern and pretty much every character in the overall string that contains all of our words so you can say the time complexity is going to be something like big n plus m you know just based on the total number of characters we have in each of these strings the memory complexity is going to be roughly the same because remember we have two hash maps one for each of these strings so without further ado let's jump into the code okay so now let's write the code the first thing we want to do is actually get our list of words so we're just going to use the built-in function for the string s and built-in function for the string s and built-in function for the string s and just split it based on the space character and then we're going to initialize our two hash maps actually before we even do that we should probably check if this is going to even be a valid solution basically the number of characters that are in pattern should be equal to the number of words that we have but if they're not equal then we don't even have to do anything because we can immediately return false this solution won't be possible but if that's not the case then we can initialize our hash maps so we're going to map each character to a word and each word to a character so here are our two hash maps and then we're gonna uh want to iterate through both of the characters in pattern and each word in our list of words at the same exact time we know that the length of both of those is going to be the exact same so it should be easy to do we could do that with like an index but in python it's pretty convenient to use a built-in pretty convenient to use a built-in pretty convenient to use a built-in function so i'm going to iterate through each character and each word in our two data structures and in python you can zip them basically that allows you to iterate through both of them at the same time so we're going to zip the characters in pattern and the words in the list okay so now what are we going to do well first we want to check if we have to return false basically if the pattern somehow doesn't match so basically we want to know if this character that we're looking at already maps to a different word so basically that would mean that c is already in our character to word hash map right and the word that it maps to which we can get by uh using it as the key is a not equal to this word that we're currently looking at it should be mapped to this word but if it's not mapped to this word then we have to return false and we're going to actually do the exact same check with the word uh with the opposite data structure so basically if this word has already oh um a character mapped to it we would check it like this word to character and if uh that word or if that character that this word is mapped to is not equal to the character that we're currently looking at right now then we would also return false because that means it was already mapped to a different character but if neither of these is true that means we're perfectly fine and we can basically add these to our hashmap either we haven't seen this word or this character before or we have seen them before and they already map to that same character or word so basically what we can do is just like this either this operation will be setting this mapping this character to this word for the first time or it will be mapping the same word that's already in this hash map so it'll it basically works out in both cases and also do it with the word so the word this word is going to be mapped to this character and then we're going to continue with the entire loop and if the entire loop exits and we didn't find any mismatches between any characters or words then we know that the patterns match so we can go ahead and return true now let's run the code to make sure that it works and as you can see on the left yes it does and it's pretty efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Word Pattern
word-pattern
Given a `pattern` and a string `s`, find if `s` follows the same pattern. Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `s`. **Example 1:** **Input:** pattern = "abba ", s = "dog cat cat dog " **Output:** true **Example 2:** **Input:** pattern = "abba ", s = "dog cat cat fish " **Output:** false **Example 3:** **Input:** pattern = "aaaa ", s = "dog cat cat dog " **Output:** false **Constraints:** * `1 <= pattern.length <= 300` * `pattern` contains only lower-case English letters. * `1 <= s.length <= 3000` * `s` contains only lowercase English letters and spaces `' '`. * `s` **does not contain** any leading or trailing spaces. * All the words in `s` are separated by a **single space**.
null
Hash Table,String
Easy
205,291
51
hello guys today we are going to see the r code question 51 that is n Queens uh this is a problem related to backtracking and recursion uh the N Queens puzzle is the problem of placing the N Queens on N cross n Chase board such that no two queen attack each other given an integer n return all the distinct solutions to the N Queen's puzzle you may return the answer in any order and each solution contains a distinct board configuration of the N Queen's placement where q and Dot both indicate a queen and an empty space respectively so here is a board given that as we know that uh Queen can move in all the eight directions so we would be starting from left to the right in this direction and we would check whether and we would be iterating in all the rows and in each of the row we would be checking whether that row contain a queen or not if it will contain then we cannot keep that another queen in the same row so we also have to check diagonal movement as well as we are moving from left to right and we will fill from left to right so if we start from this then there would be no Queen in this place and this place so we need not to check the right part we always need to check the top left the left then left btom this all three directions we have to check as we are moving from left to right this is done for checking whether the uh Queen placed in a particular index is safe or not then after placing we have to mark that column and row as marked such that no any other Queen can be placed in that row or column so let us see the code of the question here is the code of the question first we have taken a vector string VT uh in order to store the answer in it then a board is taken which is initialized with all the element cells are initialized with dots and the solve function is called and then finally the answer is return so in the Sol function we have to stop if column is equal to n we are traversing from left to right and if column becomes equal to n we have to push back that board inside VT and that would be one of our answer and we have to return and we have to Traverse in all the row and in each row we have to check if that row column is safe to put that Queen on that cell is not or not if it is safe then we have to put it um put that Queen in that row and column we have to call for next column and if it is safe then again we would be able to put that uh Queen and during the returning process we have to backtrack and return uh and remove all the element that are placed with that dot and for checking that safe function we have to check till uh row becomes greater than equal to Z and columns become greater than equal to Z if this is the case and if that board row column is equal to Q then we have to return false this is we are moving row minus- and column minus- are moving row minus- and column minus- are moving row minus- and column minus- means we are moving top left and this is the case uh where we are moving column minus means only left and this is the case where we are increasing the row but decreasing the column and in each of the case to retain the original value of column and row we have taken a duplicate row and duplicate column if all these functions are not true then finally we have to return true and if any of them becomes true then we have to return false so this is the code thank you
N-Queens
n-queens
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other. Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**. Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively. **Example 1:** **Input:** n = 4 **Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\] **Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above **Example 2:** **Input:** n = 1 **Output:** \[\[ "Q "\]\] **Constraints:** * `1 <= n <= 9`
null
Array,Backtracking
Hard
52,1043
771
hello friends so today we're going to discuss again next problem in the latest hash table series and as you can see the second easy problem is jewels and stones so you are given a string j consisting of different types of stones that are jewels so as you can see in this string all the jewels are present and s represent the stones you have so these are the stones you have and this is the gels the type of gels and each character in s is a type of stone you have okay so you want to know how many stones you have are also dwells so like you have some stones and you have to check that whether how many stones i have are also jewels so jewels are distant and s can contain different or like the same character so the simplest explanation is like for this problem is you can make a map of all these characters because all these characters are distant you can make a key map in which or you can make a set also but because i'm doing all this playlist with map i like i'm using map so you can make a map pointing every character to one so what i'm doing here is i am making a map in which every character which is present in the dual series i am making it equal to 1 which means that ok a is 1 capital a is 1 and this is stored in the map then i'm moving from left to right for this s string which is the number of stones i have or the stones i have and then for every stone i will check that whether this stone is a jewel how i can check i will send this character in the map as a key and if it returns one then it will means that yes it is a jewel and for this b if i send b as a key in this map there is no b so it will return not zero and if i return on zero it means that it is not uh like a valid uh jewel so we don't count it and that's the whole logic for this problem so i'll take down to the code part now which is also very simple the input of n and m the length of these so will make a character to integer map so we will map a character to the teacher which i have told you for every character integer which is one so what i'll do will move from left to right in the dual string and for every ith jl i will mark it as 1 then total is equal to 0 and then we'll try it over all the characters in the stone part and i will do a total plus equal to i will add the value for every stone i have for the ike stone i will check that whether it is a jewel or not so if it is a dwell it will return out one because for every jewel i have stored the value one and for every non jewel it is by default zero so for any value which is not in the map the by default value would be zero i've told you in the previous video that if the value is not in the map it will return at zero because this is not in the map so that's what we're going to do we will add total of all the stones i had stones the value so we'll send the ice stone in the map and it will return out the value i have the value is 1 which means that it's a joule so we'll add the number of jewels i have in this string s and add it in the total and you turn on the total value or the number of stones or the number of jewels i have in the stone string i have that's a very simple explanation and the very simple question itself from lead code so stay tuned for more videos in this series also next one keep coding bye
Jewels and Stones
encode-n-ary-tree-to-binary-tree
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`. **Example 1:** **Input:** jewels = "aA", stones = "aAAbbbb" **Output:** 3 **Example 2:** **Input:** jewels = "z", stones = "ZZ" **Output:** 0 **Constraints:** * `1 <= jewels.length, stones.length <= 50` * `jewels` and `stones` consist of only English letters. * All the characters of `jewels` are **unique**.
null
Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
Hard
765
97
hello friends my name is Tushar and today we are going to talk about the questions straight into the living problem so the question is given three strings you have to tell if third string is an interleaving of first and second string or not by actually living I mean that if third-straight should be that if third-straight should be that if third-straight should be entirely made up of characters in first and second string and order in which characters appear in first and second string should be preserved for example if I have three strings first string is a B and second is a XY so you have to tell if to return true if this is entirely made up of this and the order in which they appeared here should also they should appear here so let's see here a X a B Y is entirely made up of characters in this tube and the order in which a B appears years of a B and a XY e XY is same so they should return true this is another string a be a XY and this should return false because although it is made up of characters here the order is not preserved so how do you solve this question yes we'll use dynamic programming to solve this question so here I am go to dimension matrix my first here the row column is made up of a B and rows are e XY and I have my third string a X a B Y all right so 0 and 0 is true so let's try to fill up the 0 2 column so when I'm looking at a I'm comparing this Ava this a if this both of them are saying I'm saying is it is true if the guy if the value on the left of me is true so since this is same and this is true so this is true all right if I am looking at this I'm combining second character with this so this is same as this and the value on left of me is also true so this is true X since X is different from B this is directly false all right let's fill up the first column zero column so here a is same as a then this is same I'm saying is the value on top of me is true or not so this is true so this also becomes true now I'm comparing a with X second character here and second character here so this is not same so this is false I'm combining Y with X so they're different so this is false so I filled up my first row zeroth row and 0 to column so I lie on Philip rest of my matrix so when I'm trying to fill up this cell I have two characters here so basically I'm going to compare it with the second character I'm going to come see if this is same as either of this so it is actually same as both of this so in this case what I will check is if this a if since this a is same as this a and checking is if it's the guy on top of me true or not so it is true so this is also true so now I move this by 1 and we move here is this X same as either they say or they say it is not so this is false is this a same as this V or this a this it is same as this it is the guy on top of me true no this is not so this is also false so basically if I have a string a B and a and first four characters to consider here are this first four characters interleaving of a B and E they are not which is why this is false all right let's introduce X so now I have X this is and I'm considering this point so one character from here in two characters from here so here I'm looking at the third character is this X same as this it is so which means that I look at the tall guy at the top of me which is true so this is also true basically I'm saying is I find one character here and two characters here e ay and ax and say a X is in interleaving of a X which is why this is true I'm going to consider the for a and e x so I'm going to look here is this a neither same as this or this it is same as this so if since it is same as this I'm going to see if the catcher or left if the value and left of me is true or not this is true so what did also this is also true since this a and this a are same all I'm checking is this a and this ax same as our interleaving of this or not since this is an inter living of this so adding one more a makes it as a still keeps a to living in quiz so which is why this is true let's try this one so is this be same as this or this it is same as this so am checking is the gum left of me true or not this is true so which is where this is true again this B and this B if we remove them we are left with a e X and that is an intial and this a ax is an interleaving of a yes so this is true and this B acts through the inter living so which is why this is also true let's fill up the last two last row so I'm looking at the fourth character so I'm looking here is this is same as Y or a it is same as a so it means that is the guy on the left of me true no so this is false let's try this one is B same señor y no so this is false let's look at why is this Y same as either this or this it's same as this so I'm saying is AG on top of me true it is true so this is also true so again since this is same as this I'm checking is it does px and EAB make up the danger leave to form the first five characters of this string yes which is why this was true and since this Y is same as this way it will continue to form the internal living which is why this is true so finally this is inner answer yes a B and E XY will interleave to form a x8v why let me quickly write the formula for this one if STR 3 which is our this frame I first J equal to STR one I then I'll say T of I J is equal to if it is then I'm looking at the guide the top so T of I minus one J if str3 I plus J is equal to STR - J then I'm is equal to STR - J then I'm is equal to STR - J then I'm looking at the value on the left so P I G minus 1 for everything else T of I G is equal to false if you want the full solution for this problem go to my github link github calm machine peas interview wiki if you want to check out similar questions go to my youtube channel user to SH all right channel user to SH all right channel user to SH all right 25:25 thanks for watching this video
Interleaving String
interleaving-string
Given strings `s1`, `s2`, and `s3`, find whether `s3` is formed by an **interleaving** of `s1` and `s2`. An **interleaving** of two strings `s` and `t` is a configuration where `s` and `t` are divided into `n` and `m` substrings respectively, such that: * `s = s1 + s2 + ... + sn` * `t = t1 + t2 + ... + tm` * `|n - m| <= 1` * The **interleaving** is `s1 + t1 + s2 + t2 + s3 + t3 + ...` or `t1 + s1 + t2 + s2 + t3 + s3 + ...` **Note:** `a + b` is the concatenation of strings `a` and `b`. **Example 1:** **Input:** s1 = "aabcc ", s2 = "dbbca ", s3 = "aadbbcbcac " **Output:** true **Explanation:** One way to obtain s3 is: Split s1 into s1 = "aa " + "bc " + "c ", and s2 into s2 = "dbbc " + "a ". Interleaving the two splits, we get "aa " + "dbbc " + "bc " + "a " + "c " = "aadbbcbcac ". Since s3 can be obtained by interleaving s1 and s2, we return true. **Example 2:** **Input:** s1 = "aabcc ", s2 = "dbbca ", s3 = "aadbbbaccc " **Output:** false **Explanation:** Notice how it is impossible to interleave s2 with any other string to obtain s3. **Example 3:** **Input:** s1 = " ", s2 = " ", s3 = " " **Output:** true **Constraints:** * `0 <= s1.length, s2.length <= 100` * `0 <= s3.length <= 200` * `s1`, `s2`, and `s3` consist of lowercase English letters. **Follow up:** Could you solve it using only `O(s2.length)` additional memory space?
null
String,Dynamic Programming
Medium
null
316
hello everyone I should be live now and okay I hope everyone can hear and see me clearly if that is the case you can just type yes in the chat box can you guys hear and see me you can okay all good yeah I'm good how is everyone how are you all did you get some time to try your hands out on this question how many of you tried to solve this question on your own okay that's great uh could you come up with some solution to it any approach I'm pretty sure a lot of you would have come so why don't you just mention it in the chat just feel free to write your Solutions in the chat and probably we'll pick them one by one we'll discuss them and then we'll take small steps towards the final solution okay let's do that I'm waiting to read your Solutions okay so meanwhile I'll mention a lot of solutions that I got to hear from a lot of people so I think if you read the question the problem statement is quite clear it says that we are given a string s and we are supposed to remove duplicate letters so that every letter appears once and only once and you need to make sure that your result is the smallest in lexicographic order that's the most important thing so for example let's say uh you have been given a random string which is uh let's say double p a b C so the first requirement is that I don't need any duplicates every letter as you can see here should appear only once so B which is coming for three times should be coming only once similarly uh a it is already coming once so yeah a should also come just once and the other characters also like D and C they should also be appearing only once this is the hard and fast requirement that no duplicates are allowed every character appears only once and on top of that we need to make sure that our result is smallest in lexicographic order so do you guys understand the meaning of lexicographic order what is lexicographic order is same as dictionary order so if you look at dictionary in dictionary the words are sorted correct so for example if you are going through a dictionary which word will come first will you have a word AC or will you have a word CA which one comes first in dictionary AC will come first right it's smaller than CA in terms of lexicographic order so see let us say ah you consider this input itself which is b c a b c right now the first thing that I wish to tell you here is that you are allowed to remove any number of characters correct you're allowed to remove any number of characters but after removal you are not supposed to reshuffle the string you are not supposed to rearrange the characters so what I mean by that is let's say this is what your string is and if you have chosen to remove let's say uh C and B so if you choose to remove this C and that b what will be the result will be BAC correct now you can see it quite clearly that after removing C and B I did not rearrange these characters I did not change their relative positions now what a lot of people do is they also go ahead and change the relative position which is the rearrange so if they rearrange they can easily get something like ABC and they will say that ABC is answer now in this question for the context of this question you are not allowed to do so you can remove as many characters as you want but from the result you can you cannot do rearrangement of characters so this is a very important point to understand uh by the way uh is that making sense how many of you get this point that rearrangement of characters is not at all allowed okay so if you understand this point then a very well known solution that a lot of people come up with will automatically get discarded so I'll tell you what a lot of people say they say that hey what we will do is we will simply sort the string we'll sort the string and whatever will be the answer that will be uh that will be the real answer and in fact one of you is also saying that uh increasing in sorted form so if you go ahead and sort you know first of all we'll understand that why this very idea of sorting comes up in our brain why it comes up because what is a string is nothing it is merely an array of characters correct it's an array of characters now forget about array of characters for a moment let's say you have an array of integers this is your array of integers one seven five four three six now if I ask you to rearrange it in a way somehow rearrange it in a way that you get the lexical graphically smallest value what will you do you will simply sort it sort in increasing order and whatever you will get that will be your answer so going by this thought lot of people are tempted to come up with this solution that hey whatever input I have I will first sort it but given that sorting is not allowed rearrangement is not allowed so this solution will fail you are not at all supposed to sort sorting based solution will not work basically that is the first point to understand I hope everyone gets that right why sorting based solution comes to our mind that is the first thing and second thing why it is not going to work in this case why because rearrangement is not at all allowed okay so um let's think of it in this manner now let's say you have been given an input you have been given string s and for now your string s is a special string which only contains unique characters so I am writing it here it only contains unique characters and that too in ascending order so let's say your string is something like a b n y z something like this in this case what will be the answer can you tell me if your input string is this which contains unique characters which are sorted in ascending order what exactly will be the answer and you can take this as an example can I say that hey the original string itself will be the answer yes or no correct yeah because this is the smallest permutation this is the smallest string that you can get by taking these characters into consideration right so what does it mean it means that if we have a string or for that matter if we have a portion of string which is sorted in ascending order then do not disturb that portion why do not disturb that portion because if you disturb it you will end up getting something which is lexicographically greater for sure correct so if a string is already sorted or a portion of it is sorted then it's good for us in that case there is no work which is needed from our side can everyone realize this point okay now we will go one step further in this so now we will say that okay the characters are sorted in ascending order but there can be duplicate characters also for example let's say a is coming Thrice B is coming twice N is coming once and Y is coming for four times so in this case what will you do how will you solve this question I would say still it is super easy all that we will do is we will just consider one instance of a so we will see that there are three A's which are coming consecutively but we will only take one a in our answer similarly there are two B's which are coming but we will take only one B similarly there is only one n we take only one n there are four y's we take just one y so even this problem can be solved so as long as the characters are sorted in ascending order this problem is very easily solvable but if we have anything random in that case things can go Haywire so let's say this is the string that you have at your disposal and now what do we want to ensure that every letter appears only once so I have to remove certain letters right so can I do something if I just remove this B and C what am I going to get I am going to get BCA now if you look at this BCA every letter is appearing only once inside it but is it the smallest possible value that you could have gotten this is the lexicographically smallest string that you could have generated just think about it the answer is no why because instead of removing this BC how about you remove this BC so if you remove this BC in that case you will end up getting what you will end up getting ABC and that is the smallest answer so now the question is giving us a feeling that hey there can be multiple ways of removing duplicate characters right but some of the ways like this way is giving you a result which is larger than the other way what was the other way was to remove these two characters if I trim these two characters my result is ABC and that is the best possible result that is the result that we all want so now we have to come up with an algorithm we have to come up with a logic which ensures to give us this kind of result only which is the smallest possible result okay just to keep everyone on the same page I'll ask one question that is everyone clear with the problem statement and all these things that I have explained so far yes or no in the meantime I can just read what a lot of you have written in chat box two pointer approach see whenever you say I'll use two pointer approach or sliding window approach or for that matter any approach make sure that you have a very concrete logic behind that why do you want to use two pointers why do you even think that will be helpful so answering such questions will be super important right okay so till now everyone is clear to the question that's great so now we can move ahead okay so let's start thinking about this question uh is always removing duplicate elements from front correct somebody's saying is it always correct to remove uh duplicate elements from the front uh will that be a right idea can I say that it's always a good idea to do that let's see through some explanations okay let's say I have got a random string okay and the string for now has some characters inside it those characters are let's say p q r okay and then let's say you got something like a and after that you have z p Q uh something like this is what you have for now okay what will be the answer in this case what is the smallest possible string that you can get for this case so here a lot of you would say that hey what we'll do is we can see that this pqr is getting repeated so it's better to you know let go of this pqr if I let go of this pqr I will get a z p q r and that looks like the smallest possible string that we can ever get right okay now let's say the string was given to you pick this string up right after picking this string up what you did you considered the first character you consider it the first character you kept it somewhere so let's say you kept it here right now you just move on you move on to the next character is q see the next character Q how does it compare against p is Q greater or smaller than p I mean in English alphabet does q come before P or does it come after p it comes after P right so if you see that you are getting a character if your current character is greater than the previous character that you have in that case there is no harm in keeping it why there is no harm in keeping it because rearrangement of these two things will not do any profit to you if you rearrange this p and Q and you end up getting QP then that will be lexicographically larger so back to the basics what was the basics was that if we have a string or a portion of string which is sorted which is already sorted then you do not need to disturb that okay so once I found that this Q is greater than P I simply considered this Q also without doing any fuss about it okay now let's move on to R how does r compare against Q you see that R is also greater than Q so yeah you will go ahead and you will consider this r right now you come to this a how does a compare against R is a greater than R smaller than r what it is quite clearly a is smaller than r now if a is smaller than R what should I do in this case just think of it in this manner during this point of time I need to check whether this r is coming after a or not because if this r is coming after a that means we can get rid of this r correct because we all know that let us say there is a string which is starting with pqr and then there is a string which is starting with p q a if I call it string 1 and call it string 2 which string is smaller it's string one smaller or its string two smaller string 2 is smaller because p q a any string starting with p q a will be smaller than any string that starts with pqr so the point that I am trying to make is if you get a character like you got a here which happens to be smaller than your previous character that you have chosen and on top of that if this R is coming in the later part then we can kick this character out so I am just writing whatever I have spoken if r current character okay if our current character happens to be smaller than r previous previously considered character which happened here like your current character is a and it happened to be smaller than your previously current character in this case what you need to do you need to check if your previously considered character is coming in future or Not by Future I mean is coming in the later part or not if it is coming in the later part then you can knock this character off correct now the same thing that you did for R you can do for Q also what I mean by that is you can now go on to compare your current character a with your Q so what will happen what will you see will this condition hold true for the comparison of a with q yes or no what do you say is a smaller than Q firstly the answer is yes moreover is Q coming in future the answer is yes Q is coming out in future what does that mean that means we can get rid of this queue and what is the logic behind that the logic is that any character any string that starts with p a and then has Q coming later will be smaller than any string that starts with p q and then has a coming later right now the same thing can be repeated for p also you can say that hey when I compare this a with that P I can say that this a is smaller and on top of that this p is appearing in the future because it is appearing in the future we can let go of this P also and now because it is empty all the characters have been knocked out so I can simply put this a here as it is that's it job done okay now we will move on to the next character which is z how does Z compare with a is it Greater is it smaller it is greater because it is greater we will push it as it is right now come to p what is your current character is B right and what is your previously considered character is z now how do p and Z compare with one another tell me is p smaller than Z yes so I can say this condition is true now if this condition is true can I just knock this Z away can I kick it out because this condition is true yes no will that be the right thing to do not really because we need to check whether this Z is coming in future or not tell me is this Z coming after p no it is not coming after p because it is not coming after P what does it mean we can't kick it because the requirement of the question is that every letter appears once so if you kick this Z out and if it is not coming in the future you will never get that so this condition is super duper important so in this case we will simply push p and move on now we see we have q how does q compare with p q is greater than P so we will push Q how does r compare with q r is greater than Q so we will push R and this way this is the solution that we have gotten this is the smallest uh possible uh smallest possible uh answer that we have gotten here so what is the core idea what is the key idea is that we need to somehow keep track of some facts what is the first fact that whenever we are at a current character let's say this is our current character we need to know what is the frequency of other characters in the remaining part I mean we literally need to know see if you have to know whether Z is coming in the later part or not or Q is coming in the later part or not or M is coming in the later part or not how will you be able to achieve that you will only be able to achieve that if you know their frequencies so the first requirement is that I need to somehow maintain the frequencies of the characters that's the first requirement maintained frequencies of characters that are going to come in the future does everyone understand that why this frequency array or instead of using a frequency array you can also use a hash map it's up to you but why it is needed do you all understand that right okay great now there is a question but if string is aprp in this case answer will be a PRP your answer will not be aprp if you read the question again it says that every letter should appear only once okay duplicates are not a lot yeah you are asking about the duplicates case I'll talk about the duplicates case see whenever uh you encounter a character which you have already pushed somewhere in your answer you can simply ignore that character okay uh how about uh taking some case up and then working away with that so let's say you have I'm just going to alter this string a bit so let's say you did not have this queue here you did not have this P here okay what will be the answer by the way can you guys type your answers in the chat box for this question will there be a separate case for comparing the first character uh not really anyone who could figure out the answer to this okay so while you are think so somebody is saying is that are if you're seeing a z r p q are not there read the question every character should come once so you're not considering p q at all okay somebody is saying p q r a z okay and then somebody is saying uh a p q c after a you cannot have p q you understand that because we talked about it we are not allowed to rearrange the characters we just can't do that how about this p q a z r does that happen to be the real answer okay so let's talk through it okay so what we'll do we'll move ahead and we'll pick a character as our first character so let's say you have picked up your first character that is p now you move on to the next character which is Q so your current character is Q now how does q compare with p is Q greater than P the answer is yes because Q is greater than P you will simply push it how does r compare with q r is greater than Q so you will push this r the segment which is sorted life is very simple with that segment because we don't need to disturb that we don't need to do anything to it right okay at this point of time your current character is a and your previously considered character is r is a smaller than r the answer is yes now is this R appearing in future is it coming in future the answer is yes because it is coming in future can I knock it off the answer is yes now you need to understand why we are knocking it off I'll give you the same explanation that I gave you before because a string that starts with pqa is any day going to be smaller than a string that starts with pqr so knocking this R in favor of that R is a wise decision to make correct are you getting the point so what we'll do is after realizing that this a is smaller than R and this R is appearing in future we will kick this R out after kicking this R out we will repeat the same process with A and Q okay so what is your current character it is still a and what is your previous character it is Q is a smaller than Q yes but is this condition true just look at it and say do you see that this Q is appearing after a the answer is no because it is not appearing so can you kick it off the answer is no you can't kick it off so in that case you will simply push this a over here correct now what's your next character it is z and how does Z compare with your previous character it is larger because it is larger simply push it that's it now move to the next character what is the next character it is R how does r compare with z r is smaller than Z so this condition is true R is smaller than Z but is this Z appearing in future no there is no future here right so you can't knock it off because if you knock it off you will not get it back so in that case you will simply push it this is the idea this is the core idea I hope with help of this and that example you'd have got the gist of basic the most important idea right the most important idea is that if you are getting next character as greater than the previously considered character you can safely push it but if it is smaller then you can knock it off only if the previous character is appearing again in the future that's the idea the previous character was this if it's appearing again in the future we'll talk about the time complexity part all that will happen don't worry about that but is this is the score idea clear how many of you are absolutely clear with this core idea of how to phrase the smallest possible string you can say yes or you can ask questions okay great cool now that we have understood this entire thing uh you know a lot of you were asking questions about hey what to do about the duplicate characters what if our duplicate character is there of course duplicate characters can be there and you have to handle them you just can't let go of them so I would say if there are duplicate characters you don't need to worry at all like let's say you had a last character over here and that character was Q okay so you'd now say that hey now my current character is q and my previous character is r what I'll do is I'll quickly go ahead and check whether this character has already appeared or not if this character has already appeared then there is no action that I am supposed to take okay so this is an important thing if our current character is already a part of our answer then nothing needs to be done so by that I mean we can just simply skip we can simply skip that character okay and you can take any other example also to better understand that so um let's say you have got a c a uh B c d something like this okay in this case you will say that okay let's start with the first character and put it somewhere which is a now your current character is C and C happens to be greater than a because C happens to be greater than a you will simply consider it you will simply push it now you get this a tell me is this any use of considering this a does it serve any purpose although this a is smaller than C and you see that this C is appearing again in the future so if you go by that logic you might want to pop this C off you might want to remove this C off but is there any use of that there is no use because you have already considered an A before so I mean you're already going to get a string starting with AC and that way also you'll go you will go on to get a string starting with AC so there is no purpose of that there is no use of that so I would say that whenever we encounter a current character which is part of our answer take no action simply skip it so the first thing we realized was we need to maintain a frequency of characters now there is another thing also that we need to somehow Ensure I'll tell you what so in this particular case I mean let me ask you what should be the choice of your data structure which data structure would you want to choose to solve this question I mean the way we have the way I told you that we knock off the characters from back and all sorts of things it should be the most ideal data structure stack why should stack be the most ideal data structure let us understand that see I told you one thing let's say uh we are trying to create our answer and so far we have considered these characters pqr now when you get this a you always want to compare your current character with the top most character isn't it and after comparing with the topmost character if you see that it can be knocked out you want to knock it out and then again you want to compare with the next topmost character so this is the journey that you want to take right so whenever you feel like you are dealing with a question where you need to always compare with topmost character or topmost item then stack is the best data structure to use because stack gives you quickest possible access to the topmost element isn't it so what I will do is I'll say that I am going to use a stack so imagine that I am going to use this portion as a stack for now in this stack I'll push my first element which is p correct and then I'll compare this Q with P I will see it is greater so now I'll push Q on top of P now I'll see R is also greater than the top of the stack so I'll push this R so far this is the stack that I have correct now I have got a as a character so I will compare a with the top of the stack and I'll see that my current character a is smaller than the top of the stack because it is smaller than top of the stack so I would want to check whether this r this R is appearing in the future or not if it is appearing in the future that means I can pop it from the stack and pop push all these operations in the stack are order one time operation correct cool now I'll repeat the same comparison of a with q let's say this queue was coming later like in this case you can see that this queue is coming here right I mean your current character is a and it happens to be smaller than top of the stack and moreover the top of the stack is Q which is coming in the future so it means I can let go of this queue also correct now I will compare this with the top of the stack which is p and I'll see that hey although it is smaller than P but p is nowhere appearing in the future so I don't have any right to kick this P away so what I'll do I'll simply push this a inside the stack so guys do you understand why I am using a stack because I always have to compare with the topmost character and I have to pop it and popping from the topmost end happens in order one time in stack and I also have to push at the top so I mean if I have to delete a character I have to delete from the top and I have to insert also at the top that is the reason I am using a stack instead of any other data structure over here it's very intuitive to use stack here of course you can manipulate an array or vector and get the same functionality but if there is an inbuilt data structure like stack which Taylor makes these solutions for you why not use it how many of you understand this point how many of you get it quite clearly that stack is the right guy the right data structure to use here again say yes if you get that okay coming to the part where I told you we need to maintain a frequency of characters for this what we can do is we can just have a simple vector of integers right and I can say that you know I want every character's frequency right now a character denotes an integer in its asci code isn't it and asci codes are in between 0 to 255 so I can say that I can create a vector of size 256 where all the elements are zero okay I can do that so let's say I create a frequency Vector like this it means that frequency of 0 is 0 frequency of 1 is 0 and frequency of 255 is zero everything's frequency is zero now while we are scanning the string we can do frequency of s of I plus so all of you know how to go ahead and create a frequency array right I'll be writing the code for that but don't worry about it I can quite easily do that so once we have a frequency array with us then the job is very easy but however I'll tell you one thing here it says we need to check whether previously considered character is coming in future or not so at any point of time the frequency array should reflect the frequency of future that means if your current character for instance is z your frequency array should say that P is coming once Q is coming once and R is coming once it should not tell you that P is coming twice and Q is coming twice and R is coming twice so we need to somehow keep on updating R frequency array it's very important because if you don't keep your frequency array updated it will not tell you about the future it will tell you about the entire string and it is a very important point to understand that why I am asking you to maintain a frequency array and keep updating that do you understand this part why updating it is required you can say yes or no to it and you will realize it is super easy to do so how let me tell you let us say you are scanning this string if you are scanning this string from here to here once you are at the first character P you can do frequency of P minus similarly when you reach at Q you can do frequency of Q minus basically as you are sliding along this string you can simply do frequency of that particular character minus see once you create this frequency array how will it look like it will tell you that you know the frequency of P is 2 because p is coming twice if I am not wrong similarly the frequency of Q is 2 because Q is coming twice this is the data that it will give you right but if you read this line I told you that at any point of time we need to know the frequency of remaining part the frequency of remaining suffix which is the future so I need to keep on updating my frequency array my frequency Vector so all that I am saying is as you are sliding across this string you need to keep on subtracting the frequency of that particular character so whenever I am at let's say index I'll do frequency of s of I minus it is super important to do it if you do not do it your frequency array will not be consistent with your future do you now understand this point how many of you clearly get it the importance of doing frequency of s of I minus yeah okay so that was a thing which lot of people miss out on now the next thing I told you that if we end up finding a character which is already a part of our answer then nothing needs to be done we need not do anything okay now how do you check whether a character is already a part of your answer or not how do you check that like for example if you go back to this particular input only what did you do you started with p and then you saw that Q is greater than P so you inserted Q then you saw that R is greater than Q so you inserted R now when you are at a you realize that a is smaller than R and R is coming in future so you kick this away now you compared a with q and you found that hey Q is also coming in future so you kicked it away you compared a with P you found p is coming in the future so you kick data away right now the next character was Z it is greater than a so you pushed Z now the next character is p now you need to have a way to easily check whether this p is already a part of your answer or not tell me is p a part of your answer at this stage is it present the answer is no right so how about having a Boolean Vector there can be a Boolean flag sort of thing of the same size 256 which is initially all false and now what we will do is whenever we insert a character in our answer we will do flag of that character equals to true for example if you insert this Z you will simply do flag of Z equals to true so that if in future you encounter Z again you can consult this flag to check whether it is already a part of your answer or not if it is a part of your answer nothing needs to be done also whenever you are kicking the characters away like here you saw after you had inserted pqr and after this a was one by one kicking them out then it was very important to change their flag it was very important to say that hey now that flag of R should be made equal to false similarly flag of Q and flag of P once they are kicked out should also be made false so the important thing is that whenever a character is inserted I need to update its flag to true and whenever it is kicked out I need to update its flag to false because if you had not updated their flag to false once you would have reached this P you would have seen that hey it is still true and you would have been in trouble you would not have considered that so it is very important to maintain this flag array which is a Boolean array and keep it updated do you understand this point that why this flag array is needed for the purpose of this question okay so summing it up overall what we need is we need a stack of characters we need a frequency array and we need a flag array these are the three requirements that we have if we want to solve this question right okay now how many of you uh can you guys take out your pen and paper or you can take out your ID on your computer and try writing the code on your own try writing at least the pseudo code on your own everyone should do that write some pseudo code take few minutes and then after a couple of minutes or so I'll write code along with you give some try to it okay so uh I'll start initializing important things which are needed to solve this question so tell me what was the first thing that I needed a vector of integers which was supposed to store the frequencies right so I'll have a frequency array of size 256. and initially all the frequencies are zero apart from that I'll have a vector of Boolean okay and I'll call it ah taken whether the character is taken or not in our answer and this is also of size 256 and initially everything is false because initially nothing is taken okay now what I'll do is I'll initialize my frequency array and doing that is super easy because all that I'll do is I'll go ahead and scan my string from head to toe has start length I plus and I will simply do frequency of s of I plus now what does it mean by the time this particular code is over I would literally have stored frequencies of all the characters that are present inside this string s inside it right okay the next thing I will do is I'll go ahead and create a stack of care call it SDK for now not a great naming but I'm just writing it all quickly and now to start with I'll push my first character is s of 0. now that I have pushed my first character s of 0 inside the stack don't you think I need to update the value of frequency and taken for S of 0 just imagine your s of 0 is p and if you have taken this p then you need to update the frequency of P that is appearing in the future for that to happen you need to quickly write frequency of s of 0 minus and also to demonstrate the fact that s of 0 has already been taken you need to change taken of s of 0 to true now I can say I have a stack which has been initialized so now there is an item called as P inside my stack imagine this was a stack and you have an item called as p in your stack now you can start iterating from this character onwards so you can start your iteration from index number one so you can write and I equals 1 I smaller than s dot length I plus okay now tell me what needs to be done so I'll write few conditions and you will tell me do you remember this check that if a character is already a part of our answer nothing needs to be done imagine if there was a p after this p then no action was needed right so if we end up finding that if the taken flag for S of I is true if it is true what do I need to take any action no action probably I can all that I can do is I can just do frequency of that character minus and that's it frequency of s of I minus because you know we need to keep our frequency updated and we need to we need not do anything else nothing else needs to be done so this P will simply get ignored that's it okay what to do in the else case tell me in the else case as I told you again let's imagine the scenario when you had already pushed p and then q and then R okay and now your current character was a so if your index was pointing to this a what do you need to constantly keep on comparing this a with the top of the stack and then you need to perform this check and based on that check you need to kick the element out of the stack so I am just going to write a while loop because I need to not only do that thing with r I also need to do that with q and P all the way till my stack becomes empty so I would say hey while there is a condition while ah the top item of the stack well the top item of the stack happens to be uh greater than the current character s of I and as I told you as I explained you I need to check whether that character the topmost character is coming in the future or not so how can I check that thanks to the frequency array I can just write frequency of stack dot top positive so if this condition and this condition both are true then what does it mean can I say what does it mean if both these conditions are true it simply means that yes we can kick that character away okay we can kick that character away now when you are kicking that character away the stack gradually keeps on getting empty right so I'll come to that part but before that I would say that okay because you're kicking that character away so let's do one thing let's say that taken flag for that character which is stack dot top has to be made equal to false that's the first thing and then remove it from the stack see if you're looking at the code I am doing nothing else than whatever I have explained it is exactly the same thing okay now in this while loop I'll tell you one thing while you are doing this operation the stack might eventually get empty when the stack gets empty and during that time if you do stack dot top what will happen you will end up encountering underflow stack under flow so it is very important to check that the stack should not be empty so I need to put a condition while not of Stack dot empty and on top of that so as long as these conditions are true I can keep on eliminating the item from the stack okay and now after this while loop what I can do now finally I feel comfortable enough in pushing the current element what is my current element it is s of I so now I can write stat dot push off S of I and once I have pushed something I need to repeat these two logic because if it has been pushed and if it has been firstly considered then the frequency of the future needs to be updated so I need to write frequency of s of I minus and I also need to write taken of s of I equals to true if you look at this piece of code this for Loop then this for Loop has made short of the fact that only the characters which are unique have been put up in your answer the duplicates are discarded and this particular logic has made sure that the smallest possible item the smallest possible substring the smallest possible string or call it subsequence has been generated so now the thing is that your stack contains your answer your stack contains your actual answer but you know stack has been populated from bottom to top right so it means that let's say if your answer was uh let's say if it was a p q z r then your stack would have had AP Q Z and then R now the important thing is that we construct our string so in order to construct our string what we can do is that we can put all these characters inside the other stack and then from the other stack we will why we are putting inside the other stack because if you put inside the other stack then the first character will be at the top and last character will be at the bottom and then we can create the string by concatenating the characters one after the other so what I am going to do is I am going to just uh go ahead and create a temporary stack for now I'll call it temp sorry the stack of character temp and now I will simply say while my original stack is not empty while not of Stack Dot empty I'll simply keep coming here and I'll say temp dot push stack.top and then I'll do stack dot pop that's it now it means that all these characters have been put in the other stack in the desired order I mean the topmost character would be a then P then Q then Z then R now nothing special is left now we can just initialize a string answer which is initially empty and now one by one we will empty the other stack which is temporary stack so it's a while not of uh temp dot empty simply go here and we will say answer plus equals to temp dot top and then temp dot pop that's it and then finally we can go ahead return our answer run the code check whether everything is good or not and submit the solution it has been accepted so this is how the code finally looks like Okay cool so does it make sense how many of you have been able to relate the idea of code with the algorithm that we have discussed there is a question why did you put stack empty on the left see inside this while loop what are you doing you are emptying the stack once you are calling stack.pop elements once you are calling stack.pop elements once you are calling stack.pop elements are being eliminated so can't read so happen that the stack has been completely emptied when the stack is completely emptied and let's say you do not have this check and during that time if you do stack.top and during that time if you do stack.top and during that time if you do stack.top what will happen underflow because you're trying to fetch something from the stack which is empty so this condition is needed and keep it as a rule of thumb whenever you are writing a code that deals with a stack and does things like stack dot top stack.pop then the first check you need stack.pop then the first check you need stack.pop then the first check you need to have is to check whether the stack is already empty or not right yeah there are multiple other ways it's up to your convenience I mean the core logic was still here after that whatever I have written it can definitely be optimized the most important thing that I wanted to convey was in this part this logic okay great why are you taking first character separately see I need to initialize my stack with something right even if you do not initialize no issue I mean even if you do not do that then this code should run fine but I did that to be consistent with my explanation when I was explaining then I always told you that we always first pick the first character put it inside the stack and then perform a journey with the remaining characters okay let's move on and talk about the time complexity of this part so usually whenever we see that there is a loop which has been placed inside another loop what does your brain say I mean we are tempted to say that the complexities n square or something isn't it yes or no that is what happens we see Loop inside loop we say that it's going to be n square or something but that's not always true and that's not what is happening here if I ask you to find out the complexity here what will be the answer what are your guesses let's say the length of the string is n if it is n then was the time complexity in this case n square or of n what I'll try to explain it to you in the easiest possible way when you look at the stack in this stack all that is happening is either a character is pushed or a character is popped that's on that's all that's happening can you tell me what is the maximum number of times for which we touch a particular character how many what is the maximum number of times it is touched the answer is 2. it is touched first when it is pushed and it is the second when it is popped take example of this string only like you push p you push Q you push R And now when you compare a Vidar you realize that R is coming later and it is greater so you pop this r so the maximum number of times you are touching a character is two times and you are doing push and pop both of them are constant time operation so I can say order two amount of work is being done for each character and if there are n characters then what will be total work it will be nothing but 2 into n and 2 is very small in front of n so it can be ignored and that way we can say that the overall complexity is linear as some of you have said also so order n is what is the time complexity for this problem okay and this is how it can be easily explained and now if you talk about space complexity I would say that yeah we are using a frequency array and a taken array of size 256 but on top of that we are also using a stack now the maximum size of this stack can be order of n right because what if the input that we have is already sorted so in that case all these characters will keep on getting pushed inside the stack one after the other so I would say that the space complexity also here happens to be order of n so both time and space complexities of this question are order n each a beautiful app eition of stat data structure isn't it what do you guys say usually when we talk about data structures like stacks and queues you feel like they are very simple they might not be able to solve harder questions but you see here how a simple data structure like stack has been used to solve a question like this right okay great so ah by the way how many of you have ever studied a concept of next greater element in Array it's a very well known question where somebody asks you that hey uh find the next greater element for every element in an array and you must have used stack to solve that isn't it I'm pretty sure about it did you find this question to be in exact same line as that question I mean the line of thought the design the implementation everything was in the along the same track isn't it and you know so such kind of questions are said as questions that require monotonic stack here also the stack that we created is monotonic only monotonic as per this rule that the characters are appearing in ascending order and only if the frequency of a character is lesser than uh it ends up coming after a greater character right okay great so that's it uh just go back and try writing the code on your own when you write the code on your own then you will get much more clarity of things but uh understand whatever we have used why we have used a frequency array why we have used this Boolean array and of course most importantly why we have used this stack okay cool so I think that will be it for today uh let's see you all again tomorrow with the new question okay bye good night
Remove Duplicate Letters
remove-duplicate-letters
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "acdb " **Constraints:** * `1 <= s.length <= 104` * `s` consists of lowercase English letters. **Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/)
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
String,Stack,Greedy,Monotonic Stack
Medium
2157
134
hey guys welcome back to another video and today we're going to be following the lead code question gas station all right so let's start off by just reading the question and then i'll explain what the question actually means okay so in this question there are n gas stations along a circular route where the amount of gas at the station i is gas at index i you have a car with an unlimited gas tank and it caused cost at the index i of gas to travel from station i to the next station i plus one you begin your journey with an empty tank at one of the gas stations return the starting gas stations index if you can travel around the circuit once in the clockwise direction otherwise return negative one okay so uh one more thing we really want to notice is that if there is a solution there it is guaranteed to be a unique solution okay so let's start actually visualizing what the question means and try to understand so this over here is the same as example one over here so this is the gas this is the cost and we have the same values over here so now what i'm going to do is i'm going to create one more thing over here call the station so this is going to represent each of our gas stations so where our stations are going to start off at zero so we have station zero then we have station one station two station three and station four so what exactly does this mean so let's just go by this one by one so let's say we're at station one so once we go to station one the amount of gas we get from station one is equal to this over here so we go to the first index of gas which has a value of two and that is the amount of gas we get at station one so we get two liters of gas okay but now if we're at station one and we want to go to station two the cost the amount of gas is going to take us is going to be four so in other words let's just say it costs us four liters to go from station one to station two uh one more quick example let's say three so this value over here is going to cost the amount it takes to get from three to four and this over here is going to tell us how much gas we get at station three so that's pretty much it for the question and one more thing is let's say we start off at a station two so that means we start over here and what that means is we want to go over here then here and then all the way back over here since it's a circle then over here and finally we would end up over here that is going to be considered a full circle and in that case we do not want our tank has to end up by being empty or more than empty it has to have more than zero liters of gas in order to be a valid answer and if it's not a valid answer then in that case we return negative one so now that you understand what the question actually is let's see how we can actually solve this and i'll be looking at the same example in this case so over here we're going to have three different variables that we want to consider so over here we're going to have a variable called the start variable so this start variable over here is going to be the gas station at which we're going to start our journey at and in the beginning we're just going to start our journey at the zeroth index so at station number zero so we're going to be starting from station zero over there so over here we have one more a variable called tank so tank is gonna correspond to how much gas do we currently have inside of our car's gas tank right so in the beginning when we're starting off we have zero liters of gas and finally we're going to have one more variable called shortage so shortage in other words is going to be how much tank how much gas are we missing in order to get to the next station so let's say we don't have enough gas and we are missing let's say one liter of gas that is going to be our shortage value so this is going to be a cumulative value which we're going to add on as we go so this is going to be the best solution since we're going to be going through our list only one time so this is how it's going to work so first we're going to start off at station zero and at station zero we're gonna fill up our tank with one liter of gas so now our tank has one liter of gas since we added one so now in order to get to station two it's going to cost us three liters of gas but we only have one liter of gas it is not possible for us to use to get over to station 2 with just one liter of gas so in that case what's going to happen that means that starting at station 0 is not a valid answer so we're going to add this value the shortage of gas to our shortage variable and also one more thing this starts up at the value of zero okay so what is the shortage gonna be so we currently have one liter but we need three liters so there's a difference of two liters so that is going to be our shortage three minus one ending up uh giving us a value of two and we're going to add two plus zero giving us a shortage value of two now we know for a fact that station zero is not a valid answer so now we're gonna change our start position to the next station so instead of zero we're going to start off at station one so that's our new start position and our tank is going to reset to a value of zero since we're just resetting everything and now i'll just go through this a little bit faster so at station uh one currently out uh we fill up with two liters of gas so now we have two liters of gas in our tank and but in order to get to the next station we need four liters of gas and we do not have four liters of gas so that gives us a shortage of four minus two uh giving us a shortage of two liters we need two more liters in order to make that possible so in that case uh we're gonna add that to our shortage so two plus two now has a value of four and we also know that starting at station one is also not a valid answer so we're gonna change our start to station two and our tank is gonna reset to a value of zero again so now we go on to station two over here we get three liters of gas so that becomes the value of our tank three plus zero and to get to the next station we need five liters again we do not have enough gas so that's a shortage of two five minus three ending us with a value of the shortage equal to six okay and now we gotta do the same thing again we change our start value to the next value so now we're starting at station three and our tank is now going to have a value of zero again okay so now at station three we start off we get four liters of gas so now our tank has four liters and to get to the next station it costs us one liter but what you want to notice is that this is possible we have four liters and we only need to give out an extra one liter so we can do that trip right so in this case what's gonna happen we're just gonna subtract the one liter of gas inside of our gas tank so that is going to end up giving us four minus one so now our tank has a value of three and we do not have any shortage since we were able to make the trip and we're going to leave our start value of three because so far it has been working out so now finally we go on to the next value over here and at the fourth station we get five liters of gas so now our tank is five plus three and it has eight liters of gas in total and in order to go back to the first station over here since it's a circle it is going to cost us a total of 2 liters of gas so that is going to be 8 minus 2 and our tank now has 6 liters and the reason we subtracted from the tank is because we are able to make that trick so this is going to be the ending of our solution but what does this actually mean how do we get the solution from this so at the ending we have a start value of three so that's telling us that we can start at station three then we have a tank which has six liters of gas currently and we have a shortage of six so what does this actually mean so shortage if you recall is let's say we collected one liter of gas here and the shortage to get to the next station was 2 liters right so 3 minus 1. now what you want to notice is currently when we're starting off our trip again from over here we already have 6 liters in our gas starting off from and we're not counting the amount of gas which is over here since that gas is already accounted for in our shortage so if this value of 6 is equal to our shortage or greater than that means that our trip is possible and we can make a full circle if that still doesn't make sense let's just go through this real quick so over here in the beginning we have 6 liters so now we add 1 so we have 7 liters 7 minus 3 is 4 so currently we have 4 liters then we get two more liters so we have six liters and six minus four ends up with two liters in our tank then we get three liters over here so that gives us five liters and five minus one is zero so at the ending once we get over here we end up with zero liters inside of our gas tank but there's no problem because we start off again with four liters over here so that is what the shortage means and our tank must have a value greater than or equal to the value of our shortage only and only then are we going to be able to give out our start value as a valid answer or else in that case we're going to end up resulting negative one if our tank is not greater than or equal to our shortage and one more thing you want to notice is let's say we kept going on with this there might have been a point so our start value is always i plus one so let's say we did not find a proper start value and we went to the very ending over here and in that case our start value would have given us a four plus one right so we would have a value of five and when you have a value which is equal to the length of our gas area that means that we do not have any proper starting point so we in that case that means that we're not able to make a single trip and when we're not able to make a single trip we will never be able to make a round trip so that's exactly what that means and that is going to be another condition which if that is the case so if the start value is equal to the length of our gas then in that case we're also going to end up outputting negative 1 in the case that it is not possible so now let's go on and look at how the code part of the solution is going to look like all right so let's start off with our code over here and we're going to start off by initializing our variables so over here we're going to have our tank variable which has a value of 0 then we're going to have the shortage variable which also starts off at zero and finally we have the start so we're gonna start off at the index of zero so we're gonna start off at station number zero okay so now we wanna iterate through each of the values inside of our gas so to do that we can do for index and range length of gas okay and the reason we're going through it by index is because then we can refer to that index for our cost area okay so over here the first step is going to be to fill up our tank of gas so we're going to add the amount of gas so gas and we're going to go to the index and add that to our tank so currently we have that much gas and over here we're going to check if the amount of gas we have in our tank is greater than or equal to the cost at that certain index so if it is greater than or equal that means that we are able to move go on to the next gas station with the current amount of gas we have so in that case all we're going to do is we're going to decrease that cost from our tank so that means that we used up that certain amount of gas in order to make the trip to the next station and now over here we're going to have an else condition so else means that we do not have enough gas to move on to our next station so in this case what's going to happen is we're going to add a value to our shortage so our shortage is going to increase by the current cost that we're on so cost index and we're going to subtract that by whatever value we have in our tank and the reason we're doing the cost index first is because since this is not true that means that the cost is obviously greater than our tank and by doing this we end up getting a positive value or you could do it the other way around and just get the absolute value of that okay so that is what we're going to add to our shortage because we're this many liters short in order to get to the next station okay so that's going to be our shortage and over here we're also going to change our starting index and instead it's going to be index plus one so we're going to start off at the next station so if the zero station didn't work out we would now start off at station number one and finally after this we want to reset our tank to the value zero and that's really it for our for loop and over here we want to check if the start value we got is valid or not so how can we actually check that so over here we're going to check if our start value is equal to the length of gas so if it is equal to the length of gas that means that we were not able to cr go through even one trip we weren't able to make a single successful trip and in that case we're not going to uh get a proper answer and we're just gonna end up returning negative one and over here we actually have one more condition for when it could be negative one and that is if our tank has a value which is less than whatever the shortage is so if we have a value less than our shortage for the coming trips we will not be able to fulfill how much of a shortage there is in order to complete a full circle so our value has to be equal to or greater than the shortage so that the starting value in our tank compensates for that shortage okay and that should be it so that's if we have uh any of these we're going to end up returning negative one but if that is not the case that means that our answer is valid and we're going to just return the start variable that we have and that should be it so let's submit our solution and as you can see our submission did get accepted and finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe if the video helped you thank you
Gas Station
gas-station
There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`. You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique** **Example 1:** **Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\] **Output:** 3 **Explanation:** Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index. **Example 2:** **Input:** gas = \[2,3,4\], cost = \[3,4,3\] **Output:** -1 **Explanation:** You can't start at station 0 or 1, as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. Therefore, you can't travel around the circuit once no matter where you start. **Constraints:** * `n == gas.length == cost.length` * `1 <= n <= 105` * `0 <= gas[i], cost[i] <= 104`
null
Array,Greedy
Medium
1346
6
okay question six leak code zigzag conversion the string paypal is hiring is written in a zigzag pattern on a given number of rows like this you may want to display this pattern in a fixed font for better legibility and then read line by line so we have p a h n etc so we need to convert this string into this so going down zigzag down z exactly so initially this seems like a very complex question but if you just think about it as an elevator of sorts where you're just going down and up as opposed to diagonal then we can create some kind of array to store these values and then just have a true value for going down and a false value for going up so let's jump into the explanation so we're going to have some kind of direction flag when it's true it's going to go downwards and when it's false it's going to go upwards right so we're going to have some kind of array to store our results so we can have array and the hard part here is we need to initialize the array with something that would separate three different zones we need to separate here and here we could use arrays for these so each one would be an array the only issue with that is the space complexity and then at the end we're going to have to join this so we could use reduce or map and it just becomes quite complex in terms of time or we could just use three different strings so for this we have um rows is equal to three so we could just have the array initialized with the number of rows as strings so it looks something like this we also need a count variable which we'll put up here and this can be initially set at zero and this is what's going to determine when we need to flip the direction flag so say the direction flag is true once we reach this value here so this is two so once count reaches two we then flip the flag and turn it to false and then we go back up so let's run through this example so we're going to loop through this string right so we start off at p we add p to the array at count of zero so p goes in here we check if count is equal to zero or count is greater than or equal to nums at row minus one because that's going to give us 2 and that is this value here once that happens we turn back at this moment we're going to go forward so we move over to the next one so we increment count here so count goes to 1 direction is now set to true and we move over to a is at one so we push r into count of one so that's going to be a goes in here we check if count is greater than or equal to num's row minus one it's not so we increment count because direction is true then we move on to the next one why we add y into array at two we check if count which is at two now is equal to num zero minus one it is so we change direction so we go to false now when direction is false we just decrement count so count goes to one now we're on p is added at our count we check if count is equal to num1 or count is equal to zero it's not so we can decrement count and move along red a can be added to r at count zero we check of count is equal to zero it is so direction is changed to true then we increment count back to one l is added here so r at one we check there's nothing to change here we increment count and we move along we add i in here we do the check count is equal to nums at row minus one so we flip again so this becomes false we decrement count we move to s we add s in here we do a check nothing changes we decrement count we go to h is added here we do the check we need to convert direction to true and we increment count move over to i is added in here so i'll put this under here because we're running out of space we do the check nothing to change we add to the count we move over to r is added here we do the check count is equal to nums at r minus one we change direction to false and then we decrement the count to one so we move to i goes here we do the check nothing to change we in we decrement count we move over to n is added in here count is equal to zero so we need to change the direction so direction goes to true count is incremented to one and then we go to g and g is added in here and then we finish the loop so after this is done we just need to join this array to form a string so if we join it with r dot join we are going to get b a which is the answer we're looking for now in terms of time and space complexity we have one loop which is going over this string so time complexity is o of n and space complexity is also over n where we're storing all of the values of the string within an array so firstly let's have a look at the constraint see if we have any edge cases we need to handle we do so if num rows is equal to one or s dot length is less than num rows return s so if nums at rows if the number of rows is equal to one well then there's only going to be one string right and then if s dot length if the string length is less than the number of rows well we aren't going to be able to create that number of rows that they're looking for so we can just return straight so we need the direction flag we need the count and we need to create that array we populate it with num rows and we're going to fill each one of those with an empty string now we look through the string let's extract the current value to make it a bit easier to read so firstly we need to add current to the string at count so it's going to be r at zero and if count is equal to zero or count is greater than or equal to none rows minus one we need to change the direction and this is really important because at this moment in time direction is false so we need to convert that to true because we've added into the array now the current value we need to convert this to true if we set it true to begin with what's going to happen is we're going to meet this if condition right here and then it's going to flip it and that direction is going to become false and then we can go to minus one so we don't that so we need to initially set direction to false that way when this converts it's going to set to true and it's going to trigger this chain of events the last thing to do within this for loop is to check whether direction is true or false if it's true increment count if it's not decrement count it's a very similar to an elevator right so going up and down forget about the diagonals just simplify it to up and down and then we can return r.join and that'll convert it into a string let's give this go submit it and there you have
Zigzag Conversion
zigzag-conversion
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); **Example 1:** **Input:** s = "PAYPALISHIRING ", numRows = 3 **Output:** "PAHNAPLSIIGYIR " **Example 2:** **Input:** s = "PAYPALISHIRING ", numRows = 4 **Output:** "PINALSIGYAHRPI " **Explanation:** P I N A L S I G Y A H R P I **Example 3:** **Input:** s = "A ", numRows = 1 **Output:** "A " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. * `1 <= numRows <= 1000`
null
String
Medium
null
394
hello everyone welcome to another episode of the blasphemy by uh my name is atul john and it's been a long time since we did a video so i think it's time for us to get back on track and start working on some problems right so just a couple of things that are going on in my life i recently uh took up a role with cisco i'll be working as a software engineer in the enterprise access point team uh it's pretty exciting role i've been interviewing for some time right now and i've finally got the job role that i wanted another thing that you'll notice is that the uh the video quality has improved so i got a 1080p full hd webcam so you'll be able to see my face a little bit better also i got a brand new uh desktop pc it's an aurora alienware aurora r12 gaming pc but i'll probably be using it more for video editing rather than gaming and you can even see it right now so the background has changed uh it's because uh the graphics card is uh there's a there's an application from nvidia called media broadcast where they you can put change the background and that goes into obs so this does a better job than what obs does with its green screen so i thought i'd just uh try it out so yeah that's about it uh thank you so much for staying with uh with the channel and i really hope to do a lot of good things uh hopefully get out at least one video per week uh we'll focus most uh mostly on the concepts of solving problems rather than just going into the code but definitely the code will be there for you for everyone to look at anyway with that said uh thanks for being here welcome back and let's get started hey everyone so let's get started on this question so question is uh number 394 on lead code um it's actually a google ask question so yeah let's get started it's called decode string and you can see the question over here it's basically saying that if you've got an encoded string you have to decode it and return the decoded value so i'm not claiming that i came up with the answer i'm just looking at the lead code solution that i found was good so uh let's get started and look at that right now uh the question basically is asking you if you're given the encoding rule is basically like k encoded string where the encoder string inside the square brackets we repeated k times now yeah this doesn't really make sense so let's uh look at the examples and let's try to figure it out so for example if you've got 3a to bc you're going to have 3 uh divide uh you use the kind of like the uh rule where you start from the left and go to the right you've got three a's and you've got two bc so you add the three a's and you had the two bc's and that's that we can look at the other examples we i'll just go through them quickly so that you get an understanding of what the question is uh asking of you okay let's look at these examples and uh see if we can make sense out of it right so the first one is going to be uh 3a uh 2bc and i think we've already looked at that one so this you can because you just have one single bracket i guess you can evaluate them all together so this would be a okay let's do it separately so a and two bc uh and then we're going to do aaa and then it's going to be bc and bc uh similar story here we will try expanding things that are inside first so we would get 3 a cc and then we expand that again we would get acc and c um look at this one here uh yeah this is pretty straightforward let's not spend too much time there so abc cd and ef uh finally the last one it's also pretty straightforward so we get a b c d and x y and z so basically the question is something like um like this in some sort of format like this over here where you have a k constant value and you have a string right so uh in this example over here k2 or string 2 would be repeated k2 times and then string 1 and this whole thing that we evaluated here would be done k1 time so that's basically the question like this is how you get the question the input would be coming in this format and we're going to use this input and then try to decode that moving on so we're going into the solution and the solution is going to be using a two stack solution so we're going to have two stacks uh one is going to be for the count stack which is all of your k1 k2 k3 values and then you're going to have another string stack which is basically going to be your string 1 string 2 etc now we're going to have two different stacks as i mentioned and you can just remember the name uh it's going to be we're going to use the same name itself so it's one is called the count stack and the other one is called the string stack and i already mentioned like what we're going to be keeping in those uh in those stacks moving on to the algorithm and everything basically boils down to uh to this algorithm over here uh you can code this up directly like it's pretty straightforward you can do it uh do it by just following these so different cases case number one let's see what case number one is case number one basically says if you're getting a digit okay that's going to be appended to your current k value right so we have to populate the values of k1 k2 or not so let's say you get a value 20 okay um you have to stop it when you get something other than a digit so as long as it's a digit you have to keep it appending to it so for example you have a value 15 right so you will get one first and then you will get five first so when you get uh one first your k value would be one initially and then when you get this uh five when you count the five next time what you're going to do is you know multiply k with 10 and add five or k was k so in this case k is one so you would get 15. so that's how you would uh take that but now that's just a minor thing we don't have to worry ourselves about that case two if you're getting an actual digit so that's going to be part of your string right like if you're getting a value uh abc uh that's going to be your string so every time you get a string you have to keep appending to your current string so now this is something that i wanted to highlight a little bit uh this current string guy um it's going to be it's going to come up a couple of times this current string guy and i want you to notice that current string does not necessarily mean the string that's there right now like for example in this case over here um maybe you could say that abc is the current string but it could also be that your current string is um let's say the evaluated part of this whole thing okay this could also be your current string i mean when you look at the code and go ahead and go through the algorithm you'll understand that has a significant importance so it's not just that small part of the string it can actually be an evaluated part of the string that's going into the current string so yeah you append that to the current string we'll go into that um and the next one is if you're getting an open brace okay open braces are the cases where you have to do some um uh some computation right so far we've gotten either digit or um or an or a string and then now finally we've gotten some opening braces so we have to evaluate some part of that inside and what we do is we take k and we push k into the stack so we create two separate stacks one which is an integer stack and another one which is a string stack which will keep track of all of our strings right now and we're going to push the k uh into that and we'll also push the current string into the stack okay and then we will also do one more thing which is we're going to reset the values of k because we've already uh computed the value of k so far like for example in our previous example we saw 15 which is the value that was computed so far so that whole thing you know going to put it into the stack similar thing with the current string so i told you like constrain it could not probably it's not just an abc it can actually be an evaluated part of abc so you have to take care of that as well now finally the last case is basically the part where you get a close break and that's where you're going to do the bulk of the work where you're decoding your actual uh actual value actual string okay now let's go into the decoding part a little bit now decoding is where it starts to get fun right you are going to take all of your stuff and you're going to start popping stuff out of the stack so you've been pushing some stuff into the stack now it's time to start using those values like um so far we've really been dealing with uh manipulating dealing with trying to get the values out of the stack we've not looked at the part where we want to use those values that are in the stack so that's where we're going to do so that's why i have a happy smiling face over here that we are actually going to do some work over here so what we do is we are going to pop the kx or the top uh the top k value and the string uh that's the current string basically so this would this is actually not just the uh string at the top this would be your current string okay so whatever is current right now that's what you're going to multiply so when you go into an example that will be understandable like you can understand what i mean by that so basically you take the constraint you have and then you multiply that uh how many other times that we have it in the stack and then what we do is we append that into the decoder string so decoder string would be this really the big thing that we need right yeah so and then to find the decoded string we've already found out the k string right like you found out a big really big i mean not a big thing like a subset of uh what we want over here right now you use that and add that to the decoded string okay now when you go into the example you will understand what decoder sling is so uh every time that you want to add uh the k dot string uh you will just add that to the decoder string okay let's go into an exam into the example so it's a little bit more clear so right now what i have here is two string two stacks so one stack is account stack which is an integer type stack and i've got a string stack which is obviously a string type of stack and then i'm going to keep track of something called the decoded string okay and k is just the current k value so the current k value and the current string those are the two things that i'm going to look at now uh going back to our algorithm you guys remember that you remember that depending on what value we get we're going to do different things right so the first one that we're going to do is uh depending on the value that we get so the first thing that we're getting is a three right and that is going to go where uh right now it's going to stay in k so k starts with zero and current string starts with the null string you can say like an empty string and when you get three you put three into there into k and then the first time that you get a are you getting well what are you getting here now you're getting a let me take a different car so we finished 3 and now we have this guy over here uh what do we do with that guy we're going to do something we're going to push k into the count stack and we're going to push the current string into the string stack okay so right now when you look at the stack it's going to look something like three and there's going to be another over here i mean there's basically nothing there right that's how it's going to look right now and then the next uh yeah after we do that we are going to reset our k and current string so k would go back to zero and constrain would stay as null okay that's gonna that's good that's how it will be at this point next we get a so at a what we're going to do when you get a you're going to append a to current string so right now your current string would be a okay and then next what do we get you get a value uh two so we've extinguished two a and now we're going to extinguish two so when it comes to two we're going to multiply k 10 times so that's 10 times 0 is 0 and then add 2 so currently the value of k is going to be 2 for us okay moving on you get you're going to get another left brace so what are we going to do here we're going to push k into the stack so that's going to be 2 over there and you're also going to push current string into the string stack so you have that over there and then as earlier we're going to reset our current string and k so k goes to zero and your current string is going to go to null next what do we get you get b right when you get b you're going to add that into your current string okay so you're going to append it to this guy and then what you're going to get is basically b you're going to get b over there okay after that you're going to get another digit sorry another character over there and that's also that's going to get appended so you get b c over there okay now is a beautiful part right the decoding part is going to start happening let's see what happens over here okay when you get a close brace what you're going to do is you're going to take the current string and we're going to start adding it to the decoded stick and now the way we do that is we're going to pop whatever element is there in the stack into the decoded string so that our decoded string right now will be a right so i have painted that blur there so decoded string oh my god so decoded string would have a right now and then you would pop that value out of there nothing is there right now and then what you're going to do is we're going to look at the value that's there in the stack of the count stack so we here the value we go and check and we see the value there sorry we see the value there is 2. so what do we do with this 2 so we have the decoded string and we have the current string what you basically do is we're going to do a plus two times of the current string so the decoded string is going to be whatever is there at the top of your string stack and then you're going to add the current string the number of times that's there in the stack so the reason why we're doing this is because we know for a fact that once we've reached an end point whatever string that we've found so far like the current string that we have so far that has to be multiplied by the number that's at the top of the stack so we've not so far put the current string into the stack but we know that the count stack has a number of times that our current string has to be appended so at the end of that iteration what we have in the decoded string is going to be a bc okay and then you can um pop the count stack we are all done with that now a very important thing that you have to talk remember so remember i told you that current string not just contains the small subset of the string it can also have the partially decoded string so the last step of doing this decoding is going to be putting the decoded string into the current string okay that's going to be the important last step that we have to do so what happens there i'm going to take a b c and where we're going to put it into the last into the current string okay so now decoded string yeah decoder string is still there it's fine and finally when we reach the last guy the last uh closing brace what are you going to do we're going to follow the same process what are we going to do we're going to put decoded string as the last thing in the stack so what is the last thing in the string stack it's going to be a null uh null string so what do we put there you put null there okay and so and then you can pop the stack out a string time can be popped out and next what you're going to do is to the decoder string you're going to add the current string how many times whatever value is there in the count stack let's pop it out and then as many times we're going to add the current string so let's what do what happens over there so we're going to get basically three multiplied by abc bc and when you evaluate that's going to come up to uh abc abcbc abc bc sorry abc bc so that's going to be your final string and finally there you are done with things like this nothing else to process in that input state so you just print out without the um now what do you print out at the end actually so once you're done with the decoded stack you're actually going to put that back into the current string like that's the step that we followed last time so we'll follow the same thing here and we're going to put decoder string into the current string at the end of the uh at the very end we're going to return current string that's basically it now we can take a look at the code uh to show you the part where we are um creating the decoded string and the current string like that kind of that part it's just a little something that i wanted to look at let's quickly go ahead look at that okay so here is the code and this is the part where we are decoding the string right so we've received a closing brace and then we're going to pop whatever is in the string stack into the decoder string once you know once you have the top you can pop that out and then you know that count stacked on top will have the value that you want to um repeat the decoder string by so just have a small for loop to do that once you're done using the count stack.top value you can just pop that stack.top value you can just pop that stack.top value you can just pop that out finally the very important thing that you have to put it back into the constraint in the next iteration that's going to be helpful right that's going to decide how what string you're going to repeat okay and then finally at the end you're going to return that string uh one more thing that i want to look at is the time complexity so let's quickly go over that as well so looking at the complexities uh what we see is that assuming that you're given a string s that has a length in so this n means both uh it'll include everything like the number it can have digits it can have letters it can have parentheses you can have everything okay so for time complexity we're going to use that n over there and what we see is that so yeah i remember earlier i mentioned about k1 times string 1 k2 times string 2 and so on and so forth so how many times do you repeat k is a factor of the k1 k2 so whatever is the k max value let's say it's 10 okay and the length of how many times you repeat that thing in the worst case it could be that you're repeating the whole string n times now um i don't think that can happen because it'll be a little bit lower than n because you need some part that's uh that's reserved for k right you can have the whole thing have just the letters so that's the time that it takes to uh repeat the because you have that many times of times that you are repeating that so that's why you have k of n uh k max into n times similar thing with the space but here the end is something different i'll explain that now uh in space so you have two different stacks right so the m is going to represent the stack for the number of letters in the string okay and n is going to be for the number of digits in the stack now uh if you looked at uh the example that you were doing we only had like sub parts of all of the strings right but in the worst case scenario we could probably have a situation where all of the letters in that string have to be put into the stack okay so in that case if you have m characters in the string you have to put all of that into the stack but the same thing with the digits also like if you got like a really long digit like uh 10 506 or something like that you'll have to put that whole thing into um or i think number of digits might be yeah so you might have to put that whole thing uh already like say 10 000 uh 1542 or whatever that has to go into the stack so that's how you get like that's the largest one so that's basically the whole question i hope you enjoyed the question uh definitely look at the solution in lead code there are probably better ways of doing this but this is a very straightforward and easy way to do this question and sometimes it's better to like a straightforward way rather than looking at like really complex space that will take you ages to explain to someone like you have to go with a solution that works and that's um that works reliably that's pretty much it that you'll have to look at yeah thanks guys uh welcome back and thanks for being here i hope you understood and enjoyed the session and have a good day take care
Decode String
decode-string
Given an encoded string, return its decoded string. The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`. The test cases are generated so that the length of the output will never exceed `105`. **Example 1:** **Input:** s = "3\[a\]2\[bc\] " **Output:** "aaabcbc " **Example 2:** **Input:** s = "3\[a2\[c\]\] " **Output:** "accaccacc " **Example 3:** **Input:** s = "2\[abc\]3\[cd\]ef " **Output:** "abcabccdcdcdef " **Constraints:** * `1 <= s.length <= 30` * `s` consists of lowercase English letters, digits, and square brackets `'[]'`. * `s` is guaranteed to be **a valid** input. * All the integers in `s` are in the range `[1, 300]`.
null
String,Stack,Recursion
Medium
471,726,1076
303
all right let's talk about range some query immutable so given integer array numbers handle multiple query of the following type so you have the class num3 and you need to know there's a constructor and initialize it in array and also the sum range which takes two argument which is left and right so you have to return the sound of the element of the nouns between in this left and right in inclusive right so uh there is an easy way so you create an array and then you copy the nouns to the in array and then you try verse using a for loop and then return the in value this will take all the fun because uh for every single time you call some range right it takes all of them right and there's an easy way to do uh minimize the time complexity to i mean on some range to one all of one so you can use presump so prism is really important this is actually like memorized what is the current i mean what is the previous sum for this current position so if you just write out on your paper and then you will be able to know the first index is negative to the second index which is one is negative to you and the third the next one will be negative two plus three which is uh one right one plus negative five negative four plus two uh negative two plus uh plus negative one which is negative three and this is really important to have a previous sum and then you will be able to know like what is um uh what is the time complexity for the sum range this one only takes all of one right so let's just traverse so before you traverse you need a pre-song is to go to new uh need a pre-song is to go to new uh need a pre-song is to go to new uh new ins and then non-stop lens and then pull in we don't need to know the uh there is some that in this video this is because uh i will tell you later so that length left click plus and read some right like i which is one i'm going to add my value uh in this itemized ones value plus the nums i minus one so this will actually know that what is the uh value for list in the rate the previous sample in array so you have to know like you need extra space for recording the last one so we're starting from the first index so we basically like uh taking every element and then move to the right i mean the sum of the elements right and for the sum range right since uh we only need all of one right we just can return what so we look at this example so uh this will become for the previous sound factory sound and i'm going to give you more space for this so uh favorite sum for the index 0 which is 0 you are not initially so negative 2 negative two comma one comma uh negative four comma negative two comma negative three so it does take uh extra space right for our favorite sum and you when you need to return imagine you return zero to five when you return you have to return this index right zero to five so what is zero to five um the sum of the array so this will become negative two plus three one plus negative five negative four plus two negative two plus negative one negative three correct so in this case you can actually just return negative three but did you actually notice there is the value for negative three so this is now calling coincident you need to uh you need to actually get a value from quick sum and then red plus one and then minus through some left so you don't actually need to plus one or minus one on the left index because this is actually um the presence actually indeed indicate like the value you stored in the i mean before this current position so i mean we can actually test two and five is actually zero one two three four five right so this is actually like three plus negative five negative two plus two zero negative one right so negative one so two and five so i would use right is 5 plus 1 is 6 so negative 3 minus 2 0 1 2 which is negative two minus negative two is uh negative one right so negative three plus two is negative one and this is how it is so they just run the code and see if i have any type of enough yep okay here we go so for the time and space complexity so you have to narrow down the sum range time capacity layers but normally the space complexity is all the one and the time for the sum range is all the one which is the base solution and if you want to know that all the fun solution this is all of the solution you try versus every single time you call it some range and you return the value and this is all of them which is actually more poor in performance on the equation and the function so this will be a solution and if you feel helpful subscribe like if you want it and i'll see you next time bye
Range Sum Query - Immutable
range-sum-query-immutable
Given an integer array `nums`, handle multiple queries of the following type: 1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initializes the object with the integer array `nums`. * `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`). **Example 1:** **Input** \[ "NumArray ", "sumRange ", "sumRange ", "sumRange "\] \[\[\[-2, 0, 3, -5, 2, -1\]\], \[0, 2\], \[2, 5\], \[0, 5\]\] **Output** \[null, 1, -1, -3\] **Explanation** NumArray numArray = new NumArray(\[-2, 0, 3, -5, 2, -1\]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` * `0 <= left <= right < nums.length` * At most `104` calls will be made to `sumRange`.
null
Array,Design,Prefix Sum
Easy
304,307,325
1,644
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 1644 lowest common ancestor of a binary tree 2. let's read the question prompt given the root of a binary tree return the lowest common ancestor lca of two nodes p and q either node p or q does not exist in the tree return null all values of the nodes in the tree are unique according to the definition of an lca on wikipedia the lowest common ancestor of two nodes p and q in the binary tree t is the lowest node that has the both p and q as descendants where we allow a node to be a descendant of itself a descendant of a node x is a node y that is on the path from node x to some leaf node okay so we've read the question prompt and we need to make note of one important detail that either node p or q may not exist in this tree whereas in lowest common ancestor of a binary tree you know one we were guaranteed to have p and q in our tree so it did make our solution a little bit easier this question is a bit harder because we do have to account for the fact that nodes may not exist let's look at some examples so we have this tree here and we're told that p equals five and q equals one so five and one we can see the lowest common ancestor is going to be this three right because this is the first point where they converge when going up you know up the tree so that's how we get three what about if p equals five and q equals four so it's this node and this node so as we can see it's going to be five because this is the first point where they converge and remember that a node is allowed to be um you know a descendant of itself so that's why five would be the lca here because it's going to be the lowest common ancestor for this four and it's an lca of itself so this is the first point where they converge now let's look at the interesting case of p equals five and q equals ten so we have this node five but we can see in our tree that there's actually no 10 in the tree um and oops i made a mistake here this should not be to return 10 we should just be returning uh none here because actually you know 10 is not in the tree so therefore we return null in the case when one of the nodes is not in the tree so you know there's two ways to solve this problem and the first way is going to be the naive solution which is going to be that you're going to traverse the tree you know to make sure that both nodes are in the tree so basically you want to traverse the tree make sure that p is there and q is there if either one of them doesn't exist you can return none if they both exist then you could use the algorithm that you used in lowest common ancestor of a binary tree the first problem now that you know that they both exist you can use you know the standard lca but obviously that's not efficient you're going to have to do one traversal of the tree to figure out if p is in there you're gonna have to do one traversal to figure out if q is in there um actually you could just do it in one traversal you could just level traverse everything so maybe ignore that part so you'd have to do one full traversal to check whether or not p and q exist and then you would have to do the second traversal to actually find the lca there should be a better way to do this that we can only do it in one iteration and let's look at that solution now so we went over the problem introduction we read the question prompt and we talked about what the naive solution to this problem would be but i did mention that there is a more optimal solution where we don't have to traverse the tree twice we only have to do it one time so let's think about how we might do that the problem here is again that we're not guaranteed that p and q exists in the tree and we know that we have to return null if p or q doesn't exist or they both don't exist so what this means is that we have to do a full tree traversal to figure out whether or not p and q are in the tree because if they're not then we know that you know there's no answer for us to return so if you remember from the solution of how to do lca of a binary tree one you know for example if we were working with the example of like five and four again the second we saw one node that was actually equal to either you know p which would be this five or the q then we wouldn't even bother looking into the rest of the tree because we could just return and then we would either find the lca on the other side or it would have to be you know in five subtree and therefore we could just return the five the reason we can't do that in this case is that we have to know for sure that four exists in the tree whereas in you know the first iteration of this problem you are guaranteed that you know p and q existed so we could return here without you know any fear of not actually finding the q the problem with this problem like i said is that you know p or q may not exist so we want to use basically the same algorithm as we did before where you know if we find a node that equals p or q we want to you know return that node to its parent but we can't do that before processing the rest of the tree so you know in lca 1 we could cut our recursion at the point that we found either p or q and then return that node to its parent now what we have to do is okay we have to traverse the rest of the tree to see if we can find you know the other node and what we need to do is we need to maintain uh two boolean flags and we need to say whether or not p was found and we need to say whether q is found so every if we ever find p then you know we'll set this equal to true and if we find q we'll set this equal to true and the algorithm is going to proceed the same as it did for lca1 so for example you know we'd start at the root uh let me get rid of all this you know we'd start at the root and we'd say okay does you know three equal p or q no it doesn't okay so now we need to explore its left and right trees so we go to the left first so now we're at the five and we're gonna say okay so we'll pretend that p equals five and uh q equals four right so we'll say okay you know um we need to check we need to find p or q in the tree so we can't just stop here because you know this node equals to the five so we're gonna do is we're gonna then explore its left and right children before we make any sort of processing on this five so we're gonna go to the six okay does this equal p or q no it doesn't uh you know we go to its children but they don't exist so we end up back at the six now we can actually process the six because we've done both of its children and we can say okay does six equal p or q no so this six is going to return a none to the five right then we go into you know the right subtree of five and we're going to be at this two and then we still realize that you know we need to process its children first so you know we're going to do this in a post order manner so we're going to process you know the children first we're gonna go to the seven okay is seven equal to uh actually we do the check later sorry so we'll say seven okay this is not null so we go into its children we see that they're both null so now we can process the seven so at the seven we'll see okay is it equal to five or four no it's not so this seven will return a none uh similar to how we would have done in the you know lca one then okay we go into two's right uh child which is the four and since it's non-null we try to go into its left and non-null we try to go into its left and non-null we try to go into its left and right which are null so now we can process the four because we process the children so we'll see that okay um four equals to q so that way we would set you know q found our boolean flag um equals to true right and then this node instead of returning null we can now return the node four to our um you know parent here the two so now two is gonna receive none and four from its children and you know two doesn't equal to five or four so what we wanna do is simply return you know the non-null one so we return you know the non-null one so we return you know the non-null one so we would return four so this would return four and we'd be back at the five so now we can process the five the first thing we want to do is check whether or not this node five equals to p or q so we see that it equals to p so we can simply say okay so we found the p now so we've say p found equals to true right so now we've processed that and we received a none here and we received a four from this side but since this node actually equals to p um what we can do is simply return five here it doesn't matter whether we return five or four it wouldn't really matter uh and now we go into you know the right subtree of three because we've now processed the entirety of the left so we go to the one we see that you know it's non-null so we go to that you know it's non-null so we go to that you know it's non-null so we go to its left we see okay we're at the zero we try to go to its left doesn't exist it's right doesn't exist and then what we're going to do is we're gonna check okay does this zero equal to p or q no it doesn't so that way we're going to return null here or none and then we go into the right subtree we go to eight we go to its left it's right they're both null so that means that we um you know we check okay does eight equal to p or q no it doesn't so that way we're going to return none here and then we're at the one okay now we can process you know does one equal to p or q no it doesn't and then we just return you know left or right in this case because it doesn't equal to p or q and uh neither of the children were um defined they're both none so we return none to the uh three here so three is now receiving a five from its left subtree and a none from its right subtree now we check okay does three equal to p or just three equal to q no it doesn't and now what we return kind of like globally is you know we would return five from our function um so we would return a non-null node um so we would return a non-null node um so we would return a non-null node um from our like recursive um i guess dfs function that we would write here and the last thing we need to do is actually for our answer um you know if the function that did this entire dfs returned a non-null node this entire dfs returned a non-null node this entire dfs returned a non-null node which it did okay so that means that we found a potential lca if and only if both q found and p found are true so we're allowed to return our lca here which would be the node 5 if and only if q found equals t so for example our return statement would be you know return true if um you know dfs of you know on the root node um and q found and uh p found uh else we have to return false so we have to find q and you know p uh otherwise we can't return true because for example if you remember you know when we had the case where you know p was five but q oops what am i doing um q is actually ten you know our function here if we ran this would still return five here um because you know we did find a node five but you know since we never found 10 because it doesn't exist in the tree you know we could be lured into saying oh actually we found an lca but in reality since we didn't find the q uh even though our function this dfs is still going to return this five here the fact that we didn't find q means that we have to return false otherwise our solution will be wrong because as you can see there is no 10 in this tree so that's why we have to make sure that q is found and p is found to make sure that if our dfs function returns you know a non-null node then we returns you know a non-null node then we returns you know a non-null node then we can return true otherwise we have to return false because obviously if one of the nodes doesn't exist then it's false so that might be a little bit confusing let's go into the editor and we'll write the code and it should be relatively straightforward like i said this is going to be a post order traversal where again we want to check the children of a node before checking the you know parent here and then returning up back to the parent so i'll see you in the editor let's write the code and let's figure out how to do this problem okay we went over how to conceptually solve this problem in the most efficient manner but how do we actually write the code so let's implement it remember that we need to make sure that p and q exists on our tree so let's define two boolean flags to keep track of this so we're going to say self.p found self.p found self.p found is going to be equal to false because we haven't found it yet self.q found is haven't found it yet self.q found is haven't found it yet self.q found is also going to be equal to false because we haven't found it yet okay now remember that we want to see if uh our dfs function will return a non-null node because that indicates non-null node because that indicates non-null node because that indicates that we found at least one of the nodes in the tree we're not guaranteed that the node we found will be the lca but if it doesn't return anything then that means that neither of them are going to be in the tree so we need to at least have some result here from our dfs so we're going to say you know uh answer is going to be dfs uh and we'll define dfs in a second so we'll say dfs and we're going to call this on the you know the root node that we're provided and remember our answer was only the answer if q was found and p was found because that would indicate that it's an lca so let's say okay return ands if q found um let's see if q found and um let's see p found uh else none uh right because we're returning a tree nun tree note here so uh we want to return none instead of false so let's define the dfs function so we'll say def dfs and we will just take in you know a node right cool so how do we write this function remember that you know we were doing this in a post-order manner and this in a post-order manner and this in a post-order manner and obviously one of the things we have to do is make sure that the node that we're processing is actually you know non-null processing is actually you know non-null processing is actually you know non-null otherwise there's nothing we can do if we've hit you know the end of the tree where we've gone to you know null left and right subtrees then we can't do anything so we have to make sure that our node is actually processable aka not null before we can actually do anything on it so let's check that we'll say if node um sorry if not node then we just want to return none because there's nothing we can do here right there's no lca that we can find otherwise we need to do the processing and remember that we're doing this in a post order manner so we want to process the left and the right subtrees before we process um you know the actual node itself so we're going to say left is going to be equal to self.dfs to self.dfs to self.dfs of node.left and we're going to say of node.left and we're going to say of node.left and we're going to say right is going to be equal to self.dfs right is going to be equal to self.dfs right is going to be equal to self.dfs self.dfsnode.right self.dfsnode.right self.dfsnode.right so that's going to be us processing the left and the right subtree now when both of these recursions finish what we want to do is then process the node that we're at because again this is a post order traversal so now we can do the check of whether our current node equals to p or our current node equals to q similar to how we did in you know lca of a binary tree one so we're going to say if node equals to p or node equals to q that means that one of you know this node is either you know p or q so we need to check which one it is actually so we're gonna say if node equals to p we're gonna say um you know self dot p found equals to true uh otherwise that means that we found q and we're going to say um self oops self dot q found equals to true right and then at this point we can actually return the node because we know that this is our potential candidate for an lca so we can return the node otherwise if the current node doesn't equal either p or q what we want to do is actually we can just get rid of the else here we can say um you know if it doesn't equal to either p or q but um you know we were able to find p and q in its left and right subtree which we'll get from this l and r here if we were to receive non-negative non-null were to receive non-negative non-null were to receive non-negative non-null nodes from you know these recursions into the left and right subtree and that would mean if both l and r are non-null then that means that and r are non-null then that means that and r are non-null then that means that our current node is the actual lca so we're going to say if l and r so if both of them return non-null nodes so if both of them return non-null nodes so if both of them return non-null nodes then we can return our node because we know our node is actually the lca in this case it was where you know since a node is allowed to be the lca itself that's why if it equals to either p or q we return the node here this is like the more formal definition of an lca where you know the nodes are in its subtree and this is the first point where they converge so um if that's the case then we can return no otherwise the node sorry not null uh otherwise we would just return l or r oops return uh l or r and that's what we want to do okay so we've written our dfs function and now let's submit it and make sure that this works so uh oops this should be actually self thought q found fix some bugs before we run this self.q fix some bugs before we run this self.q fix some bugs before we run this self.q phone okay phone let's double check okay this should work and up p oh whoops i forgot to pass in p and q here apologies for that um c node p q god damn it okay node p q and then we want to call this p q okay cool if we pass these in now this should what is going on uh oh okay god whoops bad radio here okay and there we go okay after a few stupid bugs uh we basically fixed our solution so we can see that it works like i said this is going to be you know optimal solution because we're only doing one pass to the tree um time and space complexity wise let's think about this so we know that we have to traverse the entire tree to find whether or not p or q is found which means that because we're traversing the entire tree this is going to be a big o of n solution right we have to touch every single node in the tree to make sure that you know p is found or q is found and you know we don't stop our recursion early if we find either p or q we do explore the entirety of the tree so that's why our time complexity is going to be big o of n space complexity okay this one is a little bit trickier if you want to count the stack frames from the recursion it's going to be a big o of n solution because you know you have to traverse the entire tree and in the case that you had a very skewed tree where it was just like all left sub trees it would be big o of n but if you don't want to count this so we'll say big o of n if counting stack frames otherwise it's going to be a constant space solution because obviously the only variables that we define here is going to be these two boolean flags but this is a constant space allocation um so there's no you know extra data structures used here so you know you can bring this up to your interviewer you can tell them okay if we want to count the stack frames it's going to be big o of n otherwise it's going to be a constant time algorithm um this is generally good enough for most interviewers they say okay you know the guy's thinking about the fact that you know you're using recursion here that's not like technically free so you should get a pass on this but this is going to be your um time and space complexity i hope you enjoyed this video if you did please leave a like comment subscribe tell me what other videos you'd like to see i'm happy to make whatever video you want uh hopefully it's not some crazy obscure question that nobody knows the solution to but i'll do my best to figure it out make a video explain it for you guys any anything you guys want please just leave it in the comments i'll do my best to get back to you and make those videos otherwise happy elite coding
Lowest Common Ancestor of a Binary Tree II
maximum-number-of-non-overlapping-substrings
Given the `root` of a binary tree, return _the lowest common ancestor (LCA) of two given nodes,_ `p` _and_ `q`. If either node `p` or `q` **does not exist** in the tree, return `null`. All values of the nodes in the tree are **unique**. According to the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor)**: "The lowest common ancestor of two nodes `p` and `q` in a binary tree `T` is the lowest node that has both `p` and `q` as **descendants** (where we allow **a node to be a descendant of itself**) ". A **descendant** of a node `x` is a node `y` that is on the path from node `x` to some leaf node. **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. A node can be a descendant of itself according to the definition of LCA. **Example 3:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 10 **Output:** null **Explanation:** Node 10 does not exist in the tree, so return null. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` **Follow up:** Can you find the LCA traversing the tree, without checking nodes existence?
Notice that it's impossible for any two valid substrings to overlap unless one is inside another. We can start by finding the starting and ending index for each character. From these indices, we can form the substrings by expanding each character's range if necessary (if another character exists in the range with smaller/larger starting/ending index). Sort the valid substrings by length and greedily take those with the smallest length, discarding the ones that overlap those we took.
String,Greedy
Hard
null
1,091
So hi gas this is today's daily lead code problem the name of this problem is shortest pathri matrix and in this problem you have to return a n cross n key and you have to return d length of d shortest clear text in d matrix you have to return a shortest text and This is no clear pass written -1 ok obviously no clear pass written -1 ok obviously no clear pass written -1 ok obviously if we are not getting the text then we have to manage ok now the clear thing what will happen is this clear text in d battery matrix is ​​this n text from d top left matrix is ​​this n text from d top left matrix is ​​this n text from d top left cell to d bottom The meaning of right cell is a matrix, it will be the value in the matrix and the top left cell which will be that means which is zero comma zero to k tu d bottom right cell is n - 1 and n - 1 and from bottom right cell is n - 1 and n - 1 and from bottom right cell is n - 1 and n - 1 and from because n cross n's. The matrix is so the length of the great and the great because both are there in the roll and the pen so we have to go from the top left to the bottom right cell. Okay now what should be the things near it which are D way of D. Meaning of every zero cell. We will visit any cell, all those sins in it. Whatever cell we take, the value of all of them should be zero which is D adjacent cell of D pass are directionally conduct there different and give lion and one more corner okay I will tell you like this I am here, the direction is okay, now one thing I can do is driver JB, when the value here is zero then I can go into it, if it is one then I cannot driver it if it is zero here. So I can just do it here, meaning I can go this way, okay, so this is what we have to do from top left to bottom right, I can drive in one direction, I can move in this direction, okay, first thing. In this, first of all, I will tell you how is the base, that is, when we will always print -1, okay, if the print -1, okay, if the print -1, okay, if the value of the place from where I want to start is one, regardless of the rest inside it, the value of that place will be one, if my It is the top left corner, if its value is our one, then I cannot start like this because I have to traverse any zero value will be present in the cell, I can do the traversing from there only in this direction from there. I can move in the reverse direction but even if my initial value is created then I cannot do the driver C in this great. This is how the minus one will be printed one. How is this also? Let's flip this. Here we have zero and start here. Okay, I'm going here, going anywhere, but I can't reach here because I can go whenever. When the value of the cell will be zero but here it is one, then how will we have mines in this I can traverse in 12th, meaning it is my wish, I go here, go there, I will traverse in ortho direction so It will take only one second for me or I will travel the same distance, okay, I will travel in the eighth direction, so it will take only one second for me, and I will travel the same distance, okay, I will travel, now mother, take me, I came here, I also went from here like this. Then like this, then like this, we can go like this, okay from here too, I started like this, I went here, I went to both together, then I came here, then I went here and there together, then I went from here to this side I am doing it together on this side, I side to this side I am doing it together on this side, I mean, at one time I came on both of them, then in the second time, I came here, BF is going here, search breakfast, in the first time, I came in the same second, then to further that, I came on one. It will take more seconds from each point, from here also if I do it or from here I do it, from here I did it and from here also I didn't do it, so out of these two, it is two each, two times two seconds time, so here But we have to do it, okay, you must have been surprised to see that DP can also do it in this, obviously we can do it in DP, but it gets a little coded, it becomes a little too complicated, we have to repeat each and every one of it again and again. For this, I have to check in some entry whether I can travel in an auto or not, but in BSF, in a loop, it is checked whether I can go in that direction or not. Okay, now I understand this. Gya zero I also have to put time or distance in it. If I think, I can sleep in one second or one second going here or one coming here in one distance. Listen, I read it as tick time second, one at a time. Okay, now one thing here, I am starting here, so already one second has passed, the initial will be that will be the value of my time, one is already done, I can go here but I cannot go here. I can go here and here in the next 1 second, from here if I do, I can go here, and I can go here, that is, I am coming back to this place from here, that means I am coming back to this place with zero work. Doing the thing again and not here, there would be many places like this, if I came here, if there was zero value here, then I am going back here A, I am checking in all these, so I have to do one thing. If I have taken this value, it means that I have taken this index. If I have taken 0, 1, then I have to band its value from zero so that I can go to this again. You are relieved. If I have taken this index. Zero comma I put them in K because its value was zero so I can drive there. If I can drive then so that I don't come to it again, so for this reason I banded its value to go from one to here. I am here, what is its index? One because I have already taken it, why I am okay, so from here I can't go here too, so this one can also be completed, by doing this also I will go from zero to one because I have done this and I can go here Can't go because if I change, I can't go here because this is one, okay now zero comma zero one's mother, I can go, your zero one, you come one and you come on my pulse, let's take it now here. I can't go here either, I can go from here, what happened to this is our 011, now I am late from here, this story can't go here, you cut it, let's take this is our 2 I from here I can go here, okay, this gives our value and the question is done by returning from the source to the destination because I could go here, I can know because one is already done, the driver is already done, okay now from here If I go here also then by increasing it the base will be five only. How did you tell me how to put a normal one when we can make it rich? This zero will not reach the bottom right corner again and we will return it in the last minus one. It is okay. Still, it will reduce, okay, why did we take the time of arrival, I did it, okay, now ahead of this, let me tell you one more thing, okay, look for a minute, I am there, mother, take it from here, I can go here, and here also, okay, from one, I can go here, this is our zero minus one, it means we did mines in both, okay, one less. But my pen is a good pen, it is also big, it just got flooded, okay, now here I have written all the changes, now let's put all these together, okay zero, then I will write down our plus one plus properly, minus one zero one. Mines One Zero One is the pen, that is ours -1 01 -11 -1 0 -11 -1 0 -11 -1 0 01 Okay -1 03001 Our direction should be one below the other, lest you If you mess things up even further, the sequence will get messed up. Sequence equals tu equal tu one return kar dena -1 -1 -1 Wise Note Equals tu zero ok hai row comma time = k dot = k dot = k dot Main sabko driver karna hai usko first bob will do Well, now this row equals you and minus one and tomorrow = M - 1 row equals you and minus one and tomorrow = M - 1 row equals you and minus one and tomorrow = M - 1 means we went and moved, we if they reached our last bottom right, we will return, okay if so No, this endro give greater equal tu is equal to zero, meaning if we travel then it becomes invalid right and the pen give greater give equal to tu is equal to zero only then we have to drive so that we do not have to traverse again, ok great. 1 minute name is wrong
Shortest Path in Binary Matrix
maximum-average-subtree
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`. A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that: * All the visited cells of the path are `0`. * All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner). The **length of a clear path** is the number of visited cells of this path. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** 2 **Example 2:** **Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** -1 **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 100` * `grid[i][j] is 0 or 1`
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
Tree,Depth-First Search,Binary Tree
Medium
2126
1,061
thank you welcome you all to the channel one stop for Python and this is the first video in the daily lead code series uh the very basic motive behind starting this series is that people are not that friendly while writing code in Python therefore this video is for newbies and also for the mid-level programmers who also for the mid-level programmers who also for the mid-level programmers who try to write code in Python but they are good at logic building they can write code in C plus but they are not able to think the data structure and how to look and iterate uh in Python uh therefore this is the series dedicated for them they can build problem solving skills in Python by solving daily lead code problems uh with that intention uh this is the first video of the series because what I have seen and that is the very basic intention behind starting this channel is that a lot of resources are there on YouTube uh they all are telling approaches in C plus some uh some telling approaches in Java therefore people felt out and follow everything in C plus in Java but we are here to start the community building in the case of python therefore I am here love to tell my approaches and how to solve problems in Python and with data structures should be used perfectly this is the first problem number is one zero six one problem name is lexicographically smallest equivalent strike let's jump into the problem and understand the problem statement first of all you are given two strings of the same length S1 and S2 and there is a string based HDR therefore what are the pieces of information that need to take into account first one is that the two strings are of assignment second piece of information is that you need to tell establish relation between each character S1 I and s2i relation between this character okay now there are three relations given the flexibility symmetric Collision in transitive relation you all know about this relation there is nothing new to tell you about this and now let's start understanding the problem that what we need to do here we have given first string ABC we have given second string CDL we are telling that we need to establish relation between each character of both the string let's start like first character of Swing one is a second first character of string two is C we have established a relation a symmetric relation see when we are writing AC we need to automatically understand there is a c and a automatically vice versa relation is established then we need to step this lesson between B and D there is a relation D and B uh due to symmetric property and at last then relation between c and e what you need to observe between a c and CE that this is following the transitive property therefore you need to put e in the first set now we have two sets of characters this is the set one this is the set to now in problem we have given a base string now we need to iterate over this string and we need to return and we need to check like the first character is e we need to check this we need to check upon which set this is belonging like e is belong to first set and what is the least character of this set this is a now the second character is e again the list character is a now the last character is d therefore list character is d therefore what is the lexicographically smallest string possible of the base string a d it is aad uh sorry uh this b a b is the lexicographically smaller string therefore now how we need to approach this problem we understand the problem statement perfectly therefore the very first thing how to think in that direction see and the problem the two strings are of the same length okay now whenever in the problem the problems are such like the problems uh the problems like the arrays and the strings the elements are of same plan okay and you need to establish relation between each and individual elements so that uh array or strings you need to think in the way of that each element is in node and you need to stay when you establish simulation between two node and you are thinking in the direction of trees or graphs okay because and how this is beneficial here because whenever you need to think that uh there is a node and there are certain conditions given in the question upon which you can interchange the node or like uh like there is a earlier there's a relation between a and C now at the last resolution between c and e and you need to change and change node to the uh earlier established edges a b a c okay whenever such type of question you need to think in the form of the graph and trees you need to solve the problem in the form of arrays and the graphs arrays and strings only but you need to think in the way of the graph entries now let's visualize the problem very well and you can understand that how we are approaching this problem aha see we have first string Parker and we have another string Maurice and best thing given is parser what I am telling you that you need to consider each character as a node p m a o r k e r and you need to establish since this character uh they are the length of the characters are same therefore you can establish relation between each character see when I am stabilizing character between p a m a o or the rrc RR here you can say it is a reflexive relation uh here we can this is the reflexive relation in RR in case of R it is a reflexive relation uh now we need to establish between k r e f r s and now how we can think uh then what we need to do we are taking each node okay we uh we are taking each node we are establishing relation like pm aor uh here we are taking a relation between AR here we are taking a relation between AI here we are taking a relation between r and s again you need to follow the same property like this is a simple symmetric property this is again the simple symmetric property this is the reflexive one you need to check the transitive one and the best uh way to think in the problem the graph that there's a transitive relation and you need to overlap the node Whenever there is a transitive relation like here we have relation between K and R and RN is therefore what we need we have to do we need to put s here and we need to save this edge here and we need to step this lesson like this okay now this is uh now the problem becomes simple now it becoming a rock problem you can think in the direction of DFS but what I am suggesting that what we are doing and upon because everything you need in the lead code there is a pattern in every data structures advanced concepts to the data structures they are taking their advanced concepts and they are implementing simple problems based with that there is nothing big deal in that therefore you need to observe the pattern right here what we have to do we just need to return upon each relation we need to return the smallest or we can say the leader of each set earlier we have the each node individually it means each have their own disjoint set then we are making Union by creating an edge between two nodes okay listen we are careful very carefully how we are going in that direction earlier there is all single nodes then we are creating edges between them it is like we are creating Union of the disjoint sets there earlier that we have provided okay and each time we need to find out the leader of that set therefore while making the uh union we need to test our logic in such a way that each time when we are returning the leader it will be the smallest character like when I am making Union between P and M I will keep sure that here will be M leader will be m this child will be p a o r k r s e i okay now let's start for writing uh the output for the parcel let's take P the leader is m and for a the leader is a for R the letter is R uh no for R the leader is K okay you need to remove this also and for S the reader again is K foreign set and Union fine uh Union find of the decision set Union find is a very basic algorithm that we are used to find this cycle in a undirected graph and there are very famous use cases of the Union fine and well whenever you are thinking in the direction of the lexiographically smaller string of the similar length you need to one string in the direction of the Union Point if you want to check out the distilled explanation and how to approach Union and find it in Python you check the link in description or I will also attach that video at the end of this video so that you can find all the details about the union and find uh in first video we talk about Union Finance basic implementation two and three problems of the lead code itself and in this next video we'll talk about the optimization the rank optimization upon the union file and we will do two and three problem on that also okay now let's implement this problem what you have understood that we need to implement we need to return the lexicographical or return the smallest character of each set that is made after the union okay therefore thinking now the implementers on the Union uh Union fund is out of the scope of this video therefore I am refraining from explaining a lot of things because unnecessarily the video length will be high now let's start solving the problem first of all uh we are taking a well as a b c d e f g h i j k l m n o p q r s t u b w x y z why I am taking this we are trying to create a dictionary where we need to create a disjoint set of each individual character we are trying uh this is the very replica of the very first logic implementation of the design set that we have provided with the design like we have provided with the design set and you need to establish Union uh upon finding uh age between uh two individual characters okay now how we are establishing the relation there is 26 characters and we need to maintain the 2026 disjoint uh set how we are doing let's check it out we are making a dictionary and we are using the dictionary comprehensive uh there is a very cool Concept in Python see very small line foreign like this we have a this will be our output like this B is to be has that approachet we have in our dictionary now what I am doing I am trying to make a relation between like I am taking one character from string two and try to make a union between that but how I am doing it let's check it out therefore let's see again uh you need to think very simply in Python like whenever you have to string whenever you are having two strings like here we have uh one is ABC again it's c d e and you need to establish lesson between AC BDC very common thing that you need to come in your mind that is g function like 4 we need to zip both string one listening to now again there is a very cool Concept in Python that you can extract item this can say unpack the zip itself in the for Loop like this is the first character okay the second character is B in the G this one what is a and b like when we zipped and see it is like it become a zip object and it's like a collection of tuples therefore A and C A and B here is the A and C they are the first and second characters of that double okay now what we need to do we need to find we need to implement a find function and what is fine what is Union that you must refer to my union find video you can understand there very clearly now for finding the leader of that character we need to implement the fine files let's understand the first leader is L1 second leader is L2 again we are using the cold concept of uh items find of a comma kind of B let's define the find function inside here see again that is a very cool concept of python that you can do nested functional programming inside a function also in other languages you cannot write is that and why we are writing it what are the chord structure if you want to learn a lot about it you can refer to my earlier videos where I have in detail about the intricacies about each data structures about each uh iteration method how to master iteration in Python how to approach how to choose the data structures in Python I have make a comprehensive video in that check it out link is given in the description below we are implementing the find function let's take we need to find X now we need to look we are maintaining the leader of each character in the dictionary itself therefore you are using dictionary in file Union we are using parent you all have to remember that thing you all are remembering that we are using the parent for finding the uh which one is the leader in that array therefore here we are using the dictionary that is character in uh in the value of each character which are used as a key we are storing the leader uh in correspond to that character F find X if peak of X is equal to X we need to return X else we need to return we find a that's simple this is the our fine function now it becomes L1 and L2 is clear now you need to check here only you need to check the condition of the union we are not writing unions separately because it is a very simple use case of the find Union unit will not make the code necessarily active a lot of in lot of solution you will find that people will follow the approach of Phi write the class find Union they have a dedicated fine function dedicated Union function but you need to think that like world is like in code do not in what is the concept in the coding do not repeat yourself this is a dry principle and the reusability is a very basic function that there is a fine function there's Union function there is a class unit there's a class of the find Union how you are using it here and there they are just like collection of individual Concepts and it together they make a big concept but you need to go from bottom up approach like you are understanding is Concepts then you are understanding the bigger picture then you can what is the very basic benefit of this that you can apply each individual concept the smaller Concepts here and there okay now what we are doing we are checking the L1 and l tool if L1 is greater than L2 it means that L2 will be the leader of uh L1 therefore in dictionary of L2 while storing L1 okay dictionary of element we are storing L2 because L1 is bigger L2 is smaller we need to return this smallest lexical graphically therefore we are writing so we are writing like that okay and we need to store the value now I just need to return this string now our dictionary contains leader correspond to the each individual keys now we are iterate over the base string and find the leader of each character of the best string from our dictionary and how I will convert that list into a string that is another thing let's take it into the list we are again using the list comprehensor if you want to know a lot about list compensions or problems the list components check my earlier videos find of I find of decofi for in this STL we write it over the basis here for each character we find the characters corresponding to this dictionary these are the leaders of the dictionary and how we are finding it and we need to join it uh this will be the very basic core structure that will be going to open let's run our let's run it yes always this is the first let's submit it yes we have a submitted our code perfectly fine and this is the solution uh and I hope you all like this video I know this is the first video there's some problem while recording it after two and three videos the videos are going to be smooth and the problems and the explanation tendency also going to be very far better than this because this is the first time I am shooting videos I am not expert in it but I am trying my best to tell whatever thing therefore they see smaller videos because if I can sort also uh explain this video in or 10 to 20 minutes but that is not a case here because I am trying to explain you the things how to approach problems in Python see I am telling you about the Jeep function how you can unpack individually at the for Loop only how you can see what we have done here we are using the joint function because we are storing the leaders correspond to the each character of the best string in a list and now it's like what is like this we are like if our base string is like our best thing is faster we have macaque in our list here um a k e we have stored like this we need to convert that list into a string we are using the join function uh to a empty string and that we need to return this is a very simple thing now please I recommend you to watch my video on the disjoint set in Union I have very comprehensively taken the class and you can get only uh doubt your all the doubt clarified after understanding the designs at Union and you can apply it in competitive programming also you can use that concept to solve the problem here also in the lead code problems lead con medium problem can be solved very informally uh you can also use Union and find to solve the various graph traversal problems also you can use in the we have all the DFS on the basis of that also therefore please check it out that video and after understanding that video and after when you watch the video of very basic python data structures when you see this solution uh series video you can get everything very clearly okay thank you for now uh a very good day thank you all of you
Lexicographically Smallest Equivalent String
number-of-valid-subarrays
You are given two strings of the same length `s1` and `s2` and a string `baseStr`. We say `s1[i]` and `s2[i]` are equivalent characters. * For example, if `s1 = "abc "` and `s2 = "cde "`, then we have `'a' == 'c'`, `'b' == 'd'`, and `'c' == 'e'`. Equivalent characters follow the usual rules of any equivalence relation: * **Reflexivity:** `'a' == 'a'`. * **Symmetry:** `'a' == 'b'` implies `'b' == 'a'`. * **Transitivity:** `'a' == 'b'` and `'b' == 'c'` implies `'a' == 'c'`. For example, given the equivalency information from `s1 = "abc "` and `s2 = "cde "`, `"acd "` and `"aab "` are equivalent strings of `baseStr = "eed "`, and `"aab "` is the lexicographically smallest equivalent string of `baseStr`. Return _the lexicographically smallest equivalent string of_ `baseStr` _by using the equivalency information from_ `s1` _and_ `s2`. **Example 1:** **Input:** s1 = "parker ", s2 = "morris ", baseStr = "parser " **Output:** "makkek " **Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as \[m,p\], \[a,o\], \[k,r,s\], \[e,i\]. The characters in each group are equivalent and sorted in lexicographical order. So the answer is "makkek ". **Example 2:** **Input:** s1 = "hello ", s2 = "world ", baseStr = "hold " **Output:** "hdld " **Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as \[h,w\], \[d,e,o\], \[l,r\]. So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld ". **Example 3:** **Input:** s1 = "leetcode ", s2 = "programs ", baseStr = "sourcecode " **Output:** "aauaaaaada " **Explanation:** We group the equivalent characters in s1 and s2 as \[a,o,e,r,s,c\], \[l,p\], \[g,t\] and \[d,m\], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada ". **Constraints:** * `1 <= s1.length, s2.length, baseStr <= 1000` * `s1.length == s2.length` * `s1`, `s2`, and `baseStr` consist of lowercase English letters.
Given a data structure that answers queries of the type to find the minimum in a range of an array (Range minimum query (RMQ) sparse table) in O(1) time. How can you solve this problem? For each starting index do a binary search with an RMQ to find the ending possible position.
Array,Stack,Monotonic Stack
Hard
2233
532
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you have not liked the video please like it subscribe to my channel and hit the bell icon so that you get notified whenever i post a new video so without any further ado let's get started so problem is k different pairs in an area very easy problem we are given an area of integers and a number k we need to return all the unique k different pairs in the area so what does that mean k different pair is an integer pair numbers i comma num j where the following are true inj is less than nums length and nums of i minus numbers of j should be equal to k right so that means if you subtract the nums j minus numbers of i if you do that uh or like the difference between both uh these numbers there should be two numbers and the difference between them should be equal to k so uh let's see this test case so here what we are given is we are given this array and we are given k so k is 2 means we need to find two numbers that is we need to find two numbers a r of i and a r of j right such that when we subtract them we get what k we get k so this is absolute means like the overall difference should be absolute value of the difference should be k so if you see what all pairs are there in this area who's like if you subtract them it gives 2 so see 3 and 1 is there 3 and 1 3 minus 1 will be 2 so this is 1 pair and 5 and 3 so you can say 3 and 5. so if you subtract 5 minus 3 if you do that you will get 2 so these two are the pairs so answer will be what answer will be two because there are two pairs so we have to return the count of how many pairs are there so output will be two right so i hope you understood this thing now let's see how we can approach it so here what we will be doing is we will be uh seeing two approaches first we will see the better approach and then we will be seeing the uh like first we'll see brute force then better and then optimal see guys we have to find pairs now we have to find pairs so whenever we have to find pairs the simple brute force approach which comes into mind is that we have two nested loops the same like thing we have two nested loops and we will consider all the pairs this is the i loop this is jelu arr of i minus ar of j absolute value of this should be equal to k if this is the absolute value if this is so then just increment the count plus so using this approach you will be considering all the pairs which can be possible in this area that is three with one three with four three with one three with five then one with four one with uh one with one then one with five four with one four with five and one with five so all the pairs you will be considering all pairs so obviously time complexity for this will be of n square which is not efficient right so there is extra loop which is this one this j loop and we can avoid using this right now this j loop is taking n complex tina it's taking in o of n it will run so it is taking o of n what we can think is we can think of reducing this of n to o of log n so if this o of n is reduced to o of log n this time complexity of this will be what outer loop is of n and inner loop is log n so it will be n log n if somehow we can reduce o of n to o of login now login is what log when login time complex complexity comes when we use binary search right binary search has what login complex tina so what we can do see what we can do is we can use binary search we will be doing what c we will be going to each element and we will be finding in the rest of the array so see we are currently at i three so in this rest of the area what first of all what we have to do is see binary search always the array should be sorted now so we will be sorting this area first condition of binary searches area should be sorted so we are sorting so one three four five this will be the sorted area right then what we can do is simply we are currently here we just need to find what we need to find whether there is uh 1 plus k because the arr of j minus a r of i we need to find out if it is equal to k so we are fixing we are going to each element and that is our ar or phi and we are finding j a r of j will be what a r of i plus k na so this is all our ar out of fives and we are finding a r of j so i a r of i is what 1 plus k is 2 of 2 so 1 plus 2 is 3 so what we will do we will find three whether three is present in this array or not three is present so we got our we got a pair so you will go ahead then so you will not consider this one again because then it will give the same pair we have to take only the unique pairs only unique piece so you will just shift i until the values are same so these eyes are same as shifted now from here you will check so 3 three plus what three plus k is what two so five you need to search five so five is there here five is here so we got another pair so pair another pairs so in this way you can use binary search for each element you are searching it's this ar5 plus k in the rest of the area so this is one approach right and this time complexity will be n log n right there is one more approach which is again n log n one only so let's see that three one we have areas three one four one five right we have this area three one four one five and k is two so see whenever you have to find pairs if you remember we have discussed that in for some question that if we have to find pairs so what we can do is we can use two pointer approach two pointer why two pointer because see we have to find pairs now means we have to find two elements so two pointer one pointer will be pointing to the first element and second pointer will be at the second element so whenever you have to find pairs you can use two pointer approach so how we will use that over here see we will be taking two pointers they are not really pointers they are variables only that will be storing indexes so just two indexing so right currently we will be taking i at 0 and we will be taking j at index 1 but before starting 2 pointer we have to again sort the array because for port 2 pointer we have to sort the array sorry so we will sort the array so this will be one three one five oh sorry my bad just a second here what will be the array so i will change here only so now the array will be what one three four five this will be the new area one three four five sorted array right so now i is here at zero index and j he is here so what we need to find out whether a r of j minus a r of i is equal to k or not we need to find this thing see over here a r out of j is what 1 minus a r of i is what one minus one is what zero but what we are difference is coming out to be zero but what do we want the difference we want it to be two tuna we want it to be 2 so this difference is less than expected so if we have to increase this difference what we have to increase a r of j or air or phi think about it this difference is less than the expected one so if we have to increase this difference what element we have to increase this one or this one so we have to increase this one a r of j so that this increases and then the difference comes more because let's say if this is 4 then 4 minus 1 will be 3 so we have to increase j so if difference see if the difference this is the difference if difference is coming out to be less than k means we will increment j plus we will do j plus this is one condition so j move it ahead right now again check a r of j minus a r of k a of j is what 3 minus a r of 5 is what 1 so 3 minus 1 is 2 now this is equal to the expected k so this is one pair we got three comma one three comma minus one pair so you can increment your count becomes one right now see uh we will shift i ahead because see this one and three column can also be a pair so just shift i j will also be shifted and also uh shift i so i come here so i will come here now see like when we got the difference is equal to k we shifted both i and j all right now four a r of j is what again do it a r of j is what 4 minus a r of i error 5 is what 1 which is 3 so 3 now see this difference is greater than the expected way we want 2 but now difference is 3 we need to decrease this difference so what we will do we will increase the arrow of i because if arri is 2c then this difference is 2 now so what we will do is we will if over here now another condition will be that if this difference is greater than k then we need to increment i right so i will come here at now again a r of j is what are of j is what 4 so 4 minus 3 is what 1 so 1 this difference is less than k so if difference is less than k j plus j will come here now again see what we will do is five minus arrow of i what is the error of i is what three so five minus three is two now again we got k so we will increment j and i and we will also increment our count now it will become 2 now j is out of bound means we got all the pairs so now we will stop so see this is one approach two pointer we sorted the array and we are just shifting the pointers based on this difference right so i hope you got the approach code is here so uh just quickly we will go through the code so we have taken these pointers sorted the area first and then what we are doing is uh we are if the difference is same like if we got the difference increment i j and answer and just increment like just move j ahead so that we do not get the duplicate elements duplicate also we have to avoid now so we are doing this so that we do not get duplicate pairs and then if the difference is greater than k so if the difference was greater than k then we were incrementing i and if the difference is less than so we are decrement we are incrementing j so if you submit this is getting accepted right so see we are doing sorting here now so this is also o of n log n time complexity space is all fun there is no extra space we are using now the optimized approach which we can use for this problem is wherein we our time complexity will be con often but we'll be compromising on space so we'll be using some extra space so let's see what it is so we have this three one four one five we have and what is k is what two see earlier what we were doing earlier we were what we were doing we if you remember the binary search approach right uh we fixed this arr of i we fix this arr of i and arr of i plus k a r of i plus k which is our arr of j we are searching in this rest of the arena so that searching was log of n what we can do to avoid this searching is that can we use a data structure where searching time is constant if this searching time becomes constant then of n log n where this log n was for searching if this is constant now so o of n will be the time complexity so whenever you have to search an element in constant time then you can use hashmap for that so what we will do see what we will do is we will use a hashmap we will have a hash map let's create this hash map right we are creating this hash map and we are just adding all these elements in the hash map so this will be the element and this will be the count of that element so first we have three's count is one is there how many times one is there one is two times so its count will be two time and then four uh it's one time only and five we have which is also one so this is the hash map we created now it's very simple guys what we will do we will go through the array so this is ar of i now we will be finding whether a r of j is in the hash map or not if it is in the hash map we found a pair a r of i was what 3 so 3 plus k which is 2 so 5 is in the hash map yes it's there now so we got a pair three comma five so count will be one go move ahead so here now a r of i is what one so 1 plus k is what 2 3 1 plus 2 is what 3 so is 3 present in the hash map yes 3 is present please present now so we got another pair so count two basically you know what like now you will understand something now we go here four so four plus we do four plus k is what a 2 so 6 is not there in the hash map so we will go ahead now see again guys see again you come again to 1 we are again coming to 1 so we will do 1 plus 2 will get 3 and we will search it in the hashmap we will try to search it in the hashmap but we will find it so we will increment the count again but earlier we have taken this three comma one combination now we have taken one commerce recombination so we will not iterate on this array we will be iterating on this keys of the map we will be iterating on the keys of the map so that do not we do not have a duplicate pairs because one was occurring two times now so one with three also and again one with three we have to have unique pairs if you remember unique pairs we have to return so that's why we'll be iterating on these keys of the map and accordingly we find the output we found find the output so here when we are here at five so we will do what five plus two is what seven is not in the hash map so just go ahead so we found two pairs one comma three and three comma five right so i hope you understood this approach there is one edge case in that let's see that so we have what we have again three one four one five and k is equal to what two so let's do one thing let's take here in place of 5 let's take 3 so now for out for this and also here let's take k as 0. right so k 0 so see what we will do is first of all we'll make a hash map so hash map will be taking this is the element and this is the count so three is count is what two there are two times three occurring then one count is what two again and four is what only one thing this is the hash map now what will be the output so k is 0 means we have to have a r of j minus a r of i and that should be equal to what 0 difference should be 0 means when is different 0 difference is 0 when there are elements are same both the elements are same so 3 comma 3 this here difference will be 0 right so what will be the how many pairs are like that we have 3 comma 3 we have 1 comma 1 we cannot take 4 comma 4 because 4 is only occurring once so we cannot take 2 times 4 that's not possible so pair can be taken only if for a certain number there are two more than one occurrence then only its pair can be taken i hope you understood this point so let's see now what we have to do here so see now what we will do is when we iterate through these keys so we will go to three now we will check whether k 0 no so what we will do we will just simply check if we have this is a count of 3 so if count of 3 is more than 1 so we can pick a pair of this 3 with itself right like that so we will increment our count 1 then again we'll go here we will see k is 0 and for this one its count is there are two ones so we can take its pair one comma one so count will increment and will become two then we go here we take we see k is equal to zero so how many times four is occurring for only a thing one time so we cannot take it spare so only two pairs are there so i hope you understood this test case also let's see the code now let's see the code for this so here what we are doing is just this simple like if k is negative just return 0 and we are taking this map and we are storing the element along with its count and then we are taking this count variable which we will return that how many pairs are there and then we are going to each element each key in the map this is map we are not going in the area because then the duplicate pairs will be taken will be going in the map key maps keys and if k is equal to zero and its second p dot second means this value if this value is greater than 1 right otherwise if we have k as some number like 2 3 and it's p dot first plus k that is like we were finding the 3 plus 2 5 so if 5 is present in the map so that if that is there so increment count and lastly return count so here see we are taking just going through the keys so its time complexity will be off in and we are storing the keys so it will be space will be open i hope you understood all the approaches and uh let me know if you have any doubts in the comment section and you found the video helpful please like it subscribe to my channel and i'll see in the next video
K-diff Pairs in an Array
k-diff-pairs-in-an-array
Given an array of integers `nums` and an integer `k`, return _the number of **unique** k-diff pairs in the array_. A **k-diff** pair is an integer pair `(nums[i], nums[j])`, where the following are true: * `0 <= i, j < nums.length` * `i != j` * `nums[i] - nums[j] == k` **Notice** that `|val|` denotes the absolute value of `val`. **Example 1:** **Input:** nums = \[3,1,4,1,5\], k = 2 **Output:** 2 **Explanation:** There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of **unique** pairs. **Example 2:** **Input:** nums = \[1,2,3,4,5\], k = 1 **Output:** 4 **Explanation:** There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). **Example 3:** **Input:** nums = \[1,3,1,5,4\], k = 0 **Output:** 1 **Explanation:** There is one 0-diff pair in the array, (1, 1). **Constraints:** * `1 <= nums.length <= 104` * `-107 <= nums[i] <= 107` * `0 <= k <= 107`
null
Array,Hash Table,Two Pointers,Binary Search,Sorting
Medium
530,2116,2150
232
hi guys today I'm going to solve lead code question number 232 that is Implement a q using a stack in this question we have to basically create a q using Stacks so first we have to keep in mind that Q follows the first and first out method that is fif however stacks on the other hand follow the last in first out method which means that the element for example if I create a stack the ele uh let me insert one over here followed by two so the element that went inside the stack in the last was two so when we try to pop out the elements the first element that would come out from the stack is going to be two only I hope I was able to make this clear now let us quickly jump into the question so I will be trying to explain this with the uh example which is given in the question so what we can do is in this we can first create two steps okay so let us create one stack as ST1 and the another stack as st2 so now I have two stacks ready with me so this basically is the formation of our Q now my first operation is to push the element one so I will quickly take one and push it inside my stack one now I have the next step that is I have to push element two again when it comes to push I would be inserting the El to inside stack one now I have an operation to perform Peak so what I can do is since I have to create a q that means that the element that gets inserted first is supposed to come out my answer here should be returning one however I can see when I try to do a pop operation on stack one my element that comes out first would be the element two and hence this would be wrong so what I can do is I can simply take all the elements which are present inside stack one and push it inside my stack two so I'm going to take all the ele I will take two I will remove it from stack one and push it inside stack two next I have element one I will take the element one pop it out from stack one and push it inside stack two and by following this my stack one becomes empty so I have a empty stack one now once it is empty and I know that stack one is empty what I can do I can simply take the element which is present in the top of stack two and return it for the answer of peak so my peak in this case would be one now my next operation is pop for pop as well I would be doing the same thing that I followed for Peak I would be checking if my stack one is empty or not if stack one is empty I would be simply doing a pop operation on my stack two and in the end I have a check empty function in which I will be checking if both my stack one and stack two are empty if both of them are empty then I would be returning a true and if any one of them is having element then I would be returning a false now let us understand this question better with the help of the code now I will jump into the coding part so what I can do is I would be creating two stacks as I just mentioned so let us create are two stacks stack of type int I would name this as ST1 I would create another stack similarly let's name it st2 this was a creation part now when it comes to push operation I would be taking the element inside of a stack one so I will simply push X in my stack one now when it comes to pop and P Peak operation what I will be doing is I will check if my stack 2 is empty or not if my stack two is empty then I would be taking all the elements of my stack one and pushing it inside my stack two so I will take a while loop while not of st1m empty I would be taking my elements of stack two do push the top of Stack one ST1 do top and after that I would be popping the elements from ST1 then I will be having int element is equals to st2 dot Top This is the topmost element which is present in Step 2 and then I would simply do s2. pop and I would be returning the element the peak operation will be following the same logic of the pop operation and I will simply copy paste it and the only thing that I would be omitting here is the pop operation and in the end we are just left with our empty function and this would be directly returning if both the stacks are empty or not so I'll do ST1 do empty and st2 do empty let us try running this once and the test case does get passed now let me try submitting it and here we go I hope I was able to explain you this question thanks for watching
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,029
hello friends today we like status fish from him problem number 1 0 to 9 to 15 skip you said this question you are given that when people are applying for a company and young people find to me and the company are paying for the cost and the ayat person replied to that a city it cost the company first I and if it cost for Blanke to the CPP is cost I even have returned the minimum cost of flying every person felicity does that exactly n people arrive and so let's do there through cities and there are 2l people we have to send n people and 50 button and the pellets it says that you are given the post applying the people from like respective places to 51 and 52 so you have to return the pilgrim frost off evil okay so in this input array as you can see for the person first who fly to city 1 a or 1 is 10 and blank city 2 is 24 person to flying between 1 is 30 I'm seriously so answer so what is the minimum cost so let us see this is example these are the same values for like for full repeal these are the Mount which it will be for the company to paid to make the people person fly to city exit so what we can do is we can we release or the heli but on what condition you have thought that if you have to first see that okay if we subtract the first this value second value from the first value what we can get is we get 20 minus 10 is 10 okay then for this its Finiti 170 then for this is 50-50 then for this is 50-50 then for this is 50-50 cause this attacking this one this and 20-13 it manage them so what does this 20-13 it manage them so what does this 20-13 it manage them so what does this value actually depends it depicts - in value actually depends it depicts - in value actually depends it depicts - in comparison to slang into CPP it is costing 10 rupees war if the person is flying to city B instead of City thing it means if you are flying the person to CTP the company will cost oneself is blue if it's climb sweetie hey but in this case if it's flying too steep be it will be better because the company is saving people will instead of like the city so if it's sorted according to this number and let's say the first number will be well 70 you feel like sorted in descending order 170 then I understand - so it means it's better to flag this - so it means it's better to flag this - so it means it's better to flag this person to City this person disappear this person to see TV and this wasn't is there enough as you can see if this person flies city a then if this was fertile if not to reflect better and the more the bigger value is better to fly it looks to be a okay so that's it does the mean like those the main observation you have to see it in this question so let's do the food for this we will first total number if it is a number of people understand it's actually doing because they are doing people but we will show it I then okay now we have to first sort this element so in this while sorting this area we can use another function also put and have like let me show you how the lambda function works for 10 and the function is like we can write the Capuchin function in this for function only so we have to first make the hard brackets and then we have to just write the function as it is because it's a vector and yes okay so now what's in the little so we are to return we are to see if actually we have to find a difference so if the difference of a for these are vectors we are subtracting the big the second one because this index of this is 1 this is 0 for index of 1 minus vector 0 so if it's greater if it means if it's greater than 0 we have to bring it forward return - because you have to it forward return - because you have to it forward return - because you have to bring the finger forward so the first value should be get that we are sorting in this order before the first one is good and then it's decreasing so then it's part then I could find the total function to store all the total cost or fine and for the first n people from 0 to N by 2 we have to add 2 to the plus equal to first or I or Twitter because for the first n people we have to store for T and then for last and people the after store for me and for the last and fatal well I for one and that's it unfortunately fine I'm still asleep it's running perfectly fine to see if you've any doubts till you can mention down in the comment box thank you for watching this video if it's useful for you please click like button and subscribe under
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
1,603
hey everyone welcome back today we are going to solve problem number 1603 design parking system first we'll see the explanation of the problem statement then the logic and the code let's dive into the solution so here I have taken the first example from the late crop site so in this problem we need to design a parking system so in order to design the parking system we are given three inputs that is big medium and small so these three inputs are nothing but the number of spaces that is available to part these type of cars so basically we have three types of cars can be parked in this space that is big medium small right so initially we will be having an input of parking system which indicates the number of slots available for the particular type of cars so first we will initialize that so we will replace big with one and medium with one and small with zero so there is one slot to park a big car and one slot to park a medium car and there is no slot for parking a small car in this system right so this input is for just for this particular example so it varies for different types of example right then we are going to use the function add car where we are going to check whether we can park that car in this available slot right so if I was able to park that car we need to return true and if we can't park that car we need to return false that's all the problem is so here we have the add curve input so here one represents big car and two represents medium car and three represents a small car so now I'm going to try to park these cars in the available spaces right so now first I will try to add car one so now I will take this one and I will minus with one the reason why I'm minusing with one is that I need to check the zeroth index right my input starts from zeroth index in this spot list so if one minus 1 I'm going to get 0 which is nothing but this zero type core slot so I need to check whether there is a available slot or not so I'm going to get 0 and I will check in this 0th index then I need to check whether it is greater than 0 or not this value is greater than 0 or not yes 1 is greater than 0 right so I need to return true so for this input I am getting true right so after returning true we need to reduce the slot since we have parked a car in this slot so we are ready we have to reduce that so next I will be getting the value to the 2 represents I need to check whether I can able to park this car in the medium Slot 2 is medium right so 2 minus 1 is 1 so I need to check them first index so there is an available slot and I can park this car right so I need to return true and I also have to reduce by 1 since I have parked the car right then we will be getting 3. that I need to check whether I would be able to park the car in the small car slot I cannot park this car right since there is no slot here so I need to return false next I will be getting one minus 1 0 index represents big type car and there is no slot here as well so I need to return false and I am done with all the inputs so I need to return this one right that's other logicals now we will see the code before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future also check out my previous videos and keep supporting guys so initially I will be initializing the available spots for the type of course big medium and small right then in the add car function I need to check whether there is space available or not for that particular car right I will take the car type and I will reduce by 1 and then I need to check is there any spots available for that particular type of car if it is available I will reduce that particular spot by 1 right since I have parked that car I need to reduce that by one then I need to return true if there is no spot is available then I need to return false that's how the code is now we will run the code so the time complexity will be order of 1 and space will be order of 1 as well thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers guys
Design Parking System
running-sum-of-1d-array
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the `ParkingSystem` class: * `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slots for each parking space are given as part of the constructor. * `bool addCar(int carType)` Checks whether there is a parking space of `carType` for the car that wants to get into the parking lot. `carType` can be of three kinds: big, medium, or small, which are represented by `1`, `2`, and `3` respectively. **A car can only park in a parking space of its** `carType`. If there is no space available, return `false`, else park the car in that size space and return `true`. **Example 1:** **Input** \[ "ParkingSystem ", "addCar ", "addCar ", "addCar ", "addCar "\] \[\[1, 1, 0\], \[1\], \[2\], \[3\], \[1\]\] **Output** \[null, true, true, false, false\] **Explanation** ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0); parkingSystem.addCar(1); // return true because there is 1 available slot for a big car parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car parkingSystem.addCar(3); // return false because there is no available slot for a small car parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied. **Constraints:** * `0 <= big, medium, small <= 1000` * `carType` is `1`, `2`, or `3` * At most `1000` calls will be made to `addCar`
Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.
Array,Prefix Sum
Easy
null
1,675
High Gauge Our question today is Minimum Division Hey, so basically in this question we will be given an Hey and we will perform operation on Era, if and is the element of Hey, then we will divide it by Tu, if Eric element is OD then we will divide it by If we multiply by tu, then by doing this, basically what do we have to find out. If we have to find out the minimum division on this, then how can we do it, then suppose we have a given here, so there is a trick for this, like basically we have given. So what can we do with this easily, if we have to solve it, then what we will do first is convert it into and, whatever element is there and we will convert the element into and, then something like this, you will look like you to us first. If we multiply one, then here it will become like this, you will become six, it will become four, just convert the other element in it into and. Okay, what will we do now, the minimum out of this will be the minimum, like here you will be And the maximum here is six, so this has been done, we will store the minimum in M. Okay, now what will we do in the answer here, six which is the maximum - minimum, so here six which is the maximum - minimum, so here six which is the maximum - minimum, so here four comes, meaning our minimum division can be four. Next step. What will we do if the maximum is ours and then we will divide it by you okay so something like this 34 Now which of these is the maximum element 4 is 4 okay minimum which is yours okay now if we subtract it then 2 will come minimum now this Will update you in the answer OK then what will be the next step then we will repeat the same process multiply the maximum by tu means sorry we will divide so if we divide then how will ours become Now ours will be 223 so we can do like this Now if the second is second then what is the maximum in it? What is the minimum in it? If you are there then your answer will be eight. Okay, this can be. Now then we will divide it further, meaning if we divide by you, it will become 5. It will become 8. It will become four. Okay, so what is the maximum element in this? Sa is wife and minimum is you, so this will be our 3rd answer, it cannot be smaller than this, so you can solve it by doing this, we have seen the approach, now let's see how the code is done here. Look, first of all why do you have to make priority, here we are doing priority because whatever element is on it, whatever is maximum, you will get it on the top only, so like here we have given maximum here. But if we had taken then we would get elemental 246 from the thing, that is why we are doing it here, so why we have made a priority brick here by the name of PK, it is storing the minimum element and M which is storing the minimum element. What we are doing is that we are running a loop. Look here, in the next step, we are running a loop. Nas dot size means we are running a loop till the size of Eric. If that is our element then simply what we have to do is we have to push it in which. Why did we create priority in this, when should we push it and what will we do with the minimum? Whatever M is our minimum, then we should put M in the minimum and whatever is the minimum, it will be reflected in your minimum, it will be updated if whatever is ours. Element and otherwise, what we will do is simply multiply it by you and the same process is being done in the minimum also, so as I told you here, the process of conversion is simply the same is happening here, we are converting it, so we have In this step, we converted and stored the priority in when and this is the answer one which we have to return here. Then in the next step, if our priority when will continue to run, we have created one named Top in Top here. But created a variable in which we are storing the top element of priority age, then popped it from the age of priority. Okay, then out of the answer which is ours, we will store the minimum one like in the answer which is minimum and top means M. Like this process which was Top- Top- Top- Talk-Minimum has become the answer which is our minimum so we will not update it and the priority is given to tubemate. If like you came here then we will divide it again by doing like this. You can solve it, this is a very easy question.
Minimize Deviation in Array
magnetic-force-between-two-balls
You are given an array `nums` of `n` positive integers. You can perform two types of operations on any element of the array any number of times: * If the element is **even**, **divide** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].` * If the element is **odd**, **multiply** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].` The **deviation** of the array is the **maximum difference** between any two elements in the array. Return _the **minimum deviation** the array can have after performing some number of operations._ **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 1 **Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1. **Example 2:** **Input:** nums = \[4,1,5,20,3\] **Output:** 3 **Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3. **Example 3:** **Input:** nums = \[2,10,8\] **Output:** 3 **Constraints:** * `n == nums.length` * `2 <= n <= 5 * 104` * `1 <= nums[i] <= 109`
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
Array,Binary Search,Sorting
Medium
2188
849
Jhala Hello and welcome to your consideration question maximum subscribe to aao na dil at least one lamp's 35th labs subscribe to subscribe And subscribe The Amazing and mist appointed vitamin E ki koi directly write candidate setting on your head in between how to PT The second Chief Selector of the States passed left the third quid that a five right note to 1 inch and gave one so in this one the water into 10 minutes point when skin problem me to the that between these two pieces and find hidden With * * * * these two pieces and find hidden With * * * * these two pieces and find hidden With * * * * Find a Bluetooth setting from left are their tree for remind this quarter inch settings from aright 500 Now we came out word acid in witch she the amazing 0 liquid well that new that first one is next over will give Due to take care of all subscribe my channel ko subscribe our Channel And subscribe Video ko k newly vihg result i will initially 200 k and finding amazed when u the intake bandh khushboo na will u only a which are the that Africa a question is setting On This Is Pay Ki Vidhi Prohibition 20 Deposit Again Diluted Effective Treatment For The Result Of Good Result And A Well A Plus One Buy To That Bismil Take Care Of The Horse Today Cake One Nagesh To Will Be The Amazing Staff That and difficulties that solution sequence 212 AV that submarine maximum invalid 9th pimple comedy is in the jhallu that no the final beech teeshri lage it's rocking-wall 1 hua tha irfan ball sheet is issue kushvansh yo agyaan find one of them ajay singh Result SSC Hue Cutlet - Wall - Sai Pa Scientist That And Will Return R 's Result Will 's Result Will 's Result Will Have Not Equal Than A Possible In The Midst Code At This Time Can Write Result For The Knowledge They Have That Is Right And Mrs. On The Election Adh Jhal Main Pin Code Watch Next Ki A
Maximize Distance to Closest Person
maximize-distance-to-closest-person
You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return _that maximum distance to the closest person_. **Example 1:** **Input:** seats = \[1,0,0,0,1,0,1\] **Output:** 2 **Explanation:** If Alex sits in the second open seat (i.e. seats\[2\]), then the closest person has distance 2. If Alex sits in any other open seat, the closest person has distance 1. Thus, the maximum distance to the closest person is 2. **Example 2:** **Input:** seats = \[1,0,0,0\] **Output:** 3 **Explanation:** If Alex sits in the last seat (i.e. seats\[3\]), the closest person is 3 seats away. This is the maximum distance possible, so the answer is 3. **Example 3:** **Input:** seats = \[0,1\] **Output:** 1 **Constraints:** * `2 <= seats.length <= 2 * 104` * `seats[i]` is `0` or `1`. * At least one seat is **empty**. * At least one seat is **occupied**.
null
null
Medium
null
58
hi my name is david today we're going to do a leak code problem number 58 length of last word this is an easy level problem i want to solve it in javascript so we're giving a string as consisting of some words separated by some number of spaces return the length of the last word in the string so we can look at an example here we're giving an input of s which is a string and it wants us to return the last word the length of it so the last word is here world and the length of it is five so we return five and it's just it's tricky when it asks for it can be separated by some number of spaces so it could be more than one as well so there's a clever way of doing this rather than what i originally thought was that you just split the string into an array separated by space and then you return the last length of the last index and then to cover up these edge cases you need to do a trim as well but when you whenever you do the trim you're creating a new string and it's going to be oven so there's a clever way to do this with only of one i mean when you create a new string is open space and time but there's a clever way of doing this where it's only o of one space and that is by doing a backwards loop and then we're going to move backwards we're going to do two loops but it's still going to be over the first loop will be when we hit a letter a character so we're going to loop through this if it space is we keep looping it and then once we hit a character we're going to begin the next loop and we're going to loop this until we hit the space or we end the string and we're going to keep a word count during this and then if it's not as space we increment that and we return the word count at the end so ask the pseudo code for this algorithm the first thing we want to do is create a variable so create last word count and when i start set that equal to zero and next we want to loop backwards s and then in this we want to create a condition if current character is not an empty space not a space let me just do a space i want to loop backwards from current char and then you want to create a condition if current char is not a space we want to increment last word count and then if it we do hit a space we just return that last word count else return last word count and there's also one more edge case and that is when we loop backwards but there's not empty space we could say that there's just one word in it so we can just return last word count after the loop and that will get that edge keys so to put in code first we create the variable that password count and set it equal to 0 now we loop backwards so for let i equals s dot length minus one s is greater than equal to zero sorry i is greater than zero and then i minus so we loop backwards we can look at this example loop backwards until we hit a character so if s index of i is not an empty space we begin this second loop so for let j equals i so we start at where the i is so for this we'll start here j is greater than or equal to zero j minus now we check the same condition again if buffer j s of j equal an empty string empty space we increment last word count else so if we do hit an empty string empty space i mean we end it so we return last word count and now we have to deal with the edge case so if we finish the loop and we hit the end of the string we just return last word count great now let's run it nice we got it so for the time and space complexity of it we can see here that we are looping through s the string and then we're doing as a nested loop but it's not really um we don't do it for each one of it we just continue the loop again so it's still going to be oh then because we can just we're gonna because the second loop starts where this one ends and then the space complexity we're creating a variable here and that's an integer and that is it so it's going to be o 1. and that's how you solve this problem thank you so much
Length of Last Word
length-of-last-word
Given a string `s` consisting of words and spaces, return _the length of the **last** word in the string._ A **word** is a maximal substring consisting of non-space characters only. **Example 1:** **Input:** s = "Hello World " **Output:** 5 **Explanation:** The last word is "World " with length 5. **Example 2:** **Input:** s = " fly me to the moon " **Output:** 4 **Explanation:** The last word is "moon " with length 4. **Example 3:** **Input:** s = "luffy is still joyboy " **Output:** 6 **Explanation:** The last word is "joyboy " with length 6. **Constraints:** * `1 <= s.length <= 104` * `s` consists of only English letters and spaces `' '`. * There will be at least one word in `s`.
null
String
Easy
null
762
hello welcome to the solving of another leapfrog problem that is problem number 762 that is prime number of set bits in binary representation so the problem statement given here is given two integers left and right return the count of numbers in the inclusive range of left and right having a prime number of set bits in their binary representation recall that the number of set bits an integer has is the number of ones present when written in binary so we are given here left that is 6 and right is 10 and output should be 4 and let's see why so i'll just reload this page again okay this is taking time okay so now we are at it and what is the value of left it was six so left value was six right value is equals to ten and how we are getting 4 the output is 4 and how we are getting it we'll be seeing that so the inclusive range is from 6 to 10 so we'll be taking every numbers from 6 to 10 so 6 binary representation that is 4 2 6 this is final representation of 6 final representation of 7 will be one final representation of eight will be one zero this is a binary presentation of eight final representation of nine will be one zero one since nine final representation of ten will be one zero and what was the problem statement again it was to return the number of once it has so let's just read the problems written once again so it is wanting us to return the count of numbers in inclusive range from left to right having a prime number of set bits and by set we said bits we mean the number of ones present in an binary digit so the number of satellites in 6 is how many 1 and 2 is 2 a prime number yes it is a prime number and what are prime numbers are those which are divisible by 1 and themselves itself so two is a prime number why because it is divisible by one and two only so if we take ten as an example is it divisible by 1 it is divisible by 10 is it divisible by itself yes it is but is it divisible over by any other number that is 2 5 yes it is so it is also divisible by 2 and 5 so this will not be a prime number so this should not be a prime number so a prime number is 1 which is divisible by 1 and the number itself so we'll just be counting the number of ones here present the number of ones present in the binary representation of that number and we'll just check if that is prime or not if it is prime will be returning true or else we have we will be returning false and to find the number of bits present we use a built-in function you see c plus use a built-in function you see c plus use a built-in function you see c plus that is built-in n where x is the number what number the number from 6 to 10 so this can be 6 this can be 7 this can be 8 this can be 9 this can be 10 anything based upon what we want so let's take a look at the problem answer so here we have implemented a simple prime number check function which will be returning us true if it is a prime number or false if it is a not a prime and what we are doing here we just iterating from the left to right index that is it is an inclusive range so we are giving is less than equals to if it were not in the inclusive range we would have just given less than so answer will store our built-in pop so answer will store our built-in pop so answer will store our built-in pop count that is the number of ones it is having so this will be storing the number of ones that is having so our answer ens is equals to storing the built-in pop is equals to storing the built-in pop is equals to storing the built-in pop count built-in pop count of what of i and it built-in pop count of what of i and it built-in pop count of what of i and it will be sending the i and checking if it is prime or not so is prime will check if my iath number is having a prime bit count or not by prime bit count we mean the number of one bits it has is a prime number or not so six is having the how many bits so it is having two set bits that is this and this so it's count is 2 and we'll be sending it to the prime function and what will it be returning it will be returning true and if it's true we are just doing c plus counter integer and we are returning the count of the integers which are having a prime set bit and let's run this it is getting accepted let me just use some sample test pieces as well okay i don't know why it's taking so much time okay this is getting accepted too let's submit it and it's getting submitted and that is it this was a pretty simple problem thanks for watching
Prime Number of Set Bits in Binary Representation
find-anagram-mappings
Given two integers `left` and `right`, return _the **count** of numbers in the **inclusive** range_ `[left, right]` _having a **prime number of set bits** in their binary representation_. Recall that the **number of set bits** an integer has is the number of `1`'s present when written in binary. * For example, `21` written in binary is `10101`, which has `3` set bits. **Example 1:** **Input:** left = 6, right = 10 **Output:** 4 **Explanation:** 6 -> 110 (2 set bits, 2 is prime) 7 -> 111 (3 set bits, 3 is prime) 8 -> 1000 (1 set bit, 1 is not prime) 9 -> 1001 (2 set bits, 2 is prime) 10 -> 1010 (2 set bits, 2 is prime) 4 numbers have a prime number of set bits. **Example 2:** **Input:** left = 10, right = 15 **Output:** 5 **Explanation:** 10 -> 1010 (2 set bits, 2 is prime) 11 -> 1011 (3 set bits, 3 is prime) 12 -> 1100 (2 set bits, 2 is prime) 13 -> 1101 (3 set bits, 3 is prime) 14 -> 1110 (3 set bits, 3 is prime) 15 -> 1111 (4 set bits, 4 is not prime) 5 numbers have a prime number of set bits. **Constraints:** * `1 <= left <= right <= 106` * `0 <= right - left <= 104`
Create a hashmap so that D[x] = i whenever B[i] = x. Then, the answer is [D[x] for x in A].
Array,Hash Table
Easy
null
1,002
okay the question is find common characters and i'm going to summarize the question i'm not going to read it and so the question is actually telling you to find a common character for a given string array and for each string you do store each character and counting the number of the frequency so b occurred one e occur one l equal to a occurs one and label and enroll it and then you do use the integrate for each string so my idea is create a common array and you change the common array every single time when you finish one string and to find out the minimum value for each counting array so you'll get what i'm saying so common new in 26 and but i need to initialize so i can initialize to the maximum value so you don't actually um get my uh integer value so inside each string right i do say i need to create a container already to count the number of the characters so cnt c minus a you need to get more frequency uh type in i mean right in the container array so after each after finish the counting array i need to modify my common array to minimum uh continually so integer.maximum will not uh will not integer.maximum will not uh will not integer.maximum will not uh will not store in here because uh the given string will not be this big so it's going to be zero one two three four five six something at least right and for each string you update to the minimum so since l occurs twice right twice the l will be two and for the example two core locks coupe all occurs two times but all occurs one here so the common array for all is one but the answer you are going to return the answer for the list of string right so what you actually need to do i since the comma array is what we store right store if the common array what is not equal to zero or greater zero right what do we add the uh string into it so the tricky way is use at least char and since we minus a when we won't only count it so we plus a and then we return the answer and i think that will be it and let's double check okay so the minimum okay so the problem is i have multiple value for the counting i so i cannot just i can just write at least i need to loop through it in j equals zero just less than comma i j per plus so you loop twice right you loop twice and it doesn't matter for inside i mean i'm not going to change the character inside uh inside the looping so if l occur two times right you will do twice so let's try again sorry for making mistake but it happens okay so idea is use a common array and you give you use the you create a temporary counting array for each string and then you store to the common array by using the minimum value and later on you just create a list of string and then store into it so don't forget you if you have two then you have to move through two times and you feel one just move through one time and space and time so space uh all of 26 and all 26 and then of 26 for each string so although 26 plus of 26 plus 26 i you plus n time right or one plus one time so it's going to be all of n maybe of n plus time of n times 26 so uh should be constant and the time is all fun that you do through each stream so time doesn't matter time is the same so later on you store into the answer list of screen and then you'll get it alright peace out
Find Common Characters
maximum-width-ramp
Given a string array `words`, return _an array of all characters that show up in all strings within the_ `words` _(including duplicates)_. You may return the answer in **any order**. **Example 1:** **Input:** words = \["bella","label","roller"\] **Output:** \["e","l","l"\] **Example 2:** **Input:** words = \["cool","lock","cook"\] **Output:** \["c","o"\] **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 100` * `words[i]` consists of lowercase English letters.
null
Array,Stack,Monotonic Stack
Medium
null
238
in this video we'll go over lead code question number 238 product of array except self given an integer array nums we have to return an array products such that the ith element in products is equal to the product of all the elements of nums except the ith element of nums there's also two restrictions the algorithm must run in O of end time and we cannot use the division operator okay so first let's visualize this to make the problem a little clearer let's say the input array is 2 3 4 5 6 then in the output array the first element would be three times four times five times six which is 360. notice that we didn't include 2 because 2 is also the first element in the input array the second element in the output array would then be 2 times 4 times 5 times 6 which is 240 and the third element would be 2 times 3 times 5 times 6 which is 180 and we would continue doing this for every element in the array now that we've calculated every single product we would return an array that looks like this the values are 360 240 180 144 and 120. so the way we just did it is the brute force method where we just manually calculate every single product this gives us the correct answer but as you can see this runs in O of n Square time so how can we reduce this to O of n time well take a look at this notice that we did five times six three different times here we also did three times four three different times and we did two times three times four two times the point I'm trying to make here is that we're doing the same calculations over and over again and this is what's causing the inefficiency so to improve this first notice that each number in yellow is actually the product of two components which are the product of all the numbers to the left of it and the product of all the numbers to the right of it so instead of doing these calculations over and over again we're going to calculate just once the products of all the numbers to the left of Any Given element and the products of all the numbers to the right of any element here's what I mean so again assume the input array is 2 3 4 5 6. let's create an array called left which will hold the products of all the numbers to the left of Any Given element since there is nothing to the left of the first element we can start with the second one the only number to the left of this element is two so we'll start by just putting a 2 here for the next element the two numbers to the left of it are three and two but instead of going back to the input array we're going to multiply 3 with this number here that we just calculated and you'll see why in a second so three times two is six next we'll do the same thing we'll multiply four with six because six is two times three and so this is where the efficiency comes in instead of going back and doing 2 times 3 again we're going to reuse our previous calculation since we already did it so 4 times 6 is 24 and lastly we're going to multiply 5 by 24 because remember 24 is 2 times 3 times 4 so this is 120. we're now done finding the products of all the numbers to the left of each element so next we're going to find the products to the right using the same method but going backwards again the last element has nothing to the right of it so let's start with the second to last element the only number to the right of this is six so we'll start with that then we'll use the same method as before 5 times 6 is 30 so that goes here then 4 times 30 is 120 and finally 3 times 120 is 360. I'm going to fill in these blank spaces with ones and we're finally ready to calculate the final array all we have to do is multiply each element in the left array with its corresponding element in the right array to get our answer so for the first element we're going to do 1 times 360 which equals 360. next we're going to do 2 times 120 which is 240 and it's the same thing for the rest of the array and we end up with the same answer as before since creating each one of these arrays runs in O of end time this overall algorithm also runs in O of n time now before we go into the code it turns out we actually don't even need to create these two arrays we can do all of this using only the output array and so I'll show you how to do that in Python this time the nums array will just be 2 3 4 5 and the first thing I'll do is take the length of the array and save it in a variable called length since we'll be using this a lot so length will be 4. next we'll create the products array which will contain our final answer and initialize it to be all ones then we'll start calculating the products of all the numbers to the left of each element using the exact same method that we discussed earlier remember there is nothing to the left of the element at index 0 so we'll start at index 1. so like we did previously we're going to multiply the I minus 1 element of the nums and products array and write it to the ith index in products so to start 1 times 2 equals 2. next 2 times 3 equals 6 and finally 6 times 4 equals 24. the next step is to calculate the products of all the numbers to the right of each index but instead of creating a new array we're just going to store the products as we go in a single variable called write and we're going to initialize that to the rightmost element in nums which is 5. then we'll enter a loop that traverses backwards through the arrays and let's break down this line a little bit more so we're going to be starting at index length minus 2 which is 2 because we know that there is nothing to the right of index 3. the ending index is negative one because remember when using the python range function we don't include the ending index so this Loop will Traverse backwards until it reaches index 0. and lastly the step size is negative 1 which means we're going to be decrementing I okay so what we're going to do in this Loop is multiply each element in the products array with the variable right so right now 5 is the only number to the right of index 2 so we'll do 6 times 5 which is 30. then we'll update right so that it's now the product of the last two elements of nums so 5 times 4 is 20. next we're going to do 2 times 20 because 20 is 4 times 5 which is the product of all the numbers to the right of index I so that's going to be 40. we then update right to be 20 times 3 which is 60 and finally 1 times 60 is 60. write is updated to be 120 but this doesn't even matter because we're already done the only thing left to do is to return the products array and we are done
Product of Array Except Self
product-of-array-except-self
Given an integer array `nums`, return _an array_ `answer` _such that_ `answer[i]` _is equal to the product of all the elements of_ `nums` _except_ `nums[i]`. The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer. You must write an algorithm that runs in `O(n)` time and without using the division operation. **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** \[24,12,8,6\] **Example 2:** **Input:** nums = \[-1,1,0,-3,3\] **Output:** \[0,0,9,0,0\] **Constraints:** * `2 <= nums.length <= 105` * `-30 <= nums[i] <= 30` * The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer. **Follow up:** Can you solve the problem in `O(1)` extra space complexity? (The output array **does not** count as extra space for space complexity analysis.)
null
Array,Prefix Sum
Medium
42,152,265,2267
1,669
hello guys my name is lazaro and today we'll be doing a decode problem this problem is called merge in between linked lists you're given two linked lists list one and list two of sizes n and m respectively now this right here already tells me that both lists would not have the same size they could have the same size but they might not have the same size remove list ones nodes from the eighth node to the b node and put this two in their place okay so we want to move everything from the eighth node to the b node that means that we care about the position of every single node so instead of looking at the value of the node we want to look at the position of that node the blue edges and nodes in the following diagrams indicate the result all right so let's now actually look at this let's look at the first example here list one is zero one two three four and five then list two is a million one and million two a is three b is four they made it pretty easy for us by making the value of each node correspond to the index so if a is 3 then we want to remove this node right here and we want to go from 3 all the way to b and since b is four it's just these two right here so we kind of want to take these two out and shove list two right where they are and here in the second example the exact same thing we want to remove everything from position two to position five and in its place let's insert list one so let's i'm gonna write out this first example now list one whoops starts off like this one i mean zero one two three four five we want to remove three and four then we have list two which is let's just call it seven eight nine and then 10. so what do we want to look at here well we know we're going to be inserting list two let's call this l2 right here this is one there we go that's one if we know we'll be inserting list two then there's two things we want to keep hold of we don't we want to keep hold of the head and we also want to keep hold of the tail because as soon as we reach let me close this chord as soon as we reach an index let me also write out what a and b is sorry about that a is equal to 3 b is equal to 4. as soon as we reach an index where the index i is equal to a minus 1 we want to change that pointer at that index so in this case a is 3 so 3 minus 1 is good b2 as soon as we reach index 2 let's update its pointer to point at the head of list two so let's change this pointer and make it point to the head of list two then assume uh on the other case as soon as we reach an index that's equal to b so an index that is 4 right here let's make the tail of list 2 point to that node therefore if we return this list we would be getting 0 1 two seven eight nine ten and five because we change the pointer of two to point at the head of the second list and we change the tail of the second list to point to the node after b and that's really all we want to do for this problem the main thing is to keep track of the head of the second list in the tail the second list and at the proper indices change the pointers to point to the head and then change the tail node to point to the node after b so now that we know how to solve this let's get right into programming so head is going to be equal to just list two because list2 is already pointing in the head and tail this for now study equal to none but let's iterate over list two and while we're iterating over let's be updating the tail so after this runs we have both the head and tail of the second list now we want to keep track of the index just in case the list one is not perfect like this let's say list one could be five seven eight twelve and such in this case uh 5 does not represent its proper index 5 is actually index 0 so we want to use this outside variable to keep track of that also let's have a answer variable look at the head of list one so we can return that later on now while list one if the in the current index were on plus one is equal to a then let's save the next nodes in a temporary variable and let's update the current pointer and make a point at the head of list 2. let's continue iterating over those remaining nodes else if i is equal to b then tail dot next is going to be equal to list1.next this is exactly what we talked about right here i is if i is equal to b right here so at this four right here let's make the tail point at the next node after four now another way you can do it is if i is equal to b plus one so plus one that'll make i equal to five and it'll be the exact same thing so either way it will work out but this is just the way i did it now once we update the tail of list two then we're completely done and we can break out this while loop but if none of those if conditions are met then let's just continue iterating through list one let's remember to constantly be incrementing our index position now let's return answer so let's see if we made any errors by submitting okay we didn't let's submit and perfect it gets accepted so hopefully you guys were able to understand this problem this video helped you if it didn't make sure to leave a like and subscribe but other than that i want to thank you guys for watching thank you
Merge In Between Linked Lists
minimum-cost-to-cut-a-stick
You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively. Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place. The blue edges and nodes in the following figure indicate the result: _Build the result list and return its head._ **Example 1:** **Input:** list1 = \[0,1,2,3,4,5\], a = 3, b = 4, list2 = \[1000000,1000001,1000002\] **Output:** \[0,1,2,1000000,1000001,1000002,5\] **Explanation:** We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. **Example 2:** **Input:** list1 = \[0,1,2,3,4,5,6\], a = 2, b = 5, list2 = \[1000000,1000001,1000002,1000003,1000004\] **Output:** \[0,1,1000000,1000001,1000002,1000003,1000004,6\] **Explanation:** The blue edges and nodes in the above figure indicate the result. **Constraints:** * `3 <= list1.length <= 104` * `1 <= a <= b < list1.length - 1` * `1 <= list2.length <= 104`
Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them.
Array,Dynamic Programming
Hard
2251
299
MP3 Hello Sunao I Hope You Are Doing Well So today we will discuss the next question of the album master sheet. The name of the question is that of Britain. So first of all friend and my request is that it is okay to like this question because There are 20 very good questions and one of them gives a very nice idea to you people, okay then like it, I am not able to understand why people have disliked it, okay then like it once. This has to be done so that its like to this like receiver will be fixed and the recording of conception honey problem in a little time to the people goes away till then we grow and plain gold and caused him with your friends you right down the The secret number is to the friend. Guess what the number is. We put the cigarette number like 1234. Now we want our friend to gas the number. Tell us that this type of guessing game is going on. So when our friend is gassing then we interrogate him. There is a sunshine of information and what is Hindu The Number of Girls Those four digits Sindhi Gas Darling Correct Position The Number of thoughts Digit Sindhi Gas The Times in Vashikaran Number Targeted in Europe Collision which is 1234 If you put a number then your friend is gassing Hai tu 1431 adhoi 312 kya hai and if your friend does gas then it is in the same position and some letters can be added which are placed in the wrong position in her gas, then those which are placed in the wrong position are fine, we are calling them accounts and Those who are placed at the right position are calling them roles. Okay so give any cigarette tobacco cigarette friend gas which is our secret number that scene in China and who will friend gas karega number ko kaise stream hai end return dahan forum friend at time this return Member states of is it ok to return a string and hit how our format should be that the egg white that we will be interpreting should also be in the format this number of them monkey how many number of matching spring from and bike so number of the match and From the position this question is there and IMO this question is cleared but you also have to handle this duplicate case that when secret and gas have duplicate it's content then we have to consider the duplicate digits once. It is okay to read this question and it is such a hard question, first of all we take the example 18074 600, then we try to apply the algorithm, it is 1807 and 10, so what will we do first, okay, we will make two maps, okay map one. And I two now how will we interpret these maps okay now first of all the map which will be your care will be of Komal inter type okay now why did we mind the pair because this is the spring we will access a character of it okay one if If you access the digit then the character will be in the form, so I got the character and its programming mapped, then care comment came, then what did I do, now I ran a loop, okay and saw that this first character is matching with the gas of the secret, then it is not matching. If I am not getting it, then what should I do? I will stop the calling towards youth and get the seven's corresponding one shoulder done. Now coming to the second character, at and add are getting painted. I will update you then I will bulls. Once upon a time, it's okay, now 041 matches are happening, here I have come up with a pointer, 041 month is the thief, so I will store its corresponding beam mapping, zero and what will come here, once upon these is okay and what will I do now. I am definitely matching 140, even 20 are not messaging then what should I do, from now on 2000, court has zeroed crush port beam, morning bulb is on 90, so you are able to see, one bowl add one boil and If the remaining three latest ones do not match mine then the suicide of three then this example is cleared because if there is no duplicate case in it then you have clearly said that you are close and close, it is okay, that egg means one fare, your number and the number of angry matching actors. And the free care number of the match, the characters are neat, so the actress is also done here very easily, but give a new example, like 1234, 0111, then see how to delete 11123 and 051, okay, so what should I do now? First of all, are 140 matches happening now, then no, my map is fine and map 2 is fine, so 180 matches are not being made, it is fine, if the words are not romancing, then Ponting towards Bhavan, good and the latch of zero. Also, are they doing one-one match? That Also, are they doing one-one match? That Also, are they doing one-one match? That one of mine, this one is the only one, and this one is the one of second position and is matching, so will I update the boobs, will I update them? World, okay, now you and one match. If you are not doing then folding towards two and here ponting towards the building 1341 to match otherwise the methods will be crust neat and by closing here only that ponting will start then what side will I do now I will close my map again I will do light weight, okay, I am telling the algorithm, how I am calling this question, okay, now I will do internet on the map phone again, okay, now on the weapon, if I hydrate, then what did I get? If I do 1482 m1, what did I get? I got 101. Okay, now I will search that this one of mine became the one who became the first position. Is this map a woman president? Is this my first position? She is present in the map. Yes brother, the president is yours, so you are recent. Look, this is presentable, good China. If I am the President of then I will take its minimum and its minimum, whichever is the minimum of these two, what will I do in it plus the smell of will I get it done, then what all has been created in the account, here the frequency of the forest has become an elephant here and its pregnancy is this. If you say the fruit, then the minimum frequency of what I want to make is safe in one and two. What is your minimum frequency, if sowing is your one, then look at me here, the mind and intellect have become 1. So this is your mind, but it is okay. You guys will see a lot of YouTube videos, what did they do, basically, but no one is telling you this, it is okay, and I don't know how, I am not speaking ill of anyone, but example 2, no one explained it, okay. So you have come, now this question is clear to you and you must do so much work that you will like this question. Okay, so friend, what do you do, friend and I have explained the approach. Okay, no, I don't understand. Now I understand what to do comfortably, read it comfortably, learn to approach the question and understand it, then try to fold it on your own, if you are not able to figure out a single code, then only you can see my section with one code, is it okay then we start voting. Now let's say these words, okay, I initially consider Balls as a hero and he is also zero one, so why is this zero, the British, because friend Bulls has himself said in it, the matching character is for them, take a pause for them from the Bolero message character, okay? I make in gas a nodal order mail flint end now I make one and map two I mean don't ask where this rocket science came from that care ko mind is your man and define that first tell me stick is ok Okay, you look at what it means, how cool is the mind to code, okay, and in the anti equal to zero firm, what should I do on the secret string, I will make it light weight, okay, I hydrate on the cigarette spring, okay, what else did I do, and I What to do, get the chapter completed, this secret of itself, the secret of I is equal to that of Gasofire, okay, what am I doing, I keep hydrating the C character, I am checking, what friend, this is what is in the secret, this is its first position, its First position is ok and if I get it then what I do is I am doing it plus this is what I was doing whatever approach I taught and if not then what was I doing otherwise what was I doing both I was updating my so how to do now I am one gas of i plus ok now we map you main tu ki aap gas map me to secret aayi cigarette i c grade five plus and map two gas of i plus ok so It has become so much for me that I have got it done at less in both of them, I have got both the characters done at less and I started mapping and if they are same then I have made brisk plus now what should I do friend that frequency one. My concern is that I will see it and I will update it as soon as I can. Okay, what is the minimum frequency, now what is the meaning of frequency, then it will be returned to me and in that and to it, I have grown up in the travels now. I have traveled on weapons, so think about it, I came to the forest, okay, now it is okay to take a second example and see, I have read the second example, it is okay to take it, now what will I do with this map, which has given me a character like being locked in a bank. Okay so I got it 101 I will see you see if this character is my importance then I break file map you I find what find ID dots so this Muslim on this one on those so this Muslim on this one on those so this Muslim on this one on those how to access white first okay if that I get it in the whole, I am broken and the map is broken, it is okay for me, this one will increase and if I get it, then return that minimum frequency and return the minimum frequency. I suggest life to become a mother and in the second one, my mind was commenting that So what I will do is take the frequency of this which is ok and the frequency of this and return the minimum of both of them in the previous luck and in that it is said that surplus is equal to two means give plus to this the minimum of this one, how do I access them. I will do it, if he has come to the party, then IP and second IT dot second I don't second, okay which is in the second match, no friend, how will I update this, then I will not say anything, now I will not say anything, I will only say that I am you IT dot first Be it IT dots, you did not understand, there was no stressful thing, Baghwa is okay to go to the office, I said, I am fine, I got it made, you filth, you made this guna of mine, this first one became that important, the president is all for him. Make this I this one is 128 I two so okay hmmm I am you the president now what to do he will find out the minimum of IT two then how did you access this one because if it came in IT then I don't second now its map Now how will you access this photo, first you will have to mix the format, so I am saying this, I made it in IT dot print, so I am Pooja class, the map is in the one position, if this is completed then that is completed, I hope you I understood and explained in a very sweet way, okay, so this case is also cleared for me, now what should I do, should I return the answer, no, I will not return because he has said this, brother, give it to me in this format. If I have the opportunity then what should I do, friend, what should I do, I will not do anything friend, I will kill the format of my answer first, in which format was my answer, now in which format was my answer, what should I do, or first of all, the balls are one of mine. It came in the number yesterday, okay, I will convert it into this film, what will I do next to it, I will plant a tree and then if all this turns out to be Kuch Mittu, then I will convert it in Metro City because it has been given in biotech format. This friend's boss's boss and I now put it in front of him, so this point looks at me, a policeman is also okay, so I think this thing should go to the court, then the net is closed, there is another record and it will go in the court, because here I have seen this. Not removed ok that's what I think also code total time this course will run ok yes I said it ok R let's check and your hair etc is not there etc I can't see it but it could be And the commission submits this accept and looks at the figures. By submitting this dough, have you accepted? Friend, this code has been cleared by you, okay, this is a very cute question, please like it in this puja, okay, that's why the questions are not set up but in the album. Master should I hope you understand what the patterns are and why this seat is so good okay covering all the patterns okay so let's meet in my next video with questions till then let's study. please wait and suppress the request
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
1,862
That welcome back price today lotu year print code problem 1962 time to flower tree aa so let's locator description give research problem notes with 902 - 1410 is the root node problem notes with 902 - 1410 is the root node problem notes with 902 - 1410 is the root node and parental mode of noida this is father aaye na mintu water the tree sprinkle water on the Road not the water will load in every age from father of noida and noida came in course of time after hi how long it will take to flop water to all the notes types of these water problems so they can imagine that now this problem is skin Google So You Can Imagine The Trees Gave One To Has Said To Have Given Us A Tree In The Form Of This Don't Like It Is The Father Of York Share The Input Which Padre And Share Father And Time Edit Swift One Is The Father Here And Second One Is The Time There Should Be Glad You Can See But Will Look Like Decide 0232 500 Basically Half Sworn In Odd One And Two Its Father Is Not From 1000 Tunis Hair Saudi From One And Two And Its Fa Dowry Given In The Forest And This Time There is how much time it will take to reach from a root to back 98030 Artist 13 time 0250 235 time Maximum time he is giving bribe takers for more than 300 Maximum time it will take to reach from a root to country Not to time with fans After this what they had to return so that is the problem so let's take Pawan example over clear sharp and explain your rate how they can solve this problem so why have taken one tree air tight entry is like zero 12345 6 notes from total and the distance Has Also Like The Times 1802 Andar Time Will Be 302 To The Times 5123 The Times 2124 The Times 4250 To Z So Have To Find What Is The Maximum Time But Will Be Taken To Reach From Drut Note 021 Off The Lift No DP Yadav Lift Will have the maximum time right you are traversing sorry for example if you look at this tree day scientist this the time maximum time taken 12022 and two cigarettes minus five plus two it is equal to 15-8-2012 a answer 15th with answer Water all the 15-8-2012 a answer 15th with answer Water all the 15-8-2012 a answer 15th with answer Water all the parts of the two how to find right in distic for example you can go 2021 and one to three for the time for this will v5 f3 plus two is equal to 5710 tier-3 white plus two is equal to 5710 tier-3 white plus two is equal to 5710 tier-3 white veervati 021 and want two for the part plus Point Se 180 Dear Son Father 302 2125 To Take You Like Five Plus Two Is Thirteen Agro Take Care And The Last 102 And To 6 Difficult 100 Is The Maximum Times You Have Written 1580 The Answer For This Problem Null Solan-Means Background This Changes The Time Solan-Means Background This Changes The Time Solan-Means Background This Changes The Time and clear is to listen one love what will you give ur going to solve this problem using amused when you used for search of dam district and will user right in the javad a receptive busy why come and first meet creator of maps will this Rhythm App Will Show Is The Father And Children Basically Rights For Example If You Take Classes In Its Children Want To Write Achievements How You Will Create Map First Benefit One Close Children Is Three And Four Right Like This Thank You To The Children Is 568 Like This loot creator map from given a right to edu size maintain so war can look at the code and they can laugh and solution when it will be easy for you to understand the father has given time has given sources created to map vintage play List Of Cities And Violets Because You Have Multiple Children Great Souls To Please Her And You Will First Withdraw The Father And Will Just First Viewers Creator MP List Vikas Dar Will Not Be Any Children And The Time In The World And The Amazing Child Father Died From Ape You'll Get Father Aye And When Will The Year Or Two From The Map Are Like This Basically I'll Have One Commando Basically It's Children's Rhymes For That's What You're Doing This Year And After That Will Do Our Person Cycle Pred Fus Will Create a cue and will and child intuitive and person you and will create one a good time to reach no data will explain you so sorry for the benefits will work for this problem ride so what we will do in the benefit of the offerings made from the Root Rights Will Just Offer Root Node In To The Cube Solve 140 And Time Distance Between From There Is Not Distance To Travel From The Water 2000 Inside To 800 Years And In The Next Station Cons Benefits Nests 111 Track Suit For Example This Point One Level dows one number will give this one and two is another level date for the face and in this three four five six is ​​another level tricks that face five six is ​​another level tricks that face five six is ​​another level tricks that face work situation level 511 basically a it's withal on top and liquid code choose them 1111 soft smooth insulted 20 days Indra Ne Institution Which Will Come Out And In Which You Like This Is A Lips 98100 Will Edit Children's That Bread Lineage And Distance For 153 Light Is Given To 10 And Will Have To And Distance Between 5.2 Great Will Have To And Distance Between 5.2 Great Will Have To And Distance Between 5.2 Great As You Can See In The Craft Fair And inverter year distances fear and five years where later this au yar done now with this level weldon navratri 2012 on next level for the time will points 138 and will change your positive where is not a lips not right some will and its children Traveling From Foreign Land In The Tube Software Hui Have To Go To You To Calculate The Time Rates In Three Plus Two So Will Say Three Come After Five Years In The Native Village And They Are Waiting For The Time Will Be Plus 34608 Which One Will And On Tomorrow Morning New Year Tasting Avadhesh 153 Loot 2525 Poling From A Few Shovel And Power 65 The Distance Between Five Plus Sure Let's Celebrate 532 You Will Here And Went For The Series Distances 50 Things 5856 Villaval Distance Time 15th Shaili Vikas Five Plus 0 Hai So Now Will Gurjar On This Level 9 And They Will Keep Falling Leaves Means Navratri Louisville Paul First Sadhi Hui From Now You Will Keep Track Of The Maximum Time But You Have Years Singh Actually The Time Will Only Notice Thursday Visiting Include Three Election Thursday Taking Off To The Time Will Update Maximum 125 Ride With Speech I Have Seen Listen Swift Strong Pure Time Will Update From 527 Developed Is More Than Five Nine At One Will Polish 531 Handed Time Hui Updater And Max From 723 10 And for the next not with politics cot 15sou will have to update and max from 3258 will keep track of what is the maximum time you have seen and this time as you see the curious MP3 Awadhesh nothing to process in you shola and phase complete so e will just return our maximum value clear f5 press the answer to this question is so that is the cockroach 215 is the maximum time date will take from the route to the lift 600 water can trickle down to the point face eight hundred so let's you go through The benefits have created new frontiers and weaknesses after root of the right and will just like you or not it will create one variable to keep track of time and will always take of the right for that and they will put all the number of elements of the Most number of the elements from the rate elements from the rate elements from the rate current element and you will who is the father element write the father and to get the current affair basically father this is given to him raised for example clear is UC this is the father is well organized Better father and to get current affair retained for the current affair your feet is equal to minus one minute is updater time tourism board the current 2004 example where no d90 takes only zero time basically choice but they are doing a year but for the road to have To add the previous time sites on time to research note current equal to time to record current affair plus the time of current for example of what they are doing this you for visiting not want to here right before visiting not one day you have to add the time to reach 2000 plus the current time lord which is 630 plus 3 which is equal to three for this what they are doing here basically and they are updating overtime tourist note will also have values ​​for this is not s t input values ​​for this is not s t input values ​​for this is not s t input similarly for the Value 158 Like Best Actually 14213 Daily Will Have Three Plus Two Uvi Benefit Five Year Subjects Of This For You Can Read And Saudi Seven Camp Like Three Plus Corey 700 Datas True Yaar Doing One Year And After That You Will Get Number Of The Current Not Right Listen to the current node for example you are zero will get number one and two tight and will process that one and two you are not wealthy will get its neighbor has three and four basically so let's move to years and have never is not difficult which Means The Tourist Dalip Not Follow Does Not Have Any Children Should Not Have Never Saw In That Case How Would Have Been Checking For How To Update And X-Ray Development Has Happened While Check Update And X-Ray Development Has Happened While Check Update And X-Ray Development Has Happened While Check In That Case Software Did Updating And Mexico Year Finding The Con Is not distance with this month and maxists unlike software engineer Adarvais Vaidya who *duck you for bf website for example if they are *duck you for bf website for example if they are *duck you for bf website for example if they are adding zero life including one 240 to z 12512 on the few basically one in every three and four suvidha and three and four On to the Tubelight software doing a year or so and so will be oil that is basically solid will continue to follow will continue and key processing all the notes in the string and will keep updating the maximum value whenever it is the lymph nodes light when every Creation from last three for example for five six digit will update the maximum value and India's server maximum velvet comments 1580 solid business 80s time which time will return which is an answer so that is the approach to solve the time to flower tree problem hui thing my Google 100 up going to take off I will take per examples and have given year so let's check the example of 220 a little while so thanks raw taste 100 car passing out I am soy sauce testis passing kar hui thing yer getting fibers and Answer I'm sorry for that we can't see the example as well so let me just make one example so The One that has just seen at the should you in The Temple Near Last Century Only Exam Clear 100 How To See Stands For This Is The Same Example Is Prevented The Father And The Time Has Right And Preserve Running Weight For The Temple On 200 Abs You Can See Now It's Pristine Is The X Factor 1015 Is Why Do You Are Getting Hurt So Let's You Explain Shyam Like It Working Fine Should Submit Incoming Vote Now I Sagar Code Is Ganth Accepted By Liquid Swar Solution God Accepted For This Is The Way You Can Solve Time To Flower Tree Problem Using Deficit And Acute And Map Your Notes of Splendor Also If You Have Already Check My Play List Narrate Creator Play List for Lost All Its Solutions for the Name of the Playlist Is List Solution Its Soil Check Out Peeth Aur Eight Saal Problems with Examples Explained in Details with Jakhar S Well S It's Job Interview Related Places Where Is Discussed Couple In Clothes Videos Discuss Voter Frequently Asked Questions For Java J2ee Interviews Aa J2 Recording Interviews And For Interview Sorry For Preparing For Interview Please Check That It Will Definitely Thank You And If You Like This Video Please Subscribe And like this video mix, definitely subscribe to the channel and subscription will come helper riching this channel to more people so you can also get help from this video स्वप्न दोश help from this video स्वप्न दोश help from this video स्वप्न दोश subscribe thanks for watching this Video.
Sum of Floored Pairs
count-apples-and-oranges
Given an integer array `nums`, return the sum of `floor(nums[i] / nums[j])` for all pairs of indices `0 <= i, j < nums.length` in the array. Since the answer may be too large, return it **modulo** `109 + 7`. The `floor()` function returns the integer part of the division. **Example 1:** **Input:** nums = \[2,5,9\] **Output:** 10 **Explanation:** floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0 floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1 floor(5 / 2) = 2 floor(9 / 2) = 4 floor(9 / 5) = 1 We calculate the floor of the division for every pair of indices in the array then sum them up. **Example 2:** **Input:** nums = \[7,7,7,7,7,7,7\] **Output:** 49 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 105`
null
Database
Medium
null
637
hi guys welcome to algorithms made easy in this video we will see the question average of levels in a binary tree given a non-empty binary tree we need to a non-empty binary tree we need to a non-empty binary tree we need to return the average value of the nodes on each level in the form of an array in this particular example the average value of the nodes on level 0 is 3 on level 1 is 14.5 that is the sum of on level 1 is 14.5 that is the sum of on level 1 is 14.5 that is the sum of these two divided by the number of nodes that is 2 and on the second level the average is 11 that is sum of these nodes by the number of nodes and so our answer would contain the array or the list of all these numbers or averages that we have one thing to note here is that the range of nodes value is in the range of a 32-bit signed is in the range of a 32-bit signed is in the range of a 32-bit signed integer and can go to a maximum of value of the integer also and can also go to the maximum value of the integer so we cannot work with an int value but we need to take something bigger than that so that we can accommodate the sum of more than one integers with the maximum value so let's go ahead and see how we can solve this question let's consider this example that was given to us in the question the level of traversal would look like this and while you are taking the sum and average that would look something like this the size of the nodes in this particular level 0 is 1 and the sum of all the nodes present on this level is 3 and the average would be given by 3 divided by 1. similarly when you go to this level the sum would be 20 plus 9 that is 29 and its size is 2 as we have two nodes in this level the average would become 29 divided by 2 which gives us 14.5 which gives us 14.5 which gives us 14.5 on the last level we have two nodes so the size becomes 2 and the sum of these nodes is 22 and so the average becomes 22 by 2 which is 11. now how do you traverse in the level order we have already made a detailed explanation on the level order traversal in our tree data structure series so if you haven't watched that yet and if you are not aware of how that works i'll recommend you to first go and check that video out the link to it is in the top as i am not going to explain to you that how a level order traversal works i'll only be telling you how this question can use that algorithm with a small tweak to give the result that is desired the link to that video is in the top and also in the description so go and check it out first and then come back to this video to see what tweaks we make so here's the algorithm that we saw in the video explaining level order traversal wherein we initialize a queue and a result list initially we add the root node into the queue and loop while this queue is not empty then inside that while loop we take a temporary variable for storing the size that would contain the number of nodes that are there in that level and so that temp size would be equal to the number of nodes that are present in the queue at that particular time and then we loop for that particular size of the current level and then try to dequeue an element or a node each time and add that value in the result list to show the level order traversal after doing that we add its left and right to the queue for the next iteration and decrement the size of that particular level elements finally we can return the list now this was the algorithm for level order traversal wherein my result list will contain the order in which i am traversing on each level from top to bottom and from left to right now how can we use this algorithm a small change as we can see in the yellow would be made in the previous algorithm so as it works for this question so since we need the average we need to find the sum so we initialize a variable sum and instead of adding the current value to result we will add that value in our sum variable and instead of a while loop here i am using a for loop for the temp size that we have found that is the size of the nodes in the current level when we come out of this inner for loop we will have sum and the size with us and we can calculate the average by the formula sum divided by temp size and then we add this average in our result list and finally we return this result list so this small change in the level order traversal algorithm would make it acceptable for our current situation so let's go ahead and write the code for this algorithm so we will first have our result list and we'll also initialize a queue after we have this queue initially we add our root element in the queue that would denote the level 0 elements after we are done with this we will be iterating while the queue is not empty as we saw in the algorithm and over here we will take a variable size which would be size of the queue at that particular moment that is given by q dot size and we'll take a variable long sum that would be 0 initially now i'll iterate 4 in i equal to 0 to i is less than size and over here i need to pop an element from the queue add the sum and then add its left and right in the queue when i come out of this loop i need to add the average in my result finally i can return the result and that's it let's run this code and it's giving a perfect result let's submit this and it got submitted so the time complexity over here would be o of n that is number of nodes that are present in the tree and the space complexity would also be o of n so that's it for today guys i'll see you in another one till then keep learning keep coding you
Average of Levels in Binary Tree
average-of-levels-in-binary-tree
Given the `root` of a binary tree, return _the average value of the nodes on each level in the form of an array_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[3.00000,14.50000,11.00000\] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return \[3, 14.5, 11\]. **Example 2:** **Input:** root = \[3,9,20,15,7\] **Output:** \[3.00000,14.50000,11.00000\] **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-231 <= Node.val <= 231 - 1`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
102,107
349
hello and welcome to another video in this video we're going to be doing a similar problem to yesterday and it's going to be intersection of two arrays so in this problem given to arrays return an array of their intersection each element must be unique and you may return the result in any order so the way you can get an intersection of two arrays is pretty easy so one way is you can turn the both into a set and then you just check um for every item is it in the other item so like in this example nums one would become one two and then nums two would become two and then you just check like okay for every item in here is it in here so then our final result will be two so that's one way to do it you turn them both into a set another way is you can sort so let's look at this example with sorting so if we have four five9 and we have 44899 you can also do it this way and what's going to happen here is we can actually just get R of this now you just have two pointers kind of like the same thing we did yesterday where you have two pointers and you just check like are the elements the same or is one greater or is one smaller and so let's say this was four and this was like one for example in fact we can even change it so let's say this is one so because we're starting at the start and because this is sorted we know that one can't be in here right because if we if it was we would have already seen it we know can't be in here but four might be in here like we might be able to like keep going up and we might able to find it so because this four is greater than one we're going to move this pointer up over here and now these are equal so if they're equal we're going to put this result into our result so we'll just say like four and we want to avoid duplicates like let's say this had like three or four fours like this was like four so anytime it's pretty simple what we can do to avoid duplicates we can just take one of the pointers and just keep moving it up until we hit another number so if this was for example let's just say this was 444 right like four and we were on the here now we can say it's equal but we want to make sure we don't keep hitting this equality so we just pick one of the arrays let's just say array one and we keep moving it up until we hit a number that's not a four so we move it up here so now um we could move them both up but moving them moving one up is fine like that'll do enough so now we check okay four is less than five so we've already checked this four so we don't need to like and four can't like even if four was in here we already looked for it so we didn't need to do that but five might be in here we still haven't looked because we're only on four so we're always just going to take the smaller one and move it up so we take the smaller one move it up then same thing here we've already checked for the five if we would have seen it like we would have added it in already cuz we're at the eight we and this is increasing order so we move the five up to the nine now same thing again we always move the smaller one up if they're not equal so we move this one up now they are equal so we put in a n and as before as soon as something's equal you just pick one of the two rays and you keep moving this up until you hit a new element so in this case we'll just be out of bounds then once we're out of bounds on one of them we're done so we just return 49 so very similar to yesterday this problem you either use a sort and a two-pointer or just a set sort and a two-pointer or just a set sort and a two-pointer or just a set intersection so let's code out both of those is pretty easy so one thing you could do and so for set there's a couple things you can do in Python so you can say like set one equals nums one let's say except set so you can pass in an array into a set and it will turn into a set so set two equals set nums 2 now there's a couple operations you can do on sets that a lot of people don't know so one thing you could do is set one minus set two which will mean every element that's in set one but not in set two you can obviously do the other way around set two minus set one so that'll be every element in set two that's not in set one you can do set one plus set two which means every element that's in either one it will combine them together you can do set one and set two meaning the element has to be in both and you can do set one or set two which I think is the same as set one plus set two we can even try this out so let's just say um so if we print a couple things so set one plus set two let's print set one minus set two and let's print set one and set two and finally the last one is the or so I expect the or to be the same as the plus but let's see don't recall exactly and finally we'll just return this one so let's see how this goes maybe plus doesn't exist unsupported okay so plus is the same as the or I'm pretty sure so I guess there is no plus but it's the same as the or so let's see now hopefully all these work okay so let's take a look so for this first example um set one minus set two is every item that's in here that's not in here which is the ones the second one was set one and set two which is it has to be in both which is just the twos and then the third one is has to be in either one so that's that and we can even show this with another test case let's say we did like two three can we run this should provide us the right stuff so let's take a look yeah so set one minus set two which is the ones um set one and set two which is only the twos and then the ores any item that's in either one so all these work and so we can even make this a bit shorter so we can just say return set nums one and set Ms two so it has to be in both and um I misspelled it okay and when you return um when you return a set even though it takes a list it's still like the type is still fine I think it just converts it into a list so you can technically do this if you wanted to but I think this is already done for you under the hood could be wrong about that but I'm fairly certain that's the case so either one um so now let's do the two-pointer so for the two-pointer two-pointer so for the two-pointer two-pointer so for the two-pointer pretty easy so we're going to sort both of these so we're going to say nums one sort nums two sort have two pointers just like we did yesterday so i = 0 Jal just like we did yesterday so i = 0 Jal just like we did yesterday so i = 0 Jal 0 result array and we'll just say while I is less than num one uh length nums one and J is less than length of nums 2 so essentially these both have to be inbounds we'll just compare them for equality now right so if nums 1 I equals nums 2 I then we want to put this item into the result and we want to take one of these arrays and keep moving with the pointer till we get a new item so we can just say like while I is less than we'll just move up the first one well I is less than length of nums one and nums one I equals the item we just put in so the item at res negative 1 we'll just keep moving this up so we'll keep doing that so our other case is um other case is if nums one is less than nums two then we want to remember we want to move the smaller number up so we'll say i s equals 1 here this should be a j by the way so I plus equal 1 otherwise um we move the other one up because it's the last case right so else J plus equal 1 finally we can return result so this also works with a sorted two pointer um oh right this should be nums one I see nums one I okay so let's take a look uh we got a wrong answer so we probably screwed this up somehow so let's see how we screw this up so while this is fine if nums one res one appear pen this while I is less than nums one and nums one I uh this is fine else if nums one I is less than oh this should be J there we go okay so there you go so that's the other solution so this one is going to be um time o of n login and space 01 and the set solution is going to be time o n and space o n so whatever you prefer just two different trade-offs prefer just two different trade-offs prefer just two different trade-offs um and yeah that's going to be all for this one I think I explained enough of it uh and as always if you have questions or anything just uh write in the comments and I'll see you next one thanks for watching
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
350
hey guys how's everything going this is chaser in this video I'm going to take another take a look at another easy problem the 350 intersection of two arrays - I will give in to erase like 1 arrays - I will give in to erase like 1 arrays - I will give in to erase like 1 2 1 and 2 we write the function to compute their intersection like two are both existing these number race right so we return to 2 so 4 9 to 5 and the 9 for 984 a 4 for 9 because for isn't it and a 9 isn't it the order doesn't matter the each animated result should appear as many times as it shows in both arrays well let's see what the basic sample like this well if we just do it naivety we look through the numbers 1 and we were searched for the array to see if we exist or not right and search for the find another 2 and search for it check if it exists or not as such another to check if the exist or not and this - when it is found we need not and this - when it is found we need not and this - when it is found we need to mark we did you remove it or how to say add a blacklist say if it is used occupied so it's like not that easy but basically for the traversal it will cause us suppose these n elements and M elements for each memory it will cost us oh and right with an extra I say I would say the smaller one right yes motor 1 so ok suppose space Oh smaller ok wow this is might not be good enough when we are getting we weren't doing a searching like we have found we need to see that a lot of duplicate searching right 4 to 1 we will loop through all the array to check videos is not and for - especially for these table tools we - especially for these table tools we - especially for these table tools we search for the first two and then search for a second - it's obviously not a for a second - it's obviously not a for a second - it's obviously not a performant actually we could like a pre-process the numbers too - alright pre-process the numbers too - alright pre-process the numbers too - alright pre-process promised to a map of pre-process promised to a map of pre-process promised to a map of number count and now we will do pin through the novice Wong we could just get directly access to the map right if one exists we just check if exist in the map and check the account and we find - map and check the account and we find - map and check the account and we find - of course - isn't it of course - isn't it of course - isn't it and we need to decrement the cow and the for neither - and we found it and then for neither - and we found it and then for neither - and we found it and then yeah and we could just collect these two in the final result and that's it so if we do this we avoid it in that unnecessary search the traversal in other the array for all the elements in the memory and thus we first we traverse through all the nanos - and I'm Swan but through all the nanos - and I'm Swan but through all the nanos - and I'm Swan but they are not the multiply any more they are some so in + M but with extra space are some so in + M but with extra space are some so in + M but with extra space with the yeah it should be Oh same still the main em with the Ming M and we should say process the shorter one right so let's do it so let target which the pre-process so let target which the pre-process so let target which the pre-process target which is the shorter one okay this is not good let Lube target we only switch it if num Swann and then T speaker than dimes to dupe target is numbs cool now we process it right so we will create like a counter map which should be a map element number we will process the process target okay now we finally you live through the roof target right okay before you please to create a result here result array for num loop target if for like for one we need to check count map has it right so if has them not only has them but also the get count get it the count should be it a zero okay we just say yeah it has it's not when it is become is count zero we did it from the map it has it then we with result push numbers in right when we push it we need to update the counter and get now subtract with zero we do with one and if count equals zero it means there is no this there's no this number anymore so delete for the other case we will set numb to this count right okay maybe this is easier to understand we use custom ooh and at last we return the result I think this should work yeah perfect and at the time as we analyzed it should be this space this right and there is a follow-up what if they give me a raise follow-up what if they give me a raise follow-up what if they give me a raise or resort it how would you upped mais our acrosome if they are all sorted like 1 2 3 4 &amp; 2 they are all sorted like 1 2 3 4 &amp; 2 they are all sorted like 1 2 3 4 &amp; 2 5 6 well because they are sorted we could just align this array together right we could just first put it here because they the first number that the smallest number doesn't match so we this one is smaller so you can't could be removed so we align it like this so compare this one they are the same we go to this one a saying this not the thing we not aligned the four five six not the same three should be removed with not allow four or five not the same yeah so we could just keep two pointer like which both Travis to start from zero like I equals 0 to M minus 1 J equals 0 to n minus 1 and we just compare if they are equal right if they are equal we move to both them to next one if not we just a move we just move the smaller one with small values well this is the same so actually if they are we could accomplish with the time with oh it should be what is it mean and write with sort it okay so what if num size is small compared to noms to size which algorithm is better so what is the problem algorithm deep pointer a worse word you mean compared sword well sort it costs as much time than linear time so our this the hash solution will be better what if enemies of two are sorted on disk and the memory is limited so noms two is on a disk and it's limited so that I cannot note the element into the memory at once well we just know them chunk by chunk right we're first cut we first checked okay we can process numbers to first right if it says or numbers to are only on ass disk we could process numbers one first guess the hashmap and the process now is to chunk by chunk right you see we only update the count map of the pre-process the count map of the pre-process the count map of the pre-process target so these target doesn't change we could just move through lumps - yeah by could just move through lumps - yeah by could just move through lumps - yeah by their sub arrays so it's just gone it's not gonna be a problem okay so that's all for this problem I hope it helps us the next time bye
Intersection of Two Arrays II
intersection-of-two-arrays-ii
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**. **Example 1:** **Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\] **Output:** \[2,2\] **Example 2:** **Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\] **Output:** \[4,9\] **Explanation:** \[9,4\] is also accepted. **Constraints:** * `1 <= nums1.length, nums2.length <= 1000` * `0 <= nums1[i], nums2[i] <= 1000` **Follow up:** * What if the given array is already sorted? How would you optimize your algorithm? * What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better? * What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
null
Array,Hash Table,Two Pointers,Binary Search,Sorting
Easy
349,1044,1392,2282
1,732
okay super easy questions today you give it an array in the array you have the net gain and altitude between two points and you want to turn at which we want to turn the highest altitude of any point that we get up to so in this example they have a biker going uphill all right so say for example this if these are the gains and the packet starts at zero then initially at zero then next in the next phase throughout my position minus five then they're at position minus four because they went up a little and then they went up even more up to one and then stayed at one because there was no gain here and then went back to minus six now the highest out of all these is zero i could probably yeah i mean that's fairly simple so let's just start uh keep track of the current altitude and current and the answer like so answers also zero initially go through each of the gains and just current plus equals to g and the answer should be equal to current um the max of itself and current so itself would be zero sometimes in this case we see in this one here these are the altitudes and just return answer so give that a run all right thing is this is linear time i don't know why it's so slow
Find the Highest Altitude
minimum-one-bit-operations-to-make-integers-zero
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._ **Example 1:** **Input:** gain = \[-5,1,5,0,-7\] **Output:** 1 **Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1. **Example 2:** **Input:** gain = \[-4,-3,-2,-1,4,3,2\] **Output:** 0 **Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0. **Constraints:** * `n == gain.length` * `1 <= n <= 100` * `-100 <= gain[i] <= 100`
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
Dynamic Programming,Bit Manipulation,Memoization
Hard
2119
334
There is gas, thousands of questions are going to be seen, their zinc is different subjects, so for money it is said that one is given, that is running, there are 3 such numbers, they are in increasing order and their index will also increase, inverter tap topper. We can come to the question that who has taken the sample test of ours, so if we find such tablets, then this condition is imposed by the members, it should be bigger than 120, this should also be smaller than this and this thing small is fine and in these Scientific Interim Order, you are good, fine. So we see what A is going to be our that any element is assumed to be the first moment Bb also the owner is this and on the left side of this people run from zero to in I- mortgage and see it is found in I- mortgage and see it is found in I- mortgage and see it is found that this i.e. That this dish is found to have a small element, that this i.e. That this dish is found to have a small element, that this i.e. That this dish is found to have a small element, that's the way we dip it on the right side and see if C is found or not, then basically Vinod will say that there is a bigger loot than five, that if it happens, it means that our The answer has been found, yes, we will check it on the star index of cricket, then any contact is not possible, it means that the answer does not give juice and we will have to set the result but it will have time complexity, whereas this of SpiceJet because we are cheated. If people move then it will be towards this contest because we will also use people on access no ok then we need to optimize it further because Surya Square is a bill of many words ok now let's assume that we mean someone What we mean is that if we are setting any of these desk tasks, then what is the minimum element found on its left side and similarly, what is the maximum limit found on its right side and if it is found somehow, then we check. Can this index become B or not and whether its lips are off or not, comes on its right side, that is, it is okay, so why have we made a, left mean, which denotes every index of it or a value which Value will keep the minimum balance from zero to I index. For example, if we talk about this industry, then keep it 5, then it means who has the minimum balance among 012 Indians, then five is there, five is the start, similarly one right. Let's take the name which is the requirement on any index which will be the maximum volume. Let's go to the end - this is for pump volume. Let's go to the end - this is for pump volume. Let's go to the end - this is for pump and finally we will run Bigg Boss. Lastly, while running, we will see that we will go back one index in the left minimum and If you check this one on the index, what is the value, then that interest will tell which of the minimum brothers on its left side, yes, if that medium value is smaller than the current grand then one is the lead, similarly it will go to the right mixer and one Chawla will check on the index if it is bigger than the current one then it will subscribe, it will have to be set otherwise, so here we have oven time complexity, you can comment question but if you click on it then we will open a state cooperative that Now we have used JDA, okay, but in follow up question it is saying, quality improvement solution entry in one time complexity and ovens complexity, cigarette has started to be completed one time, but oven space oxidative is still left to do, okay so? It has another operation group but is limited in itself, I have cases to do forever that we are going to join ABC, it has it and it is paying us also, what is the first fundamental judgment and also we do half percent seconds - element And C is our Joe which is the seconds - element And C is our Joe which is the seconds - element And C is our Joe which is the third number which being the biggest and index Nifty will like the last, this is everything, at that time when it will reduce like this and I tell you, people will run the loop first which is life will start. First of all, first of all, we will see whether it can be made like ours, what is the potential, that is, to make the third number loot like, it should be done, okay, this is the first thing we have done, it cannot be made bigger for sewing, we also need fitting on the side. Can it be made? How can friends become a Muslim? What other condition is there that this being should be increased? It is possible because from a happy internet, we will see fit whether this is a good thing, so can it be made at all, that one taking edition. It is not there, anything can happen, it is maintained, this is our people here, you check, then in the same way, we will decide whether this person is a potential candidate, whether the condition is checked for him, what is lagging behind, what is Mentalmax, this is not big. Ca n't confirm, Saif will do it again, what can be done to recover, what is the condition that it should be bigger than this, it is already a train, if there is one, then it cannot be because it is smaller than ATM, then we will check whether Whatever it is, it can be made, is it not an evangelical condition, but it can also be made right, this already existing acid is smaller than that and now we will make it smaller than add, so we have the smallest value, that is, it is replaced in Will make oil from eight okay so we are our a look at the nation here second space has come then I will check whether the spot is near is the tips made of urad the same condition is it big in the meantime or not Bhim is still international, then check running, can it be made into tractors, that is, can it be got, is there a condition for it should be read, even then it cannot be done, because it is passed and it has eight, even then you cannot get it, then see what? Is it not the same request condition, just have to see in one condition, this is already this age, the oil in these, the number which is already doing this age is one smaller than that, we will replace one, it unites now, that is, the West. And now depression has gone here for the third day, okay then we will see whether it is a quarter inch, is it cigarette acid, is it Mentalmax, if it is not bigger than this, then it is not there, only then is it our circle, come, the next condition is that BSA should be bigger, then 20 more. He has got big so yes so we've got our second smallest value that is we've got twenty Okay then we go to the potato here and then let's see if this could be the third element or this could just be what is the second biggest Is this t-20 add not to be increased biggest Is this t-20 add not to be increased biggest Is this t-20 add not to be increased then can not be outbreak of can also be what is the condition for it to happen it should be bigger I is five and in this and here ten including women so replace B and 10 From A and then here or this expectation then let's see if this can be a potential secret, do we have to check the condition for that, see this, have you read this, where are you busy? So, we have got our thing, there are potential candidates from this. Got the felt tip and our production controller, got 80 more got toffee ready to dance, five of us come out as animated, there are 50 of them, doing it like this, they go into the form, there is no through-through, there is a potential cigarette even at the fall. If it is no through-through, there is a potential cigarette even at the fall. If it is no through-through, there is a potential cigarette even at the fall. If it is not found, it means that there is an answer which does so. Yes, so we understand that the afternoon has been deleted in front of the first Maulvis and second most first is present and one is noting the code and the second is the second one is noting the decode. That means OK and people clicked and the subscribe option is written this number is better than second-most. This this number is better than second-most. This this number is better than second-most. This means that the current element is being checked whether it can become a potential content or second to become a cigarette. Small savings will have to be bigger. If this happens then we approve it there and get our answer. If it does not happen then we check that the name is size, is it smaller than the second model and increased from the first smallest, what does it mean? Why is it a potential candidate for the second smallest, then if it happens then it is right away and by default it is fine from the side, fit is the third line, if it is the first smallest, it is bigger than the name, then west and delete it and this is what it is. Our side becomes the first day first molest, that is, we do the whole look and feel, I am your family, and its time complexity is visible to you only because once that channel is there, it is in where is the length. Off the Hague and Press will be compressed because we have used the question space, so the free fruits are there to use.
Increasing Triplet Subsequence
increasing-triplet-subsequence
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`. **Example 1:** **Input:** nums = \[1,2,3,4,5\] **Output:** true **Explanation:** Any triplet where i < j < k is valid. **Example 2:** **Input:** nums = \[5,4,3,2,1\] **Output:** false **Explanation:** No triplet exists. **Example 3:** **Input:** nums = \[2,1,5,0,4,6\] **Output:** true **Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6. **Constraints:** * `1 <= nums.length <= 5 * 105` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
null
Array,Greedy
Medium
300,2122,2280
783
hello everyone welcome or welcome back to coding Champs in today's video we are going to be solving the problem minimum distance between BST notes BST stands for binary search tree and before solving the problem if you are not yet subscribed to codingcharms consider subscribing for coding and interview related videos and in this problem we are given with a root node of a binary search tree and we have to return the minimum difference between the values of any two different modes in the tree okay we have to return the minimum difference between the values of any two different nodes in the tree okay let's take a look at the examples so in this example we have this giveaway this inventory and what will be the differences between the roots 1 and 2 is 1 difference between 2 and 3 is 1 difference between 4 and 2 is 1 and 4 and 6 is 2 this is two as well four and two is two and difference between 1 and 4 is 3 4 and 3 is what so the minimum we can see is one right because we don't have the same nodes in the tree and if we go down to the second example we have this tree um the minimum we can see here is one as well here we have one and here we have one since we have we don't have any same nodes the difference can't be one so the minimum difference we can see is one over here as well so we return one so how can we solve this problem before uh trying to come up with the solution let us see what is binary search tree so if we have a root node let's consider the tree we have a root node and we have a left subtree and we have a write summary the tree is said to be a binary search tree if all the nodes present in the left subtree have values less than root and all the values in the right subtree have the values greater than root and this is recursively true for each and every node in the tree then it is known as a binary search tree okay a tree in which a root node has values less than or greater than all the values present in the left subtree and less than all the value views present in the right subject okay then it is called as a binary search tree and um so by this we can derive another property the inverter rubber cell there are three rubber cells in a tree right reorder in order post order do you know the traversal which means the first we go to let and then we go to root and then we go to right the inorder traversal of um of binary search tree is sorted or just is the sorted order of all the nodes present in the tree so let us see that um so in this case first we started root node and we go to its left and here we go to its left again at one we don't have any left so we go to the root note at the we write down the root node and we go to write there is no right so we go back to 2 and we print to do and we go to its right and we are at 3 now and we go to its left don't have any left so we print three and then we go to its right we don't have any right so we go back to 2 and we go back to 4. at four the left tree is completed now that it's done so we print 4 and now we go to its right side is six and we go to its left we don't have any left we go to it the root now we print 6 and then we go to right there is no right since we go back to root and we complete our execution so this is the in order traversal of the this tree okay what is the in order Traverse at one two three four six you can observe it is in the sorted order so we can say in order traversal of a binary surgery is a sorted order okay we have derived this inference and now let's forget about the BST and all for a moment and let us see if you are given with an earring let's say a sorted array okay to make things easier we are given with a sorted array and we have to find the minimum difference between the values of the sorted array so let us take the sorted area as one two three four um 0.234 let's take something as one two um 0.234 let's take something as one two um 0.234 let's take something as one two five 10 and 15. so what will be the minimum difference between the any two values in the sorted array so what is sort of diary all the elements are present in the increasing order so the two elements will be the nearest Elements right one to one nearest then two five are nearest the difference between them will be the nearest difference possible to any other integer right one will be one's difference with two will be the smallest compared to all the other differences so to calculate the minimum difference we take the difference between two consecutive values in the array and we take the minimum of the all the differences between the two consecutive elements so in this case one two is one and two five is so 2 5 is 3 and 5 10 is 5 10 15 is 5 as well so the minimum is 1. so similarly what we are doing here we are calculating we are starting uh we are calculating between two difference between two consecutive values the current value and the previous value and we are taking the difference and we are maintaining the minimum difference so in this problem also we will do the same thing with the binary short string while performing the inorder traversal we keep track of the previous nodes value and we already know the current root value what we do is we take the difference between them we take the difference between the current root value and the previous value and we also keep track of minimum difference which keep tracks of minimum difference between the two values uh root current root value in the previous value in this way we can compute the minimum difference between the two nodes in the given b as T so let us see that let us code it up let me take the variable the result initially it has int Max and let's take previous variable and let us initialize it to minus 1. and now let us take a helper function minimum difference in bsp Helper and it takes the root value and um yes and we return the elephant okay and let us code the minimum diff minimum helper function so it doesn't return anything minimum difference in BST helper this what this basically delivers the inorder traverseth so let us code the initial traversal in order traversal what we do first left then root then write it so first the node the root value should not be null if the note value is null then we return if the node value exists then we go to its left so minimum difference in VST helper Roots yes now we have completed now we are at root what we do at root we compute the difference right if previous value is not equal to -1 so if previous value is not equal to -1 so if previous value is not equal to -1 so if the previous root we don't have to perform any difference the previous value doesn't exist so if previous is not equal to minus 1 then what we do is we take the difference right and we compare it with the result so result equal to minimum of result comma now we have to take the difference root value minus the previous value this gives the difference and we calculate the minimum result and next what will be our previous value will be equal to the current value right now we go to the left minimum difference in BST helper root stride looks good so what we are doing we are using a helper function to compute the result and in this helper function we have or we are basically doing is in order to Traverse it first we are checking if the root is not null and we are going to the left and then we are going to the root at root what we are performing we are taking the difference between the current value and the previous nodes value and Computing the taking its difference and keeping track of the minimum difference and next after completing the execution of the current route we are taking it we are considering it as the previous because we are moving on to the next node and then we are moving on to Roots right so this is the code looks good to me let us run the code and it passes all the sample test cases let us submit it passed all that is cases so what will be the time complexity of this approach that I'm complexity of this approach will be normal DFS or the inorder traversal time complexity which is OS n where n is number of nodes in the VST and the space complexity will be off n as well because um of n as well because we are using recursion the recursive call Stat will be at most of H and the height of the tree in worst case can be the number of nodes in the tree if we have linked list kind of a tree so Diamond space complexity is O of N I hope you have understood the solution and I have in the time and space complexity if you did make sure you hit that like button and subscribe to coding champs for more coding and interview preparation related videos see you all in my next video till then take care keep practicing bye
Minimum Distance Between BST Nodes
search-in-a-binary-search-tree
Given the `root` of a Binary Search Tree (BST), return _the minimum difference between the values of any two different nodes in the tree_. **Example 1:** **Input:** root = \[4,2,6,1,3\] **Output:** 1 **Example 2:** **Input:** root = \[1,0,48,null,null,12,49\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 100]`. * `0 <= Node.val <= 105` **Note:** This question is the same as 530: [https://leetcode.com/problems/minimum-absolute-difference-in-bst/](https://leetcode.com/problems/minimum-absolute-difference-in-bst/)
null
Tree,Binary Search Tree,Binary Tree
Easy
270,784
239
hello everyone today we are going to solve this sliding window maximum problem sliding the so now our audio is working correctly so what we have to do in this problem we will be given an error and inside that area we will also be given a window let's say the window of three so in this area what you have to do you have to find the maximum number between that given window so from here let's say we start then our maximum window is one three and might i mean the our window is one three and minus so what is the maximum it's three now our next window will be three minus one and three so which one is the maximum 3 is the maximum now this will be our next window this will be next and until up to here we have to find the maximum of each window and then return in the format of the area if you want to have the better understanding you can see this is our first index maximum is three output is three this is second maximum and we have output x3 and this is the third fourth and this is the last window in which we have seven as the maximum and if you see look at the constraint the area length can go up to the 10 to the power which is around 10 100 000 and also the number of the area can go up to minus 10 to the power 4 plus 10 to the power 4 and k will always be a positive number it will either be 1 or uh or instantly also less than the number of error o and m is because we are looking through the each window every time so this is going to remain the constant depending on the k so we can say n by m the time complexity so if we look at the name that broadcast what we do we take an output we look through each of the item then what we do we create windows so here we are taking let's say we are a index number on zero then we create a window of three so this will be our window then we're taking the maximum item and pushing into our area now our i will be saying here so we create next window and then we iterate through this window from again and select the maximum and same we do this for next all of the items this is giving the correct solution but the problem is it's getting time out so you can see time limit x8 i have already sold it in uh oh n type with the dq but let's do it again so in our dq approach what we are going to do we are going to use a double ended cube so we will uh enter the we will uh look through the array only once then what we are going to do we are going to put the top uh the greater element always at the front of the that queue so greater the element which is greater than the previous element is always going to be top then we are going to take it and push it to our array so let me do that quickly first we create a queue which is an empty a javascript uh don't have any inbuilt library or which we can use the queue data structure so what we are going to use the error so for removing from front we will do error dot shift uh remember from back we will do error or if we want to insert it at the back then we do edit.push then we do edit.push then we do edit.push so in our case we will remove from the front and back both of this and also push from only pick so our top element is going to be at the top most always now we don't have to check for the null or empty conditions because our array is always going to be either 1 or also our k is going to be one so first what we have to do we have to initialize q with the starting window maximum so let's say we will calculate this first maximum to initialize our q then after that we can run through our algorithm so what we have to do and one more thing is that we are not going to push our elements we are going to push only the index number of the element why we are doing this because we will have to check if the current items are only the items which is present in the our current window so any item is outside our window we don't want it in our cube we will just remove it and only the current window item is going to remain in the queue and let me check so what we are going to do our condition will be that rq should not be the empty so q dot length but uh we are going to do it for the looking through we have to look through the queue so we have to use the so there is always a should be one or one item in the queue and the current array item if it's greater than the size of the queue the first uh element of it so it will be yeah we have to paste the item from error because we are not going to push now let's say we already have one item in the queue which was uh greater than so in this case we push one in the cube now we come at the second position which is three so let me just do that so let's say this condition goes falls for the first time so what we are going to do your push so we are going to push the index so this item now is in the queue so when second our low is going to execute this condition will become true and our area item three is greater than the one so what we are going to do cube dot pop so we are removing the element which is not the greater than from the top so now this 3 is greater than what we are going to do q so this will be our greater element now once our for loop is end we will have the top element uh in this case 3 in our cube so we can so we will age the first item in this case let's say our queue has three only three so we will put three for the result because in first sliding window for first sliding for first window we have calculated so now at the end of the loop we are putting three inside now the same algorithm goes again but this time for the rest of the year first we have calculated for one window to initialize our tq to do the operation now we are going to do for the whole rest of the head so the loop is going to run the same let me return but before that i will be equal to the size and why it's going to be window size because we our i is already here and we want to start from so let's say i window size was 3 so we have already calculated for three so zero one two these three items now we are going to vary the three so window is three in this case for zero one two and three our index prompt will start prop and it will be less than the error so i should be less than otherwise deleting now we are going to check same only top element should be at the top of the queue now we have to check for another condition also and that will be it will be that our current the current in window let's say it was our previous window and 3 is over any item which is remaining in the window so now our window is this and maybe let's suppose in some cases this one will be there so 3 is greater than and it's not going to this condition is not going to delete the one if we have one inside the inputs and this is outside our current index because our current index is this and the one is outside the value so what we have to check if any of the item is outside the window then delete that so cube length should be greater than zero and q 0 item index so let's say q 0 if it's less than or equal to so we will get this item let's say if our window is this then we are going to get you will have the previous element this may be not the part of the our current window so we will do q dot shift so it will remove from the front now we pushing into the cube again are greater than a greater element or the element which is currently we have to push in the cube now what we are going to do we are going to push same so no algorithm is ready first we initialize the queue with the starting window then we run for the rest of the item and check that the top element should be always at the top i mean the greater than elements of the current window should be at the top always and then we also check if the current queue is having the element outside the bumper there should be no element outside the window in the arc if there is any element such the element on then we do shift and remove after that we post the top element in the queue and push the result into the error so let me turn it quickly okay i don't know how again there are going to be q um is there anything wrong gender i will try solving this entering this epiderm there is something seriously wrong let me reload okay and it's lucky now so let me change the quick clone is okay we are missing one semicolon here okay use example test cases now our example test cases are also working so let's submit and hope this will be submitted it's already accepted yeah you can see faster than the 44 percent because the implementation of this array we are using this array as a dq and the push pop and shift these obviously are expensive in javascript they may be taking longer than i mean more than the end times so in let's say if it's in java maybe they are having a push pop operation in one time over the constant time but in javascript it's depending on the size of the area so it may be becoming the big o and so yeah this was our algorithm which is fine and i will put this code in the snippet so you will understand better let me add comment or shall i miss the now okay and this is i had very hard time finding this solution but i find it somewhere on the internet yes i think it was on youtube but now i also do understand and i can also understand how this is working so yeah let me upload it i will create hmm let me put some description create now i'm sharing this link in the live chat not like it in the description you can copy from there go so yeah this was it and bye i will see you soon guys again in the next video till then bye you
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
105
so hello everyone ajam problem solving a construct binary tree from pre-order it in order traversal so pre-order it in order traversal so pre-order it in order traversal so i see coding videos and then i commented like do commentary along with it so please consider subscribing this channel as it really helps the channel grow a tough problem right so i will use this information to construct the binary so i will go to 15 or maybe 15 kelvin which we need to write so i will connect it here and similarly now i will go to 7 so this is the logic and now let's code it again so first of all i will make a integer in pre-index take a pre-order and now our part begins to solve the problem solve the soft problems uh just a second so you know let's solve it uh solving in solving we will pass this pre-order index pre-order index pre-order index free let's do one thing it let's make it free it's pretty long and let's make it okay pre in uh okay three and in and i will make this pre-order index pre-index this pre-order index pre-index this pre-order index pre-index and i will have two notes representing this uh black and red thing in order to reverse is okay of it so tree node star solve what vector ampersand free vector ampersand no matter what i will always i'm always increasing by this at every point that's why so now let's continue so subsequently if l is greater than r okay foreign three index foreign and i will pass the range in which i am searching function get index comma vector in ampersand three sorry in comma int uh let's name it x and into plus or if at any point if in i is equal to x is then i will simply return what foreign index comma pre index comma index y is not printing okay index plus 1 comma r so best problem oh i guess all kushnikov let's run this code to check if everything is fine sorry return let's hope if it works no i want it and submit it so i hope it will be clear and if you like this video like this quick short explanations so please subscribe this channel thanks for watching and have a nice day
Construct Binary Tree from Preorder and Inorder Traversal
construct-binary-tree-from-preorder-and-inorder-traversal
Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_. **Example 1:** **Input:** preorder = \[3,9,20,15,7\], inorder = \[9,3,15,20,7\] **Output:** \[3,9,20,null,null,15,7\] **Example 2:** **Input:** preorder = \[-1\], inorder = \[-1\] **Output:** \[-1\] **Constraints:** * `1 <= preorder.length <= 3000` * `inorder.length == preorder.length` * `-3000 <= preorder[i], inorder[i] <= 3000` * `preorder` and `inorder` consist of **unique** values. * Each value of `inorder` also appears in `preorder`. * `preorder` is **guaranteed** to be the preorder traversal of the tree. * `inorder` is **guaranteed** to be the inorder traversal of the tree.
null
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
Medium
106
743
hello welcome back today I will solve Reco 743 Network delay time we given a network of end notes labels one to n and we are given also the time it takes for a signal to travel from one note to another we will also given the source node and the question is what's the minimum time it will take for signal to travel from the source node to all the nodes on the network let's take a look at one of the examples here we have a network of four notes and we are given the set of edges take this Edge for example 211 means that this is nedge from the node two to the node one and it takes one unit of time for the signal to travel from no two to no one in this Example The Source node is to no two and the minimum time for the signal to travel from node two to all the nodes on the network is two because is 2 to 1 is one units and then 2 to three and 3 to four it takes two units of time that is the minimum time it would take for all the notes to receive the signal from two in this example all the edge weats are of one unit so the most straightforward approach would be to use bref first search to find the minimum time for the signal to reach all the nodes from The Source node however the edge weight may have a different value in this case as long as all the edge weights are positive we can deploy di algorithm and that's what we're doing today so let's set it up we need several data structures first of all we need to build up the jcy list for the graph the jcy list the key would be the notes and the value will be a list of Two Poles comprise the note and the distance it will take from the key Noe to that neighbors node we have three edges in our example for two it can reach one and it can reach three for both neighbor nodes it will take one unit of time for no three it can only go to four and it will also take one unit of time another sta structure we will need is a mean Heap this will store a list of two pools which comprise the note and also the distance value here is this time will take for signal to travel from the source note to that not and finally we would have an array or hash map where we going to store the minimum distance from all the nodes on the graph to the source node in this case the source node is two I set the base value for all the nodes to be minus one so if it's the value is minus one then we have not established the minimum distance from that note to the source node I going to deploy D algorithm to solve this problem and here's the templates this is derived from the template I discussed in part one of this series on D algorithm if you have not watched that video and if D algorithm is new to you I would strongly recommend that you pause the video and watch part one of the series before continue with this one first step we push thisal with a distance of zero onto the Heap s here's two so two Z goes onto the Heap now we are inside the wall Loop we take the first item off the top of the Hep that's two Z and then we check whether two has been updated in the minimum distance table it has not so we will update two here at having a distance of zero and then we can to get all the neighbors of two and in this case will be one and three and we put these two PS onto the Heap recall the two P that we going to put under the heat comprise of the node and also the distance from that node to the source no now since one and three are directly connected to two the Atway is the distance that we want to put in those two poles so the two po distance for both of those nodes are one and one now we at the top of the W loop again we take the top item off the Hep and in this case it's one so one we do an update in the minimum distance table for One S one does not have any neighbor so again we at the top of the W Loop we take the first item and this is free for the note three we do an update on the minimum distance table as having a distance of one here the note three does have a neighbor and that is four we make a two pole with no four and put that on the Heap the this distance between three to four is one but again we are looking for the cumulated distance between four to the source node so we add up the one here and also the minimum distance from The Source node to three is one so 1 + 1 is two so we put three is one so 1 + 1 is two so we put three is one so 1 + 1 is two so we put the 2.4 two onto the Heap again we at the 2.4 two onto the Heap again we at the 2.4 two onto the Heap again we at the top of the W Loop we take the first item and that is 42 we update the minimum distance table for four S the no four has no neighbors so there's nothing to put on the Heap now the Heap is empty and we are done with the Vol Loop to establish the minimum time will take for signal to travel from the source node to all the nodes all we have to take is the maximum value on the minimum distance table now that we talk about the sual code let's talk about real code here is the C implementation you can find this code in the ghub links below and you can convert that to any language of your choice this is C- code so we have a choice this is C- code so we have a choice this is C- code so we have a dictionary where we're going to store the adjacency list and we have the priority cue which is the minan Heap the minimum distance table will be in the form of a integer array because the notes are one to n so that's why the array size is n + one and we're going to array size is n + one and we're going to array size is n + one and we're going to set the base value for this array to be minus1 so any noes that has a value of minus one the minimum distance has not been set and we set the minimum distance of zero to be zero Zer is never used anyway because the notes are one to n now in this part of the code we just build up the adeny list we take all the edges which is in the form of times array and we just add it to the adeny list next we put the Heap the s portional in which case is the K value and then a distance of zero and the priority will be determined by the edgeway so this is the value that will determine the priority on the Heap now we go through the W Loop this is very similar to what's in the pseud code and at the end we check the minimum distance table now if the minimum value is minus one that means there is a node that cannot be reached from The Source node and in which case we will turn minus one otherwise we just take the maximum value from the minimum distance table that is the critical path and that is the minimum time it will take for the signals to reach all the nodes now let's take a look if this works and you looks good next time I will do another example using D algorithm hope to see you then
Network Delay Time
closest-leaf-in-a-binary-tree
You are given a network of `n` nodes, labeled from `1` to `n`. You are also given `times`, a list of travel times as directed edges `times[i] = (ui, vi, wi)`, where `ui` is the source node, `vi` is the target node, and `wi` is the time it takes for a signal to travel from source to target. We will send a signal from a given node `k`. Return _the **minimum** time it takes for all the_ `n` _nodes to receive the signal_. If it is impossible for all the `n` nodes to receive the signal, return `-1`. **Example 1:** **Input:** times = \[\[2,1,1\],\[2,3,1\],\[3,4,1\]\], n = 4, k = 2 **Output:** 2 **Example 2:** **Input:** times = \[\[1,2,1\]\], n = 2, k = 1 **Output:** 1 **Example 3:** **Input:** times = \[\[1,2,1\]\], n = 2, k = 2 **Output:** -1 **Constraints:** * `1 <= k <= n <= 100` * `1 <= times.length <= 6000` * `times[i].length == 3` * `1 <= ui, vi <= n` * `ui != vi` * `0 <= wi <= 100` * All the pairs `(ui, vi)` are **unique**. (i.e., no multiple edges.)
Convert the tree to a general graph, and do a breadth-first search. Alternatively, find the closest leaf for every node on the path from root to target.
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
495
welcome to september's leco challenge today's problem is teemo attacking in lol world league of legends there is a hero called teemo and his attacking can make his enemy ash be in poison condition now given teemo's attacking ascending time series so that's going to be a sorted list of integers towards ash and the poisoning time duration so that's the amount of time that the opponent will be poisoned we need to output the total time that ash is in poison condition you may assume that timo attacks at the very beginning of a specific time point and makes ash in poison condition immediately now a couple notes we can assume the length given won't exceed 10 000 and the numbers are going to be non-negative and won't are going to be non-negative and won't are going to be non-negative and won't exceed 10 million okay great so let's think about this for a second like if we had a time series we know that this is going to be sorted um how do we know how much time this person is going to be poisoned for so let's say the time duration was i don't know 2 and we had numbers like 1 let's say 20 30 40. like all we would need to do is like count up these numbers of time units right we'd say hey it's poison two time and that's gonna be a total of eight so that's really easy the issue becomes when these times overlap like now it gets a little bit trickier because we know that this guy's going to be poisoned at first we think two seconds but he gets poisoned again at point two so there's an overlap it like restarts that poison condition so if this was the case how would we figure out how much time he's poisoned for like let's say we had some units like this like here we would think okay it's gonna be poisoned for two units right or is it because the very next unit you can see that where he's gonna be poisoned again so actually at this point he'll only be poisoned for one time unit same with here it's only gonna be one time unit because the next one's gonna be three same with here one time unit it's only here that we see yes he will be poisoned for twofold for two time units same here and same here so what can we do to like kind of calculate that so we obviously know we have to look at the next unit in time right so like here we could kind of say well which one's the minimum amount of time going to be poisoned for will it be two or will it be the next time unit two minus one so two minus one or two and we know that it's gonna be the minimum between these two because either he's gonna be restarted he's gonna get poisoned again or he'll get poisoned for the full time unit so we just need to get the minimum here just get the minimum amount between these two and ah add those up as we go along so here it's gonna be either two or one we know that's one two or one it'll be two or two doesn't matter two it'll be uh four or two but one thing here at the last unit we can't look at the next time because this is the last one so that's a problem but just intuitively we know the last time unit he will be um no matter what poison for the duration of time right because there's no uh restart of that time unit at the last one we know oh yeah he's going to be poisoned for duration no matter what okay so that's going to be our approach let's say we have first we'll say if time series or i should say if not time series if it's an empty list let's just return zero because there's no duration so what we're going to do is say if before i in range of the length of time series but subtract one because we don't want to do it for the last one because there's no uh no next time unit so for that last one we'll just add it at the very end so what we're going to do here we'll have let's say a total start with zero and we're going to say we'll call this poisoned get the minimum between duration and time series if i can just spell here i plus 1 subtracted by times series i so whatever is the minimum here this is going to be the amount of poison he'll be poisoned for this time unit so all we need to do then is just add this to our total and really we can actually just get rid of this and put it here save a little space now we do it for all the time units except for the last one and at the very last one just add the duration and really i guess we don't need to do that we can just return total time duration here so let's just see if this works um let's say i like one two three four this should be what one two three four five it does get five it looks like that's working and submit it and accept it great so that's it this is a o of n time complexity uh does it use extra space no not really so it's constant space so there we go hope that helps thanks for watching my channel and remember do not trust me i know nothing
Teemo Attacking
teemo-attacking
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`. If Teemo attacks again **before** the poison effect ends, the timer for it is **reset**, and the poison effect will end `duration` seconds after the new attack. You are given a **non-decreasing** integer array `timeSeries`, where `timeSeries[i]` denotes that Teemo attacks Ashe at second `timeSeries[i]`, and an integer `duration`. Return _the **total** number of seconds that Ashe is poisoned_. **Example 1:** **Input:** timeSeries = \[1,4\], duration = 2 **Output:** 4 **Explanation:** Teemo's attacks on Ashe go as follows: - At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. - At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5. Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total. **Example 2:** **Input:** timeSeries = \[1,2\], duration = 2 **Output:** 3 **Explanation:** Teemo's attacks on Ashe go as follows: - At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. - At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3. Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total. **Constraints:** * `1 <= timeSeries.length <= 104` * `0 <= timeSeries[i], duration <= 107` * `timeSeries` is sorted in **non-decreasing** order.
null
Array,Simulation
Easy
56,605,649
72
hello everyone let's solve today's problem edit distance at the distance is also known as living time distance it is a measure of the similarity between two strings of characters it is defined as minimum number of insertions deletions or replacement required to transform one string into the another in this problem word 1 to word two we call it distance because it represents the difference or distance between two strings in other words it quantifies how far apart the three strings are in terms of their content in this example one we can replace h with r remove r and remove e then horse transformed to laws we cancel this problem with Batmobile dynamic programming we can make two dimensional array the rows means the source words characters and the color means the target words characters and we initialize its first row incrementally from zero it means we have no string as a source word and we want to make it a nurse string e and e x and EXE and so on so it means insertion operation and its cost and we initialize its first column incrementally from zero it means we transform order string to nurse string I to nurse string or i n to another string or int to nor string and its cost so it means deleting operation and its cost and finally if we want to replace from One Source character to Target character it takes an additional one cost from diagonal Direction this way if we have same characters in The Source and Target words then we don't need additional cost let's look at this example we select the minimum cost among insertion deletion and replacement two one so we can select this one and insertion deletion and replacement so we can select this or this one in this case we have the same characters so replace cost is zero so we can select six but here we have different characters so replacement cost is one so we select the minimum value 7. let's do it step by step at last we can get at distance 5 from intention to execution okay we made it let's cut it we made two dimensor array the rows are for words one and the columns are word two we initialize the first row and First Column as we assume the nurse string with iterating every row and every column we check if we have the same characters between word one I minus 1 and word two J minus one if we have the same then the additional replacement is zero we select minimum value among replacement cost insertion cost and deletion cost the last cell is the minimum edit distance this time complexity is Big O of M by n if the word one ranks is M and word two ranks is n we iterated every cells into dimensional array and the space complexity is also because of M by n because we have the two dimensional array I hope you enjoyed this video and it was helpful and I'll see you soon bye thank you
Edit Distance
edit-distance
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_. You have the following three operations permitted on a word: * Insert a character * Delete a character * Replace a character **Example 1:** **Input:** word1 = "horse ", word2 = "ros " **Output:** 3 **Explanation:** horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') **Example 2:** **Input:** word1 = "intention ", word2 = "execution " **Output:** 5 **Explanation:** intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') **Constraints:** * `0 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of lowercase English letters.
null
String,Dynamic Programming
Hard
161,583,712,1105,2311
3
hello everyone welcome to code and learn in this video we are going to look at lead code problem three finding the log as substring without repeating characters in a given string let's go over the problem statement first given a string as find the length of longest substring without repeating correctors so we will be given a string which has repeating correctors and we need to find the longest substring which has non-re the longest substring which has non-re the longest substring which has non-re repeating characters the first example we have is a b CA b c BB so you can c a b c all are repeating characters in this and we need to find the longest substring with non-re repeating substring with non-re repeating substring with non-re repeating characters which is AB BC in this case in the next example we have bbbbb in this case the longest substring with non-re repeating characters is the with non-re repeating characters is the with non-re repeating characters is the character B itself or a substring with only character B and length of one similarly in the third example we have pww k e w in this case the longest substring without repeating character is WK the constraints of the problem said the string consists of English letter digit symbols and spaces now let's visualize the solution first before going into the code so we are going to take the example of ABC D so to find the solution to this problem we are going to use a sliding window we will have two pointers start and end start is the start of the window while e represents the end of the window along with the start and end we will have two variables to store the max length of non-repeating substring and then a map non-repeating substring and then a map non-repeating substring and then a map to store what characters we have already seen this will make sure that the corrector we are currently on is the one that we haven't seen before we will calculate the length with the formula n minus s + 1 that will give you the minus s + 1 that will give you the minus s + 1 that will give you the length of the current window in this case since both are zero the max length will be one as such we will update the max to one along with that we will also store the corrector that we have seen with the index so we have seen a at zero then we move the end of the sliding window to the next character that is B in our case the first thing we do is use the map to check if we have seen b already in this case there's no B in our map so we can calculate the new length of the window will be two which is greater than Max so we will update it next we will repeat the same step again that is move e to the next before doing that we need to add B to our map to keep a track of the last scene index in this case b is at index one at C the first thing we do is check if we have seen C already since it does not exist in the map we can calculate the new length of the substring which is three in our case as such greater than Max that we currently hold so we will update the max value and say the current Max is three now we create an entry for C in our map and say that we have seen C at index 2 next we move we to the next corrector the first thing we do is to check if a exists in our map which it does so in case where a character already exists in our map we will move s to the next index that is Index right of a so s is now here again we calculate the length of the substring which is in this case is three since it is same as the max length we don't update it but in this case we will update the index of the character a since it already exists in our map a now holds four now let's move the end of our window to B again do the same thing and check if P already exists in our map since P already exists we will repeat the same thing that is moving s to index of b + 1 which is here now perform the of b + 1 which is here now perform the of b + 1 which is here now perform the calculation for the window or the current length of the window which is three same as the max length so we don't update but we do update the index of p in our map that we have so we say the last P we have seen is at index 5 next we move the end of the window to C then we check again if C already exists in our map which is this so what we will do is move S2 c+1 which is at a update the is move S2 c+1 which is at a update the is move S2 c+1 which is at a update the index of corre C in our map to six and then calculate the length of the current window which is three again as such we don't update the max length Now we move our end of the window to D we check if D already exists in our map which it doesn't so we update the value of D to say that D exists at index 7 calculate the length of the window which in this case is four so since it's greater than the max we will update Max since end of the window has reached the end of the string we can say the max length of non-re repeating substring is length of non-re repeating substring is length of non-re repeating substring is four which in this case is a b c and d so that's how the sliding window approach will be used to solve this problem since we only iterate over the string once the time complexity of this solution is o n where n is equal to the number of characters in The String additionally we also have a space complexity since we are using a map to store the indices of character that we encounter so the space complexity of this solution will be o of n as well because in the worst case we will have to store all the characters in The String now let us go to our code to understand how we solve it with our go program first I'm going to create a function called length of the longest substring which takes a string and return the integer which is the length of the longest substring without repeating characters and inside it let's create a map to keep tabs of the character and their indexes I can say J map create a map off Rune and in values if you remember we are using run because it represent a uni code Point next let us initiate the start of the window and the max length variable used to store the length of the longest non-re store the length of the longest non-re store the length of the longest non-re repeating substring so start of the window and the max Len is zero next let us write our Loop for our sliding window so here end is the index of the current character and corrector is the current character in the string that we are on first thing we do is we will check if the current character exists in our map so here we are saying if the current character is found in the map and the current character is on the right side of the star of the window we will update the star to index + one next let us the star to index + one next let us the star to index + one next let us check if the length of the window is greater than the max length if that is the case we will update the max length so we can say current length of the window is end minus to + one if current window is end minus to + one if current window is end minus to + one if current length is greater than the max length we will update the max length then we will also update the last scene index of the current character which is 10 at the end of the loop we return the max length so this is the solution for this problem using sliding window let's go over the solution again first we created a charm map stores the last index of where the character was last seen next we created start and max length start is the start of the window and max length is the length of the longest non-re is the length of the longest non-re is the length of the longest non-re repeating substrings we have seen till now then we start a for Loop to iterate over the string we check if the corrector is already in the J map if found and the index is greater than or equal to the start it means the character repeats within the current window so we update the start to the next index after the previous occurence of the corrector next we calculate the current length of the window and if it's greater than the current max length we update the current max length at the end of each iteration we update the CH map with the index of the current character after the execution of loop max length will be the length of the longest non repeating substring that's it for the solution I hope you enjoyed it please feel free to ask any questions you may have by posting a comment under the video or reaching out to our Discord server until next time happy coding
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
232
all right so this question is called implement Q using Stax it says implement the following operations of with Q using stacks push which pushes an element in the back of a Q pop which removes the element from in front of the Q peak which gets the front element and empty which returns whether the queue is empty so it gives it a little example over here it instantiates a new queue it pushes two elements and then uses peak so this returns the element one because that's the one at the bottom of the queue that pops the one at the bottom of the queue and returns the number one and then it returns whether or not it's empty which it's not because there's still one element left notes you must use only standard operations of a stack which means only push the top peak pop from top size and his empty operations are valid then it says depending on your language that may not be supported natively which is actually not in JavaScript you may simulate a stack by using a list or DQ as long as you use only standard operations of a stack and that's what we're gonna do you may assume that all operations are valid for example no pop or peak operations will be called on an empty queue all right so let's go over to the code that the code has provided so this is the class called my queue they want us to implement a push method which just adds an element to the top of a queue they also want a pop method which removes an element from the bottom of the queue then we need to implement peek which shows us what elements at the bottom of the queue but doesn't actually remove it then we have an empty method which just checks whether there are any elements in the queue and like I said before JavaScript doesn't have a stack class so I implemented one on my own I won't go into the details of this too much but just know that all of the code and the written explanation is linked down below so with the stack when you push you add an element to the top of it when you pop it you remove the element from the top peak shows you which element would be removed which is the element at the top empty shows whether or not it has any elements in it and then size shows you how many elements are in it so let's quickly go over the difference between a stack and a queue a stack is commonly referred to as LIFO which stands for last in first out this means that the last element that was added is the first one that's going to be removed so let's picture a stack of dishes even though the element at the bottom was at it first the first element that we're going to be that we're going to remove is the one at the top so let's remove that one followed by the next most recent and then the next most recent let's go over to a queue is just the opposite it's first-in first-out the opposite it's first-in first-out the opposite it's first-in first-out so whichever element was added first is going to be the first one removed so let's picture a line at a grocery store this person entered the line first and then this person the first person to enter the line will be removed first then the next person and then the person after that and just to demonstrate that one more way let's go to the LIFO stack this is first second third which one's going to be removed first the last one added the one before that over to the queue this is added first this is added second this is added third which one's going to be removed first the oldest one added then the one after that and then the one after that all right so how do we make a stack behave like a queue remember that what the stack the last element added is the first one that's going to be removed so with the stack let's say we add one and then two and then three with the stack the first element that would be removed is the number three but that's not what we need this to behave like a queue where the first element removed is the oldest one which is the number one so how are we going to go about doing that what we can do is we can actually use two different stacks so this is stack one and this is step two and what you're going to do is anytime you want to remove an element you first check whether stack two is empty which it is so then you look at stack one and you remove all of the elements that are in it and put them into stack two then you're able to remove whatever elements at the top because now what we've done is we've effectively flipped the original stack into the second stack all right so you want to remove one you can remove this which is the oldest element added what's the next element that was added after that it was the number two so if you want to remove that as easy as looking at the second stack so we want to add another element where do we add it we always add elements into the first stack and remove them from the second stack so you want to add the number four put it in stack one you want to add another element let's say five put in stack one now you want to remove an element you look at stack two and if it's not empty you remove whatever is at the top of it that's who we want to remove another one I remember we always look at stack two and see if it's empty it is so then we have to go over to stack one and pop every element in it into stack two so now when you want to remove an element you look at the top of stack two and remove that all right so let's code this out as we talked about before the way to do this is to use two different stacks will call the stack that we're going to add things to the push stack and we'll call the stack that will remove things from the pop stack so this dot push stack equals a new stack and then this dot pops that equals a new stack let's move down to the push method like we talked about when we use push we're just gonna add everything to the push step so this dot pushback dot push and what are we pushing the variable X so pop was a little more complicated remember what we're gonna do is we're gonna look at the pop stack if it's empty remove all of the elements in the push stack into the pop stack and then we remove the top element so let's do that so if pop start this the pop stack is empty so if there's nothing to be popped from the pop stack we need to remove all of the elements in the push stack and add it to the pop stack so while this thought push stack isn't empty this pop stack dot push this that push that dot pop I'll explain that again so this is saying while the pop stack isn't empty sorry well the pop stack is empty so there's nothing in the pop stack we take everything from the push stack and we put it into the pop stack and we do that over and over until the push stack is empty and then what do we need to return this duck pops that dot pop so the first thing at the top of the pop stack all right moving down to peak is actually pretty close to pop use the same logic first it checks to see whether the pop stand is empty and if it is it takes every element in the push stack and then adds it to the Pops that hold on let me just reformat this the only difference is at the very end it doesn't pop so it doesn't remove what's in the pop stack it just shows you what's in there so this dot pop stack peak and then for empty we need to check both of our stacks to see if they're empty and it can only be empty if both of them are empty so return this dot top stack empty and this dot push stack empty all that means is that if one of them have has any elements in it then the total queue is not empty so let's run this code it looks good Submit and it worked so this was faster than about 41% of JavaScript was faster than about 41% of JavaScript was faster than about 41% of JavaScript submissions so as usual all of the code and explanations are linked down below see you next time
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
509
um hello so today we are going to do this problem called Fibonacci numbers um so basically what the problem says is that um it's a standard a Fibonacci problem um it's usually um given as um as a problem either for a collision or a dynamic programming but here basically it's Fibonacci Sequence and we have F of zero is equal to zero f of one equal to one and this is the formula for Fibonacci right and you can and then we want to calculate the volume of events so please share forward we have some examples here um but I think we can just get started so the simplest solution is just to do a recursion right to do a recursive solution so that would be I'll just have something like uh recursive here and right let's call it maybe a right and then we know that if it's zero or one uh we need to return the exact value of the parameter right so it's zero if it's one we need to return one okay so what that would mean is that here we need to check so that would mean here is if a is either zero or one so then we need to return the value otherwise we need to just return um this formula here so let's just copy it over um and just replace with the our function name okay and return and then here we can just call our function let's call it a cursor okay on and right um this should work however for longer numbers for uh bigger numbers basically we'll be doing a lot of competitive work um so for example we'll do three for n minus 1 and then we'll call it again for n minus two and so we can just cache the result here you can do it with a hash or in Python you can just do a audio cache here if you want to do the cash route then that will be just having an array maybe call it memorization here um of a so one thing I forgot here this should be a right so you do memo of a is equal to this and then at the end you will return the minimum of a right and then here you'll check if let's actually do that before another U cache if a is in the cache then we just return it okay otherwise we calculate um and let's try this um yeah we need to Define our hash map first so that would be like this okay let's use more examples here okay or submit foreign now yeah as I said in Python you can do it simpler you don't need to do this repetitive work each time that you want to use a cache so instead you can just do a return right away here remove the memo and then just allow your cache um so like this okay let's run this and submit from this buses as well um so this is using a recursive solution with the cache we can also use of course dynamic programming and just pre-compute dynamic programming and just pre-compute dynamic programming and just pre-compute all numbers before n and then at the end compute n and do each calculation just once so it would be pretty similar to this what we need to do is we no longer need this right we need a DP array so we'll just fill it out initially with zero but since we want to return here for n we'll do DP of n so that's why I did here n plus 1 so that n is of DP of n is valid um now for a equal to 0 or a equal to 1 we need the value to be a right so for a equal to zero we already have zero so that one already works but for DP of one we just need to assign it to one so and that takes care of that now for this condition we want to do it for all numbers from 2 to n right we want to fill this here that's what we are doing with the recursion so to do that we'll just do for I in the range of starting from 2 because we already did one up until n plus 1 because we want to fill the value for n and then here we just say DP of I and then just replace this so this needs to be DP and this is now I minus 1. um and so just the same formula and this is DP of I minus 2 okay and then here um at the end here we'll just written DP of n now one thing we need to be careful of is this starts from two right so we need to handle the case where n is uh equal to zero right and so to do that we just say return n if um n is small or equal to one we want to return n so if zero will return zero if it's one with a two one okay uh and now we can just run this and submit and this passes test cases um yeah so that's the main idea here um now one thing you'll notice with this um with this Dynamic program solution is actually we only are using the two latest the two previous values for in the array to compute the next one right so here we are using opens time and open space right we have to resolvement time but can we not use the oven space can we reduce this one here well we can see here we are using just the two previous values so why not just remove that so uh let's call this here current so DP of I is just the previous value so the previous current and so let's call this current and let's call the value at 0 previous so previous is going to be zero and now we no longer need this now this is the new current value and so the nutrient value needs to be the previous current value whatever we assigned in the previous for Loop iteration Plus pref and what should be pressed pref should be um the previous current value right so this one here okay but the problem is if we overwrite it then this Print won't be the previous value that we want and so to do that we will just use python's um foreign variable right to put current and then you can assign this here to jump um yeah so yeah um and this pretty much should be it except here um what we want to return is current because that's the latest updated value here at the end of the iteration essentially so if we run this it should pass okay let's submit okay so that buses as well um yeah so this one uses just oven space so it's uh it's a lot it's more efficient here um yeah so that's pretty much it for this problem thanks for watching please like And subscribe and see you on the next one bye
Fibonacci Number
inorder-successor-in-bst-ii
The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given `n`, calculate `F(n)`. **Example 1:** **Input:** n = 2 **Output:** 1 **Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1. **Example 2:** **Input:** n = 3 **Output:** 2 **Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2. **Example 3:** **Input:** n = 4 **Output:** 3 **Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3. **Constraints:** * `0 <= n <= 30`
null
Tree,Binary Search Tree,Binary Tree
Medium
285
885
Hello everyone welcome back to me channel once again so here people are going to talk finally lead code in the big of spiral matrix 3 and this problem was striking this problem basically the sequence of this is spiral matrix one two three four and its full one And all the three videos which I have already uploaded on the channel are fine, Abhijeet, please watch them. By the way, the link of the fourth one is also available on the A button above, so if you have not seen it, then watch it from there, the rest will be available on the channel in such videos. You will get it in the next card, okay a little bit, first of all I want to tell you about it in the main, if you look mostly in education 12 and 4, then there is a kind of sim liability, okay but this three question is for me because it takes time, so that's the story. No, the story is a little different, okay, this question is a little different from the other three questions, something different has been asked in it, I had started the block with everyone, Steel City, here I have made a post, then you will go to the block page and second. Air was inserted a day ago so you can see here basically I have written a complete blog of hospital matrix spiral pattern in matrix, you will see all the four questions here by sunrise, what will be a common code for this, a common algorithm will be that, I have seen the recovery. A dummy code has also been provided to you, okay, so you will get all these things here, video link, Christian link and one more thing which is basically you will get the question of CSC here, edit right, so you will get the link of this post below. You will find it in the description box, if you look there, let's talk about the question. The question is that here you always have the same matrix, the difference here is that you will be given a cell of this matrix, okay. There is a cell in it, Start and the column Start, so if you read all the other questions, you will get this error here that nothing is given directly there in the beginning of the starting cell or in the beginning of the index of those people. We will just give you a matrix and you have to make spiral travels in it. Right, either you have to travel or you have to make a matrix from the given travel, then the question will be something like this. Here he said, it is okay to do spiral, Sparrow, we are doing this in this way. You used to travel from here, in the matrix this thing has been separated, so what did you say that it is not like this, you will travel in your own style, but this time, the way will be and where will be the starting, always used to start from here, don't do this, you have to be a particular person. It is giving in the cell, okay, start from there, okay, now here it is said that no, start from here, then from here it has a spiral method which will be something like this, first go ahead and then do these two like it used to happen in this, okay so there is one step. The spiral will move in this manner, right, it will be moving like this spiral is just that, on the contrary, we used to start here because we were not given anything, so starting from the last cell, we used to get smaller, it is not in this, we start here From here we will do almost, then after that it will almost change to the square of two, then three, then do these five in this manner, it will keep on crying like this, it will keep on increasing, are you understanding, one, three, four, five, six will become bigger in this manner. So I have given you this cell, now see where the problem will come, if you are traveling in this way, it is okay to do it in this way, I am traveling from here, then from here like this, basically if you see, this is It happens like this, sorry, from here it comes down and from here it moves like this, above, okay, then from here if you see, it comes like this, then it moves like this, then I am telling you that you have to follow this pattern only. It is okay, it is not that if we are going outside the grate, then you change the entire route. No, this is the one outside the grate which I have dotted it with dot, meaning do not go there, but after this, the one who imitates. A cell should have come nearby, you have to go back to this cell from here and then this thing will be continuous and in this way your continuous will work as if you look in first kaise or second kaise then here 123456789 now after nine dot this. Jain, if we draw this and forget the matrix for a little fear, then if this line of yours would have come down in this manner, then what would have been said in it that the butt which is outside the matrix, you will have the number to follow it, then your number will be 10 after 9. Whatever visit will happen, which is okay, so in this way, you will be visited in rounds like this, the only problem you will have in this is that when you are going out of matriculation, how will you handle it, okay, I am assuming that you have. If you have already seen the video of one or two questions, then I will not be able to clear some basic things here, that is, I have to leave that basic step, I will script how it will be different, then see here if you understand what we were doing earlier. Great, everyone was going back like this, we made a square, made a triangle and explained to him that by holding the diagonal opposite which is your index, we can make a matrix. Right but understand here is the spiral text, it is like the previous spiral. But it is a little different here, this is how your starting is going properly, if RC is here, okay RC is there, then this is your one, this one is ahead, right, after that, DR from here, okay, then you have to add the direction on the left as well. So it will be good plus one will be in this so here this thing will be there that you ok plus one will go right ahead friend plus one will be there and this is R plus one mines you and C mines you basically I understand what are the six here tell me these six I'm just waiting for one second yes white whatever will happen here then after that it will be 22 then it will come from here so you will go then like this it will change to three again and in this way it will change to you every time okay so what am I saying For this purpose here, I have kept a variable named length. Length basically tells the length of the suspensor. Right, I have also gone through the code along with it so that it becomes easy to understand. You can leave this valid one for now for a little fear. Yes, we will come to this, okay for now let me tell you what I have made here, basically what I am telling you is that you are going to GG index, if I know which cell I am going to, then whatever the value, I can I will do it only from China at the place and it will go to A. Okay, so the size is taken out here. How many elements are there in the total matrix, then the days in these columns will be the length, only I will be your one and my starting and ending, sorry, starting of the cell, its X coordinator R and A. Coordinator C, I have kept the question given on the front, we have not started yet, we have not started checking anything in the bigger matrix, even the information we had and what I needed, we have declared buckets and only variables etc. and assigning values. Done, now we come to the next line which is the wiring. Now what will happen in the next line is that s1 edge, we will encounter all the elements in our matrix or all the indices in our factor. We will leave it there because then our retirement will be complete. It will be done okay, so now what is ours in the middle, first of all, what was our lesson, go to the right, so if we move to the right, then this one will exactly match your code. The previous one, which we might have seen the video or seen the solution in, is okay. So on the right there was the text of life, so what we had there is X A, so we would move it according to 2 points, here yours will move in this way, this is the length of the spiral, later it will move on 2, okay. So for this thing, I have kept a lens which is variable, so the length time will go forward to the right, then we moved right till the length time, we are fine, it was running in the loop, so the coordinator, we have what is the ID but RC which is this is X A which is this. That's it, this is So this whole right part right moment is done, okay, similarly, if you want to move Dr, then in this, A in, if one will increase, okay, if before this you had increased by, in the right, when you are going, now you are going Dr. You will get increment in He was saying, you and sorry left and yours, we will do that also, after that again there will be length plus, so I will not explain it again, this thing is completely different from the above spring, this is the same that last time we were moving right. If we were moving then our Okay, here yours will not be good, here we understand according to the indexing of the matrix, this is your zero, we will increase down and if we go here, the pen number will increase, then how will it happen, what will happen in this, there will be an increase in this. And if we reverse this, from this particular point, if we are going up, then Okay, so after two, again the increment of length and what is this, now what we said is that we started from here in the length of one, went to two, then came to the length of three, so here it is, it came like this and in this manner. We kept moving forward, now you will say that your matrix can be a matrix, it is possible that brother, it is such that our matrix must be like in this range, you, all the further ones which are your index, all the further possible ones which are in valid cells. After checking them, it is okay to avoid this thing. To remove this thing, I have used the function of this valid, which is this, okay, this is valid here and told that if it is given the index of this cell. If he is going outside the grate then if you burn him in return then this answer of ours will not be made in it, he will just skip there, okay, we checked dot as we moved but it is not in our counting, so okay. This thing kept happening and finally our entire grid will be added in this way because one or two people were asking me about the big doubt related to it, so it got confirmed, it must have been cleared for you, okay, you can give your feedback in the comment area. If you have any suggestion then give it and I hope that there will be no one child. If you want, you can tell me the discount. Okay, we can discuss this thing on the story too and I will tell you once again that this blog is Spiral. Pattern Matrix, I have already given its link in the description box below. Ok, read it from there and understand. Do you have any suggestion related to this? This is a question for improvement. I think this is wrong. I have added it, I will change this name. It is not visible, if you have any suggestion then you can join me on the link of discount server and let me know, we will change it, ok see you.
Spiral Matrix III
exam-room
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all `rows * cols` spaces of the grid. Return _an array of coordinates representing the positions of the grid in the order you visited them_. **Example 1:** **Input:** rows = 1, cols = 4, rStart = 0, cStart = 0 **Output:** \[\[0,0\],\[0,1\],\[0,2\],\[0,3\]\] **Example 2:** **Input:** rows = 5, cols = 6, rStart = 1, cStart = 4 **Output:** \[\[1,4\],\[1,5\],\[2,5\],\[2,4\],\[2,3\],\[1,3\],\[0,3\],\[0,4\],\[0,5\],\[3,5\],\[3,4\],\[3,3\],\[3,2\],\[2,2\],\[1,2\],\[0,2\],\[4,5\],\[4,4\],\[4,3\],\[4,2\],\[4,1\],\[3,1\],\[2,1\],\[1,1\],\[0,1\],\[4,0\],\[3,0\],\[2,0\],\[1,0\],\[0,0\]\] **Constraints:** * `1 <= rows, cols <= 100` * `0 <= rStart < rows` * `0 <= cStart < cols`
null
Design,Ordered Set
Medium
879
54
lead code 54 spiral Matrix in JavaScript this is a messy problem it's got four pointers and four functions that update those pointers each function that updates the pointer also has to keep track of where it is along the position for that pointer and it's messy and I'll get into it um I have a demo that goes along with it and that'll be on my website as well so the Matrix give it an M by n Matrix return all the elements in spiral order our Matrix is a 2d array that's row 0 Row one row two we have to return the spiral order as a single dimensional array so we go across the first row and then we're going to go down the remainder of the last call to the last row we're going to decrement our call pointer last call pointer at that point and then we're going to Traverse the row in reverse decrement the row pointer as we before we do that and that's going to be eight and seven then we're going to Traverse the column in reverse and then we're going to increment the first call pointer and then we're going to start all over again with our row Traverse the row and Order and increment our first row pointer at which point the first row pointer will be pointing to 2 and our last row pointer will be pointing to 2 and there will be no more pointers there will be no more rows or columns to iterate over because we know that because the pointers overlap the demo showcases that now the demo I have here right now shows extra an extra row it's got an extra column so if we get rid of that extra column we can see It'll have the same visual layout we have three rows and three columns now the numbers inside the cells are different one two three five six seven nine ten eleven the indices of the rows and columns are the same three rows three columns nine cells we know this from basic geometry our last call pointer is three there's three columns and the last call pointer will point to beyond the last column because we have zero one two so three columns and our last row pointer is also three that points to beyond the last row the first row pointer starts at one now I said earlier that we go across the row go down go the row into first Traverse the call in reverse and then Traverse the last row it's actually a little different I actually started out by pre-populating the first row by pre-populating the first row by pre-populating the first row and the reason I did that is we can see that our Matrix our first row corresponds to the first three things in that Matrix so I thought well why not just populate the result with our first row and that's what I did you can see where this destructuring statement here so the spread operator sorry um so we have our three rows three columns now when we step we're going to see that this first row is going to be traversed and that's already actually done uh and then the last call pointer decrements so now our last call is two we're going to Traverse down the last call we're going to put the last two cells in those corresponding rows in our um and to our result we step that and we get the last two now we're going to step through the last row which we just decremented you saw that decrement automatically when I click the step button and we're going to go to the first call and that's not going to change all these pointers will stay the same now and we go to the First Column and we're going to Traverse up the first column in reverse and that First Column pointer is going to increment by one finally we do the last row of the first row which is our last row to Traverse and we'll know that because when we're done with that the value was 2. the first row and the last row have the same value and when that happens there's nothing more to Traverse that we're done and as you saw earlier we can have this with any number of rows and columns in the demo so we can go across and go to the four and it pulls them right from the Dom you see these are now three and the last row is three zero one two three and this will go down to two and then it'll Traverse across to our first call which stays at zero and then it goes up to our first row and the column increments and then we Traverse across the first row and then we'll increment it too and so that happens uh based by reading off of the Dom and I made this demo to Showcase how it works and the reason for that is that it's so messy with the four pointers and with the loop through each pointer from one pointer to another pointer and the loop having to change its incrementing variable like I or J for each case that it just got too messy to try to explain so the best way to Showcase it is with an actual physical demo I'm going to put that on my website but here's the code we start out we've got our pointers right here last call last row first row First Call and we've got a cur pointer that's our cursor and that shows where we're at in our result we don't need that we could use array.prototype.push but I chose to use array.prototype.push but I chose to use array.prototype.push but I chose to use a curve property because I thought I would pre-populate the length of the would pre-populate the length of the would pre-populate the length of the array so we start out by populating the array with the first row so our result right away has from example one two three and it'll have that from the start and our curve property will point to the last call which would be index three zero one two three so what point to that would be that's where it's going to be at that's where a cursor is going to be at for our output for a result the result's length is the length of the array and we multiply that by the last row so again rows by columns indicates the number of cells three by three is nine we've got our four functions Traverse row Traverse call Traverse row reverse and Traverse call reverse and we set this up in the loop remember we already traversed the first row by pre-populating that result pre-populating that result pre-populating that result the way we're going to Traverse the rest of them is we're going to start with a column and we're going to check to see if the first call in the last call are equal and the reason for that is well if you think about if we had a one column grid and we go and the last call is going to be one because that's the length of the columns then the length of the columns is shown up here Matrix zero dot length we have a row with length one okay so in that case we'd have a row with length one so that would be one and then as soon as we Traverse the first row and we had to go down then it would decrement that so Traverse call well last call will go minus and then it'll become zero and so you think about it after we Traverse call we go minus calls and if the first call and the last call are the same and in this case they're both zero this hypothetical example I'm thinking of uh then we'd be done we'd be all done with that I could think about that even an example here if you want to think about how that would work you can showcase that and I've never done this is the first time I've shown um even tried testing with one column in our demo but this is how that should work and hopefully it does our last row is three and the last call is one we'll go this uh Row one should highlight one okay it does last call goes down to zero now it should go down last row should go down to two and since the last column is done well there's nothing more to do so we're already done so that's what would happen in that case so back to this example the First Column if the last column are the same right we already got the row and then we go to column just as we did in our demo here we did the row that was pre-populated it's a little different in pre-populated it's a little different in pre-populated it's a little different in the demo we have to click step to see it and then we did the column just like we see over here we did this column and if the first column in the last column in this case they're both zero then we would break okay now that now back to the actual example one okay and just go back to thinking about that example for a second Traverse Row in Reverse so we Traverse the row that was pre-populated Traverse the row that was pre-populated Traverse the row that was pre-populated we traversed the column we got six and nine all right that would be the next two things we would get into there and then we would get Traverse row reverse and that will give us eight and seven in here and then uh we'll go from the last uh from this row to the First Column and then we go from the first column up to the first row which is one and then we go from our first row which is one we Traverse across that row to um to the last call and then we're done and that's how this function works so like I said it's a really messy function but if you want something that's a little easier to start working with rows and columns and things like that with a grid set yourself up a grid and then reverse the rows and the columns so you could take one two three four five six seven eight nine and you could display it as oh we could have one four seven two five eight three six nine thinking about the row values like that the way to do that would be to switch around the I and the J variables so once you start playing with that you'll see how that's useful now in the Dom document object model we have tables and the practicality of this type of problem is that we can use the Dom to update values in the browser that the user can see and user can interact with as I've shown in this demo here so there's actual practical value to this leak code problem in front-end leak code problem in front-end leak code problem in front-end programming you can have as many rows and columns as you want in this uh in this table so and this is all updated dynamically I'm going to leave this on my website so you guys can use it thanks for watching
Spiral Matrix
spiral-matrix
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,3,6,9,8,7,4,5\] **Example 2:** **Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\] **Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 10` * `-100 <= matrix[i][j] <= 100`
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row. Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
Array,Matrix,Simulation
Medium
59,921
1,996
Ajay Ko Hello Hi Friends Welcome Back Today We Are Going To Solve There Problem In This Six Number Disorder Actor-Singer Kam So Let's Go Through The Disorder Actor-Singer Kam So Let's Go Through The Disorder Actor-Singer Kam So Let's Go Through The Description Of The Problem And Will Look Better While Examples Explain How We Are Going To Solve The Problem So You Are Playing Game Date Content Has Multiple Characters Sandwich Of The Character Is Starman Properties Tags Difference Giver Today Interior Properties Were Properties Of Equal Two Attacks And Different Sizes Represent The Properties Of The Character In The Game Character Is Too Wicked To Give Any Other Character Smooth Want and Different Levels Regressed Use Characters Attack and Different Levels More Formal A Character Is Set to Give Credit to Another Character Xavier Technology Return Attack Fighter and Different White Sun Number of Birth Characters So This Is the Problem Description Should Have Given Through Eggs Jobs For Example Hindi Second Example You Can See Date For The First Character Artists To Second Step Ki Stree Rate Services Mode On Is The To Also Here Differences True And Third Is Character This Also Creates Ruchi Gardan This Character 800 Indigenous Biological Character Tight Saudi First Character This is the mixture that tweet is a number of birth character Zindagi Hamraj so common this is the problem satirist stupid loosening property link this is electronic waste ₹10 properties electronic waste ₹10 properties electronic waste ₹10 properties firing request to end attacked in different countries will give 110 ras 2515 102 this is the problem so Let's go and discuss of this problem to one other example year for discussion so as you know the first one is attacked and second one is different types of this is water dispenser mix right till character and this is the character similar for second character this is attack And different types of so what they have to give you have to find out all the best characters in this game cheats for example person default seven to madurai 110 177 for example for this attacking power is greater noida and greater than 200 calculate the actual characters in Hindi How To Solve This Problem This Cream Portal To Understand But You Have To Solve This Given Here And Were Shouting Even Here Will Be Solid Truth That You Know Like Asking Website Based On The And Tax Rates And Trick Basically Will Be In Increasing Order for example as you can see in this given there right to give winners at axis in increasing order for example Viswanath Danish Woman in this world who is not three little increase in grade 4200 like it increasing order take it 9:00 and like it increasing order take it 9:00 and like it increasing order take it 9:00 and 98 100th post Means the attack power is in increasing order but that doesn't matter when they are starting and the other things will have to remember is increased attack power is equal for example in this question 80 is equal to 740 this person in this case will have to make sure red The order will begin with difference will be in a decrease in all rights reserved that this decree is 7380 days decreasing order residency year also not 087 days decreasing order night suit with you have to say the are so common I will explain why were shouting air in this question Solve Vishuddha Are 100 Will Just One Minimum Wages In Teacher Dot Mean Value Will Take Right And Will Cry After 10 Solitaire Will Start Traversing The Inner Opposite Direction Lights Of Cost Element Will Not Come On 7th And They Will Go In The Life From The Last Element First Element of the Year I Saw This Order Will Follow After 10 Artisan Grade Saugandh Shouldering Hind This Particular Fashion I Will Explain During The Solution Saw In The Beginning While Visiting This Norm Of Human Rights And Minimum Value Will Always Be Best On The Different Sites The Minimum Is The Minimum Value Software In The Festival Of Lights Minimum Wages In Which Is The Minimum Subscribe So You Minimum Value Now Is 70 Will Have To Take The Maximum Minimum One Is The Mean Of The Valley And You Will Go And visit this element will always keep checking next subscribe this Luddi Minimum they have seen so not place will update minimum value from 2ND year result 100 in the beginning result account it is equal to number of character 600 have not seen anywhere character basically it means 16 After disawar mein begumpet now you will visit this site co martin rise again will check the difference power is not less dene attract because distance and ise tower mini 600 not least 10 minutes will update our me to take nobel price suav so after president Rule 273 Days Prodigious Check The Difference Power Rates Landed So Ben Ten Light Show Will Update Our 121 Development Gorgeous Finding In This Chapter Basically So As You Can See 20 Strong Characters In This One Great Sorrow And Time Will Not Determine Ubal Update Only For Finding like and greater meaning when life is le times will not update vu forward care again will come per difference value 00000 updater and result-2012 512 with chapter soft developed result-2012 512 with chapter soft developed result-2012 512 with chapter soft developed uc 80 eating like it is from neck 1788 mode on 0824 attacking and Expensive for both and greater than seven 737 heard through have started sharing this particular fashion rag pickers directions hui channel aa tu yaar traversing mission identify what is the weather character development the sorting mature that when you have some unique place like whenever you have less difference Power And Different Magnification Hui Always Know That Is Off Kar Character Absolutely Yadav Vijay Have Turned Away At Big Boss The Special Guest Is Less 1010 Urs Laddu News And Mean Value Front Always Recommended Is Hair Is Seven Do Not Repair Reserve Which Were Basically Because This Post Will Definitely Small Pain Back End Second Water Small Crescent Minimum Value Right Because Minimum Value Means The Difference Power Musically Tattoo Have Seen Some Point When They Are Coming From This Backward Direction Sweetest Words Dasha Hui Have Started Wearing This Particular Fashion Om So Let's Go Ahead And Lipstick Kallu Katri Many Players For Silver 4393 Is Ajna Resistant And So Will Increase And Account To Three Layer Now He Got To Three To Maintain Is Not Least 20 So I Will Not Let Anything In This Case And Will Move Forward With Big As Three Maintain is not with wearing this case ka vikas harivansh u compare a term of any three come out and attain wealth will not let 2183 difference value of three come 80 81 martin also click switch on tend difference not let s oo will not let anything come in They are India first to two so this sentence will update power reset account 214 type submarine picture 1535 vs will again updated 253 10155 difference power is hui thing dena and mean value new will updated again so one increment was with Vikram learn answer right number of birth Characters in this cream basically a tight 34 hydraulic festival you message decisions witch player on 1.5 inches seervi hydraulic festival you message decisions witch player on 1.5 inches seervi hydraulic festival you message decisions witch player on 1.5 inches seervi that and you will also be aware basically sonu s you can see please an all slur Dainik Martin Wright s you can see everything is my Love And Warmth In This Clip Sudhir Were Falling Into Mature [ __ ] You Sudhir Were Falling Into Mature [ __ ] You Sudhir Were Falling Into Mature [ __ ] You Were Traveling From This Direction Will Keep Track Of The One Variable In Preventing The Way Find More Value For Different For Example I Think They Need More Value Will Keep Track Of Moral Values ​​Which Means Value Day Video Player of the Year for Example Hair Oil Turn on Airplane Mode Dutable Look So Vinati This Placement Android Day Automatically Digesting Will Bless the Native with a Trace of We're Going to Beauty Basically So Let's Take a Look at the Implementation Now So Fast Type Two Ka Result Card 2012 Yaar Going To Return At The Rate Of Number Of Character Think This Is The Most Important Part 2 Years Ponting The Head Of The Character From 21200 To Zinc 120 Means Attacking Power Of Birth Characters That Then Akbaruddin Were Going To 100 Dam Bay Stone Decreasing Defensive Power Prithvi-1 - 54 Minutes Defensive Power Prithvi-1 - 54 Minutes Defensive Power Prithvi-1 - 54 Minutes Decreasing Defensive Tower Basically a Fair Nor Not Equal End Will Sodium By Increasing Attacks Power Ranger Increasing Attacks in Power Basically It's Zero - 200 Attacks in Power Basically It's Zero - 200 Attacks in Power Basically It's Zero - 200 Increasing Attacks in Power Sudesh YouTube Straight Resort Wave 314 3080 Increasing With A Matching Like This Is The Match In Greater Traction Power Of Matching Day In This Is The Difference Power Will Be Decreasing 88117 Like This Is Best Web Site Posts Witch To Cup Mean Very Humble Person To Mean Value Phase From Million Character To The first character web from the back website asleep reading the egg properties of annual meeting attend difference value from dowry difference values ​​gender minimum day to have seen difference values ​​gender minimum day to have seen difference values ​​gender minimum day to have seen so far applied and give increase the result for example in this case write the difference fluid and what you Mean Value To Have Seen So After 10 Minutes Will Prevent Its Object To Here Do In Here And They Will Update Them In Every Quarter Rates Will Be Maximum Of Main And Different Slide Dubai Maximum Prominent And Defense 100 Maximum Means For Example In This Cost Certificate 04 2010 Is More Than Hit Like This But After Death At Present And So Will Stay At United States Politically Aware Doing So Will Like That The Character Reader For Loan From Backwards And Will Know How Many Accused Characters In Real Time The Are Wearing Preventing Result Sauce Etc. Example That You Here Right So Which Example So Let's Go Ahead And In This Example Redwrap Solidworks Swift Giver Six Software Getting 601 Tantra Branches And Ki Century Child Worth Submit Isolation Word Acid But Bloody Mary Submitted For Your Soul Will Arrive That Example Enemy Is The giver na hmm is the first 100 exam hai tu yaar getting beaten pakistan service correct sunna loot like one care a kar do hua ki swapna dosh casinos because of this prepare saaf 4200 getting correct answer S300 old is gold and submit our solution a Solution God Accepted By List Code That And Order For Beauty Contest How Sir Fast Hair Visit 40% Better Run Time And Fast Hair Visit 40% Better Run Time And Fast Hair Visit 40% Better Run Time And Third 2% Better In Memory Side 100 Index Pretty Third 2% Better In Memory Side 100 Index Pretty Third 2% Better In Memory Side 100 Index Pretty Good Time For This Way You Can Solve Number Of Birth Character Sindhi Camp Some Most Important Part here at 30 to understand that you have started sharing and in the villages by using the dom invariable tried to keep track of the basically the minimum different so life in west indies is solid criminal mode settings virus use this readers space is so in this case Worst like the minimum variable will be seven writes what ever is solved boon will keep updating the other very 228 feature updates minimum to the next maximum of the seven my types of maximum and 761 maximum days after the train bellcomes admin vikram 3133 how you want To Do It Basically Tight Medium Stand And After That When They Look At The Enemy Dhundhaleshwar Band The Means Of Birth Ka Pair First Year Also Seven So Ben Tennyson Software Also This List Contains A Little Submit Kar Free Are Also 215 And Destroys All Class Tenth Decade And Also For The Way Are A Solid The Forest Attacking Power Will Always Be Pleased And Saturn Rights Over You Don't Have Too Much Only Will Have To Worry About The Difference Power Will Check In These Cosmic Vibes Coming Started So Band Sidhave Solid You Have A Positive Change My Play List of List Codes and Solutions for My Channel Please Witness to All Problems of Big Companies Like Amazon Apple Google Microsoft Facebook Admin or Dasha 299 Forget Your Problems Coding Problems with Dynamic Programming in English Related Problems Related Interview Questions Edifice Binary Search Tree Jara Phir Related Problems All Sorts Of Different Problems You Will Get Here A Should Explain With Java Code Please Go Through The Check List Also Go Through Tak Play List Of All Your Job Interview Playlist Saluto Telephonic Interview Questions Arduino Explain Uchcha Rashi Fix Companies And How to answer this question solve gotriya preparing for in bluetooth is channel definitely help you if you like this video and if you find good help Please subscribe to the Channel and liked video your subscription was red important because that is the video can reach to more People can also watch this video will dare preparing for interview and you can also get health Please subscribe to the Channel and thanks for watching the video
The Number of Weak Characters in the Game
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game. A character is said to be **weak** if any other character has **both** attack and defense levels **strictly greater** than this character's attack and defense levels. More formally, a character `i` is said to be **weak** if there exists another character `j` where `attackj > attacki` and `defensej > defensei`. Return _the number of **weak** characters_. **Example 1:** **Input:** properties = \[\[5,5\],\[6,3\],\[3,6\]\] **Output:** 0 **Explanation:** No character has strictly greater attack and defense than the other. **Example 2:** **Input:** properties = \[\[2,2\],\[3,3\]\] **Output:** 1 **Explanation:** The first character is weak because the second character has a strictly greater attack and defense. **Example 3:** **Input:** properties = \[\[1,5\],\[10,4\],\[4,3\]\] **Output:** 1 **Explanation:** The third character is weak because the second character has a strictly greater attack and defense. **Constraints:** * `2 <= properties.length <= 105` * `properties[i].length == 2` * `1 <= attacki, defensei <= 105`
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
Math,Dynamic Programming,Combinatorics
Hard
null
172
Hello Everyone Myself Devanshu Kumar And Today I Solved Question No. 172 Of Lead Code And The Question Says Given An Integer And Return The Number Of Trailing Zero In A Factorial So The Question Is Telling Us Given An Integer A And after calculating the factorial, we have to tell by counting how many zeros are there in the last part. This is just a simple question saying this, so before solving this question, we should know what is a factorial and how can we. How can we write a factorial so here we can see that a factorial is this n in a my way up to if we multiply zero then whole things go be zero so the one thing we have to remember is that we don't have to multiply zero by zero no So they will be all zeros so it is a factorial for as we can see that in example number one input is n equ 3 then output e 3 and ect 5 then output is v so what is the approach what should our question be So come to the white board before solving this type of question, we will have to think that we will have to take some numbers like we did here by taking four to find the factorial of 4 * 3 * 2. * 1 up to one it is to find the factorial of 4 * 3 * 2. * 1 up to one it is to find the factorial of 4 * 3 * 2. * 1 up to one it is equal to 4 * 3 12 and 12 to equal to 4 * 3 12 and 12 to equal to 4 * 3 12 and 12 to 24 so factorial of ch is 24 but if we do the factorial of pa then it will come to 120 5 in 4 in whatever so it is 120 so here But we are getting to see one thing, we are noticing that here there are no zeros till four, there is no zero, d is happening in the last but from f to h, when we started, one zero was added, when we went to nine. We will talk about Nan, when we take out the factorial, there will be one zero added, but if we take out the factorial of 10, then we will see two zeros in the last, we will see two zeros. Here is a factorial calculator as we can see when we take four. When we calculated, we were getting 24, when we did F's, we got 120 and when we did N's, we got 362 880, that is, we got only one zero, in the end, we are noticing some points that All the numbers between one and four. Sorry. All the numbers between one and five. There is no zero in the factorial. But when we start from five. Will do and go till n then we are getting a factorial and after that give a similar factorial from 10 to 15 and we will get two zeros in it. Okay so what we notice is that if it is divisible by f and whatever number it is divisible by is divisible like there is no divisible between five and four, it is not divisible at all, that means it will be zero, it is not a divisible, that means that here we will not get any zeros in the last and but between f and na And if we divide na by f then we will get one by one, f will divide na by then it will give a reminder that means we are getting to see that we did this once that means that there will definitely be one zeros but what. If the number is 30 the number is like 30 one divided by f it gives si then what is the facto so there is a six zeros in that number after doing factorial of 30 no it is a false because six is ​​also no it is a false because six is ​​also no it is a false because six is ​​also divisible by f one When we divide f by f, it will cut it once and then it will give us a reminder. If we see one, if we divide f once by si, then sorry, that is what we are working with. We have to run it, no problem, let's see, when we divide F by six, then we will divide it once, we will get one in one digit, we will get the return only once, then we will get a reminder that neither the total number which is added to the last It will be 6 pv, that is, inside a loop, we will have to update a again, so this is our approach, so this is the approach that I use, so let me repeat once again that when we updated I saw from one to four that no number is divisible that means here there will be no zeros in the last d then we went from f to n and divided by n till n then we divided by f then We saw that it is being divided once, it is being divisible once, then it will give a reminder because it is greater than five, so we will get one zero and one zero in it, then we saw it like this, but we saw that when 30 is divided by 30, we Saw that there it is divisible by six times, that means there will be six zeros, but it turned out to be wrong, there will not be six zeros, because 6 can be divided once more by 6, then 6 = then 6 = then 6 = total zeros. This is our approach and as we can see, if we find out the factorial of 30, the factorial tooth of 30 is 4 5 6 7 total zero, total zeros at the last is seven, so we saw seven zeros at the end, so what will be our approach? To solve the question, basically we will solve this question in such a way that n is always updated. If n is always updated then we will have to create a count int count which is our zero count by subtracting t count equal to zero then inside the while loop. f a greater equal greater than zero if a zero is greater than zero then this loop will continue count plus equal to n ba f and the ta data type is integer z a we can see so if it comes in point then it Point Na Leke Wah Jo Integer Hai V Lega Then Semicalun We Never Forget In Java N Ictu Ava F And Here We Update Value Of A And Then Return Count Return Equal To Count So What We Did In This Question First Of All We Created a count integer which will count to zero and then we gave the condition in the while loop a greater e 0 then count plus equal a ba f that if it is divisible by f then it will add to the count and if For example, for the factorial of 30, after six comes, we have to update the value of A because sis 6 can come inside again and after coming inside, then one ct will come again due to which it will be plus in the count. Due to addition of 6, 7, zero will come in the last so this is the solution and let's check it ok gov sec sorry or now check ok so without any error this is accepted this code is accepted now submit Submit Let's check as we can see there are zero ms run time zero ams a memory used is a 40.6 a 66 ab so this memory used is a 40.6 a 66 ab so this memory used is a 40.6 a 66 ab so this is the solution of question number four sorry question number 172 factorial trailing zeros I hope you like this code Like this solution thank you for watching me sorry watching this code watching this video no please like share and subscribe thank you we
Factorial Trailing Zeroes
factorial-trailing-zeroes
Given an integer `n`, return _the number of trailing zeroes in_ `n!`. Note that `n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1`. **Example 1:** **Input:** n = 3 **Output:** 0 **Explanation:** 3! = 6, no trailing zero. **Example 2:** **Input:** n = 5 **Output:** 1 **Explanation:** 5! = 120, one trailing zero. **Example 3:** **Input:** n = 0 **Output:** 0 **Constraints:** * `0 <= n <= 104` **Follow up:** Could you write a solution that works in logarithmic time complexity?
null
Math
Medium
233,809,2222
1,458
Hello everyone welcome to my channel quote sorry with mike so today we are going to do video number 67 of our dynamic prime playlist ok so the lead number is 1458 today is a hard mark but it is quite easy actually this is a dp named lcs The concept is Longest Common Subsequence. The code is an exact copy for those who have done it. There is no problem for those who have not done it. You will understand it very easily. The name of the question is Max Dot Product of Two Sub Senses. It is ok. Company: Product of Two Sub Senses. It is ok. Company: Product of Two Sub Senses. It is ok. Company: I still don't have any idea as to which company has asked but I will update soon on Getup as soon as I know, let's see the question, what are you giving, numbers one and numbers two are ok, return maximum dot product to you. Which two have non MT subsequences between them and those subsequences should be of number one and number two and they should be non MT. Okay, from any number one, let's assume that you have to create a sub sequence which is empty. This cannot happen, it should be non-MT, it should be non-MT, it should be non-MT, it is okay, with the same length, both should be the same, okay, a sub sequence of a ray is a new ray, which is form from the original. This is all about the sequence. What is a sub sequence? You must be knowing this, okay, so let us understand by looking at the example, as these are two examples. Okay, so first of all, from the example here, let us understand what is the meaning of dot product. In this, it is said that pick a sub-sequence from numbers one. said that pick a sub-sequence from numbers one. said that pick a sub-sequence from numbers one. And pick up the sub sequence from numbers two. Both should have the same length so from numbers one I picked up 2 1. From numbers two I picked up 3. Let's assume that from here I picked up 0 -6. Let's assume that you -6. Let's assume that you -6. Let's assume that you can pick up any sub sequence. You can also choose the length, it is okay, if you want to do the dot product of both, then 2 * 0 2 * 0 P 1 * -6, this then 2 * 0 2 * 0 P 1 * -6, this then 2 * 0 2 * 0 P 1 * -6, this is the dot product, multiply it by this, then multiply it by this and add both, then it is okay. Kitna aaya answer 0 -6 t is -6 ok so let's see answer 0 -6 t is -6 ok so let's see answer 0 -6 t is -6 ok so let's see what other possibilities are there 1 I can see this 2 -2 1 I can see 3 2 -2 1 I can see 3 2 -2 1 I can see 3 -6 ok so let's see what the answer -6 ok so let's see what the answer -6 ok so let's see what the answer will be 2 * 3 2 * will be 2 * 3 2 * will be 2 * 3 2 * 36 plus -2 n 36 plus -2 n 36 plus -2 n -6 2 * 3 6 becomes 6 to 12 minus plus -6 2 * 3 6 becomes 6 to 12 minus plus -6 2 * 3 6 becomes 6 to 12 minus plus becomes 12 6 18 ts or its answer is 18, you will be able to get a bigger answer than this, you can take any sub sequence, ok its three Take all the sequences of length 215 and 30 -6, even then you will not 215 and 30 -6, even then you will not 215 and 30 -6, even then you will not get 18. Okay, so let's see how you will approach, what will be the thought process, why this is a question of DP, okay, what is the intuition behind this, so everyone understands well. First of all, let's take a very small and simple example, let's say we have an example of mine-1 and the second one is example of mine-1 and the second one is example of mine-1 and the second one is nine, it's okay, numbers is one, it's two, see, this is given in the question, isn't it? You can choose any number from here, okay and you can choose any number from here, right, like look here, I have created a sub sequence, in this I first chose two, then -2, now either this or this. chose two, then -2, now either this or this. chose two, then -2, now either this or this. Maybe first I would have chosen -2 and then I would have Maybe first I would have chosen -2 and then I would have Maybe first I would have chosen -2 and then I would have chosen F so we have a lot of options and what does the sub sequence mean you take any 2 take 1 take 2-2 take 2 you take any 2 take 1 take 2-2 take 2 you take any 2 take 1 take 2-2 take 2 And so on, if you look at it then you have options, right, similarly here also you are getting options, don't you accept from numbers one, this numbers one is yours and this is your numbers two, so here also. So you have options, don't you believe that you are standing here, this is I and this is J, so you have a lot of options, you can either take both I and J, okay, that means Mive and minus, sorry, take Mive and Take that, okay, that means what did I do, I took both aa and j, okay one option, so that is -1, took -1, sorry, took -1 and one, the -1, took -1, sorry, took -1 and one, the -1, took -1, sorry, took -1 and one, the second option, what can you see, I took -1. I took -1. I took -1. Took it is fine but did not take this one and said that if I get any other number next then I will take it, meaning if I write it in the sense of variable, in the sense of index then I took Aa, left I as it is but said J. I will take someone else's number and if I want to write here then which one have I taken, I have taken it and J has also been taken. Okay, I have left I here and sent J ahead to see if I get any number further. I will take it from there, okay, and what is the option, maybe I do n't take I send I forward and tell J, you are here, okay, this is an option, so now look, pay attention, let's draw the essence option here. Once here I have I here let's draw this I and this is J so one option so what I see is what I did is take the I element and the zth element okay meaning what is my sub sequence my first. One is from Are and the other one is from Are, I took these two subsequences and if I took the dot product of both then what would be the dot product of both - 1 Nav is okay Na Aaya what would be the dot product of both - 1 Nav is okay Na Aaya what would be the dot product of both - 1 Nav is okay Na Aaya is okay and what can be the second option that you are okay you are I And J is taken as -1 and 1 is taken, but what are you doing? If you -1 and 1 is taken, but what are you doing? If you -1 and 1 is taken, but what are you doing? If you want to add more elements then what will you do? Then you will call solve and say i P 1 go ahead, you also go ahead. Go and more elements will come, tell me the result that will come from there, I will add it, okay look here you have taken only -1 okay look here you have taken only -1 okay look here you have taken only -1 and one, what are you doing here that you are taking the second, you are taking the one. Yes, but you are looking for more elements, don't you see, that's why you sent it here, in solve, that further element will bring the next element, which will come to the answer and will send it here and I will sum it here, okay, so I Here, if I take out the dot product of my and w, how will I get manav in 1 plus s? Okay, and if I take out the dot product here, what will come -1, what will come -1, what will come -1, what will come -1, what will come -1, what will come -1, what will come -1, okay, so one option is come -1, okay, so one option is come -1, okay, so one option is this. Show the first option, the second option, what happened that I have taken Aa and J, but then I will take more elements, I have taken I and J, here I am adding Y, I am okay, I am adding the first T here by calling Gave Fard Rikers a call to keep Fard, so my hey what will happen -1 was -1 and was call to keep Fard, so my hey what will happen -1 was -1 and was call to keep Fard, so my hey what will happen -1 was -1 and was forest so come here and Ja will come here remember we had taken -1 and va come here remember we had taken -1 and va come here remember we had taken -1 and va here. Okay, great, what other option is there? I told you another option here, that is, leave both the elements, that is, leave one element and move the other element forward. What I am saying is, let's leave Aa, okay, and move J forward. If you increase the rest of the elements, it means that instead of pairing Maave with this one, you will pair it with some other one. Okay, and what is the last option, brother, solve this, I will not take this eighth element, I will move ahead and J. I will let it be, okay, let's move this A forward, I will find some other element, I will pair it with J, so this is how many four options in total, I have four possibilities, okay, so it is difficult to expand all the branches, which means the tree will become very big. Let me just expand this one and show you why I am expanding, you will know a very important thing in it. Okay, I expand one branch so that I can know the base case because when the base case is known when you are at the very bottom. You go to the leaf node, okay, so one value, you saw that by multiplying Nums Aa and Nums J, I am okay, firstly, the value is the same, secondly, what happened is that if Nums and Nums J are taken, then you got but and Also, it is okay in subsequence. Meaning in subsequence, we took -1 from the first one, took one from the second one Meaning in subsequence, we took -1 from the first one, took one from the second one Meaning in subsequence, we took -1 from the first one, took one from the second one and we are adding more elements, dot product of this and we will take more elements by doing plus, this is the second possibility, third possibility. This is done, the fourth one is done, so let me increase the possibilities of the second one and show how the tree will look, so let's move ahead here, now look at how many options I have, then I will have four options, not three, four options, first option, what did I say? That is, take only this element and this element, meaning -1 and one, this will be the sub sequence, meaning -1 and one, this will be the sub sequence, meaning -1 and one, this will be the sub sequence, sorry -1, from numbers one and one, the eighth element is sorry -1, from numbers one and one, the eighth element is sorry -1, from numbers one and one, the eighth element is taken from this, and the seventh element is taken from numbers two, then its dot. What will be the product? It will be simple -1, ok, What will be the product? It will be simple -1, ok, What will be the product? It will be simple -1, ok, what is the other option, take both - 1 in what is the other option, take both - 1 in what is the other option, take both - 1 in 1, but bring more elements in the sequence, ok then i is 1 and j is 1, ok then you are. When we do 'P', here it is -1 -1, it is -1, now look, it will do 'P', here it is -1 -1, it is -1, now look, it will do 'P', here it is -1 -1, it is -1, now look, it will move forward, it will come here, out of bounds, if it is out of bounds, then look, when it is out of bounds, what do we have to do in return? It is very important to pay attention here, what has been asked from us in the question is that we have to find the maximum dot product. Maximum is fine. Okay, we have to find the maximum dot product. So if we assume that a and j are out of bounds, then you must be feeling that it is not good. Now if the element is not there then the dot product should be zero. So if you send zero then what will be the problem. Let us assume you have sent zero. Okay then look at the answer of this branch. The answer of this branch is -1. look at the answer of this branch. The answer of this branch is -1. look at the answer of this branch. The answer of this branch is -1. Okay if you have sent zero. So according to you, the answer will be this because we have to find the maximum, otherwise you will say that well, zero is bigger than the number, so the answer should be zero, but pay attention, here both are out of bounds, what does out of bounds mean that the numbers are one? From numbers to will also get MT sub sequence. From numbers two also you will get MT sub sequence but in the question it is said that MT sub sequence cannot be taken. Okay, so in the case of MT sub sequence i.e. in the Okay, so in the case of MT sub sequence i.e. in the Okay, so in the case of MT sub sequence i.e. in the base case, this is your base case. In the base case, you You cannot send zero. If you send zero, then look at you. In the case of negative, it will not be a big answer and we have to find the maximum only, otherwise we will feel that zero is the answer which is wrong. Right, then what will we do or we will give minus if you. If you want it to be yes, then the answer should be nothing because this is an invalid case, it is MT sub sequence, so I will send a very small value, I will send minus infinity, now see what will happen, minus infinity is there or -1 big happen, minus infinity is there or -1 big happen, minus infinity is there or -1 big mive. If it is big then I will select my, okay, maybe some answer might have come from here, Here the service is right, I will return the answer that comes out of these four. This one will return the answer that is right. In this case, whatever answer comes from all four, I will return it. Okay, then the answer here was -1, then this guy will return something. answer here was -1, then this guy will return something. answer here was -1, then this guy will return something. This guy will return something, the maximum that will come out of all of them will be the answer here, its ok, similarly all the cases will increase, four branches will emerge from here, ok, so see, the base case was very important here, is n't it? Minus infinity or send any very big negative value. I will send 9 to the power of minus 10. There should be a negative value. There should be a big negative value because we have to find the maximum. If we send a big net value then see, we will avoid such cases. Here, if you send minus and tha zero, it would get messed up, so if you send minus infinity, it is a very simple code. Exactly, the write was done in the longest common sub sequence like this, so see how simple the code would be. I solved and called index number. Zero, this is rectangle, this is J, both zeros started from zero, okay, now I am writing the solve here, okay, Ima J, okay, first I write the base case, if aa is equal to a, that means it is out of bounds or Then it becomes JEA, meaning if any of the two is out of bounds, then it becomes an invalid case. Look at what I am saying, let us assume that this number is one, in this number there was Natu and this number is two, in this one was 3. Okay, let's assume that your J is here and Aa is out of bounds. If Aa is out of bounds, then it is obvious that you cannot take the dot product. If Aa is out of bounds, then there is no element, meaning. So you can't take one from anyone, na aa out of bounds, what does it mean that you will get MT sequence but you cannot take mt sub, so whether aa is out of bounds or aa is not out of bounds and you are out. Whether it is out of bounds or both are out of bounds, or even out of bounds, meaning if either one is out of bounds, then we have to return, that is why I have written more here, it is okay, both and will mean both are invalid cases, okay. So now look at this, as I told you, I is here and if J is out of bounds, you will easily find it in a branch. Look here, I is here, I am increasing J, so Here too, there would be a case where Aa remained the same and J was moved forward, then a case would come where Aa would have remained the same, if Aa had come then that case would also be found in our tree. If you don't have any tension then this In this case, what did I tell you that I will send a very big negative value as return, I will not send the power of minus 10, okay and why are you sending a big negative value, that too I had explained to you here in the tree diagram, okay, great. We have four possibilities, you remember the first possibility, remember what was the numbers of which is i element, it is a sub sequence, taken the first element from numbers one, okay, take the i element and numbers two, take j element. So, this is a subsequence or a possibility for me, so whatever answer comes from this, I store it here. Okay, let's store it in the value. The first possibility is this. The first branch is the second possibility. Do you remember I told you? Take i and j, take both, ok if both are taken then ok nums i into nums j taken plus will take more elements j nums j taken plus will take more elements so what did I do tell solve to bring more elements i p 1 j + 1 ok Okay, now what is another possibility, take + 1 ok Okay, now what is another possibility, take I and move J. Okay, so solve, leave I the same and move J. Okay, what is another possibility? Take J means leave J, we will pair it. I moved ahead and found a new element, crossed it with J and left J the same. These are the four possibilities in my tree. That's why I say that whenever you do n't understand what approach to take, always first think about what options are there. What is happening in the question and the correct thing is that it is about options and if it is about options then always make a tree diagram. Tree diagram is the most underrated. You know the trick to solve DP program DP problems. Okay, the most underrated people know its importance. The most important thing is not given, this is the whole code written, it is visible in this tree diagram, so see what I have done, I have converted that tree diagram into code here is the whole diagram, I have written it. I am fine and what we had to do in the end is whatever maximum appears, out of these four possibilities, well means only one element has been taken, the story is over or either both have been taken, I have taken some more elements or Only Tech I or only Tech J. Out of these four, the possible answer which was maximum will be my answer. It is clear till now, it is ok and it is also very easy to memoize. Look, two variables are being changed in order to memoize it. So whatever my DP will be, whatever DP it will be, it will have two dimensions, that's fine, we can make memos very easily, now let's come to time and similarly at the same time, there are two possibilities on each index of numbers two, that I will take it and I will not take it. So for this there is a power of 2 i possibility, for this there is a power of 2 j possibility, right? Why are we multiplying it because for every i there will be that many possibilities. Okay, so actually what will happen to this is the time complexity power of 2. Or write m in place of i because m is the length of AMS 1 * 2 because m is the length of AMS 1 * 2 because m is the length of AMS 1 * 2 pa n. You can also write it like this 2 pa m + n pa n. You can also write it like this 2 pa m + n pa n. You can also write it like this 2 pa m + n This is done without memoization but if you memoize, this is my memo without memoization is fine and if I memoize If I have done it is very simple, what did I say, DDP will be m pv length n pv length, it is ok, then maximum I will visit only this many states, I will not visit more than this, then what will be my time complexity m cross et al code is also very It's simple, let's code it quickly and finish it. So let's code it quickly. We will do the question exactly as explained. The question is very simple, just the identification will have to be sent. Zero th index number of one is zero th index number of two. Okay, let's come now. Next, int solve there are two vectors, both of them have to be sent and int ama int j. Okay, so first of all we write the base case, if aa = a or j = write the base case, if aa = a or j = write the base case, if aa = a or j = n, in both the cases, we have to return it. No, this is our invalid case, so what did I say, minus 10 to the power 9, no, minus 10, I think - 1e to the power 9, no, minus 10, I think - 1e to the power 9, no, minus 10, I think - 1e to the power 9, 10 to the power 9 will become 9. I have sent a huge negative value. Okay, first let's see our first possibility. What was the numbers? Of i * Names of j By taking the eighth element and the zth numbers? Of i * Names of j By taking the eighth element and the zth numbers? Of i * Names of j By taking the eighth element and the zth element, it is okay, and what was the second case, take i and take j, what did you do in that, you had taken the eighth and the zth element, but the other elements were also taken, okay? Moved numbers one numbers i + 1 and j + 1 together okay numbers Moved numbers one numbers i + 1 and j + 1 together okay numbers Moved numbers one numbers i + 1 and j + 1 together okay numbers i into numbers j taken here okay what was the third case that take only i then solve numbers one numbers two i leave it j psv Take it forward. What was the third one? Take only j solve one of the numbers and let j remain the same. What do we have to return? What is the maximum of these four possibilities? What is the maximum value and what was the second possibility? Take Ima take j. Third. What was Tech I? What was Tech J? Okay, it's simple. Let's run a lot of tests to see if we pass without memorization. Okay, here we have numbers one. Here we have numbers two. Here we have numbers one. Here we have numbers two. Let's see if. Able to pass is the example test cases first and time limit seat will give that four possibilities are quite exponential, time complex is done, neither look at the length, I have given 500, so what will I do, which will be DP, it will be 501 and 501. I will take but one thing remember to pay attention here always to memoize we start with minus and sai au but what is the problem here our answer can also be minus and see our third example see the answer minus and If it is I then we will have to take some other value. So what will I do? I will make it negative. Let's treat it with some other big negative value. Some value which cannot be included in the answer. What did I do? I did not put the minus 10 power. Okay. It is clear till now and before calculating everything, we will check here that if I said off a j is ok t a i is not equal to minus power of e then it means we have solved this state then send the result of the state and If it is not so, then send the TIJ here. Okay, let's run it and see. Hope it should pass completely, after that we will submit it. Indeed yes, after submitting it, let's see. If there is any doubt, try to help out in the comment section and Java. You will get the code in Git Hub See next video thank you
Max Dot Product of Two Subsequences
sort-integers-by-the-number-of-1-bits
Given two arrays `nums1` and `nums2`. Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, `[2,3,5]` is a subsequence of `[1,2,3,4,5]` while `[1,5,3]` is not). **Example 1:** **Input:** nums1 = \[2,1,-2,5\], nums2 = \[3,0,-6\] **Output:** 18 **Explanation:** Take subsequence \[2,-2\] from nums1 and subsequence \[3,-6\] from nums2. Their dot product is (2\*3 + (-2)\*(-6)) = 18. **Example 2:** **Input:** nums1 = \[3,-2\], nums2 = \[2,-6,7\] **Output:** 21 **Explanation:** Take subsequence \[3\] from nums1 and subsequence \[7\] from nums2. Their dot product is (3\*7) = 21. **Example 3:** **Input:** nums1 = \[-1,-1\], nums2 = \[1,1\] **Output:** -1 **Explanation:** Take subsequence \[-1\] from nums1 and subsequence \[1\] from nums2. Their dot product is -1. **Constraints:** * `1 <= nums1.length, nums2.length <= 500` * `-1000 <= nums1[i], nums2[i] <= 1000`
Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.
Array,Bit Manipulation,Sorting,Counting
Easy
2204
138
Hello Hi Everyone Welcome To My Channel It's All The Problem Copy List With Random Pointer Sudhir Very Famous Problem Benefits Of Interviews Frequently Which Problem Is Gothami In 2019 One Of The Company When It Was Entering So You Can Watch This Video And Read This Problem Statement This And Services Pure Problem Is Giver List Victim 2.1 Is Next Point S Usual Is Giver List Victim 2.1 Is Next Point S Usual Is Giver List Victim 2.1 Is Next Point S Usual Traditional In This World And The Pointer Reference Between Random Dengue Link We Anything Anywhere Nodding Like Forward Let's Forward Backward And Channel It's Also Asked For The Example Of Birth Notice From Other Note 0.7 is going from this From Other Note 0.7 is going from this From Other Note 0.7 is going from this point to point channel that and point of thirteen is point in back to the self note 7 similarly random point of your point in back to the note one so this is the place now have to dipti this latest and return entry mode Of the place so let's understand this problem over share in all detail certificate copies fish node and also formed a structure light point of profit list is point connected seven and 3.2 thirteen der android 2.2 gen 3.2 thirteen der android 2.2 gen 3.2 thirteen der android 2.2 gen similar and uppoint 18.23 copycats similar and uppoint 18.23 copycats similar and uppoint 18.23 copycats note 7 fennel will solve this Problem solved and the street forward solution is like first withdrawal lettuce next point subscribe and will dhanol notification notes of 420 56001 and marti next point draupadi se district 131 you slept also will keep copy light mapping of the original note between 727 16 treatment call vijay phase Pet one should be selected for example to clarify his left side Original from this note Copy of playlist bill * Avoid vehicle sales and node in * Avoid vehicle sales and node in * Avoid vehicle sales and node in The Channel Please subscribe and subscribe the not go to next 9 0 1 0 Which Email ID Care Other Notes Like Love In The Midst Us Jor On Video Channel and subscribe the Channel Original This Problem Ka Solution User Can Not Give Up And They Should Refrain From Next Point To Do Subscribe Now School In This Rule Cars Id Hussain First Division As per Will against current point up from the chair and check where is the point of this can not responding so will go with its do to for medicinal value Tiggy A R Rahman Sun will be mapped this to describe some random of dresses method value from doing So Will Get Emanating From Chronic To Swadesh Points 244 Similarly 1431 Will Get Mapping 100% Random Points To This Point Mapping 100% Random Points To This Point Mapping 100% Random Points To This Point Minto 700 First Form Will Get 300 Points To From This Point To That Point A Business Meeting From Zombie Maps And 1000 And Appoint A Steam Shovel Method In this to the sentence for this is like this similarly for 11th seed to 0.5 inch 22.10 this point to 11th seed to 0.5 inch 22.10 this point to 11th seed to 0.5 inch 22.10 this point to the most wanted so let's hair mode on is 100 think 15.2 lights will reduce random display is 100 think 15.2 lights will reduce random display is 100 think 15.2 lights will reduce random display use printer every time take also random point and updater Random of current morning redness reducing vitamin point and shoot me point now electronics and this is the time limit your sale add 500 hairs to dot dissolution soft kidnapped from old is not true copy relationship and distorted meet from anywhere you can create do point current from the Head of the list and copy from vidmate software a distant current null and confident mexico day you not from the current person doctors told Bigg Boss initially e absolute will help them not only domino depend come copy is point mintu describes the first period you know dot com According to * Copy Don't Like Share This com According to * Copy Don't Like Share This com According to * Copy Don't Like Share This Daily Updates Copy From Where To Copy Contacts On This Will Be Point In This Site And Also Add This Reference Map India Map 105 Paswan Ne Is Dhandha Paas Bhi Gaye The Start And End Points Are 100 To No It's the Time Complexity of Dissolution Is and Fun Fair Editing Earliest Times Which Studied and Nothing But Water and Space Complexities Also One Can We Further Optimized for This Let's Try to Understand What Will U So Let's for Example BBC Three Not Three No no like this and in between mid-october and mid-november this point mid-october and mid-november this point mid-october and mid-november this point to subscribe videos a that Nancy videos Thanks terminal so disavar relative video co nodal in between the power original and 1999 initially exam point to different appointed It's not destroy the evil for evil the process of gains and it fast prohibit look for the random point of which it to be and will go to daughters and points should be we like share or subscribe point to the that Crowd Message How To Fix Created After Snow In Third Password Will You Will Fetch Only Date Separately In One Place And Make Originality Of Bureau Chief Any Modifications Suicide Lakshmi Explain You More Stripping To Device How Will The So Lets Say This Is Let's Take A B And See further exhausted and not from hair soft will create new note so let's copy note heard create a copy of this will not from persona current not valid and see who can not persona daughters pet next who is equal to current will feel dot x video. com photo copy indigenously developed up and they will update tower current them requested over with it will update dot net dot au subscribe to the subscribe my channel thank you can understand more clearly subscribe from behind and subscribe update from excel for more subscribe And this notice is criminal born in the chief of the written notes copy thing from new note current next current recipe the current dot next similarly update current dot com dot au subscribe this Video give start from mumbai and points 98 Is in that case which starts boss I fail current dot brigade and need to send a random of this cream so current not random not will be current daughter and rich class 100m too like it is not nil directly absorbs water And daughter is the copper metal next9news will be also one and a half hundred to random office ponting also dowry friends appointed for this is water similarly after patience broke subscribe dot 999 9999 subscribe from being supplied from redmi node to start from Dravid And that and current again from is also member step three years in the street journal and what we do not need to fetch water and what is the first day of from work places to visit in B.Sc ek dum and don'ts na ho That decision also tears modified original list there is such original list will update the con is not reduced to current a dot right back to light during winter office not benefit in our dummy Lucknow rally saffron and were removed from overall winner list one side and will update our Sudhir in current with me three do it is the power and everything to submit a is high court accepted sudera three step follow plus bidder for this note fennel assistant copy notes and insults chapter obscene notes20 com maps random point a okay na product Extract Step Three Idiot That Extra Is Coffee Node Mexico Su S C S T Time Beer Processing Overhead Pure Time Complexity Of Dissolution Of The Rich Nothing But That And There Is No Extra Space Wear Earrings Appearing For Ones Tagged For Interest Payment For The Space Of Dissolution is oven feel it solution in daily life product and subscribe my channel and year to model problem on graph 10 customers I have already video posted on 8 and a research university admit sove the video is here and not you can try very problem
Copy List with Random Pointer
copy-list-with-random-pointer
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. Return _the head of the copied linked list_. The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: * `val`: an integer representing `Node.val` * `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. Your code will **only** be given the `head` of the original linked list. **Example 1:** **Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Example 2:** **Input:** head = \[\[1,1\],\[2,1\]\] **Output:** \[\[1,1\],\[2,1\]\] **Example 3:** **Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\] **Output:** \[\[3,null\],\[3,0\],\[3,null\]\] **Constraints:** * `0 <= n <= 1000` * `-104 <= Node.val <= 104` * `Node.random` is `null` or is pointing to some node in the linked list.
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g. Old List: A --> B --> C --> D InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
Hash Table,Linked List
Medium
133,1624,1634
824
Hello guys welcome to front in DC today they will go through there no problem if video channel please like Thursday subscribe definitely subscribe to this website with all through but follow according to rule first apple me to interest remember and Heart to the Video then subscribe to the Page if you liked The Video then subscribe to subscribe The Amazing Comments Subscribe And This Precious Operation List Sirvi A Boy Doing And Iron Team Kashmir Awal Directive Video Please subscribe And subscribe The Amazing Ko Had To Take This Sim Last Words End With Updated String and Beaten at Andheri Discussed Split String in Applied Operation and Every Word and also Ambiguous Words in the New State Dinner Ministry Question to subscribe The Video then subscribe to the Page that Thanks for Watching the Video on Doosra Portal Share and Subscribe to happy birthday chanel
Goat Latin
number-of-lines-to-write-string
You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: * If a word begins with a vowel (`'a'`, `'e'`, `'i'`, `'o'`, or `'u'`), append `"ma "` to the end of the word. * For example, the word `"apple "` becomes `"applema "`. * If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add `"ma "`. * For example, the word `"goat "` becomes `"oatgma "`. * Add one letter `'a'` to the end of each word per its word index in the sentence, starting with `1`. * For example, the first word gets `"a "` added to the end, the second word gets `"aa "` added to the end, and so on. Return _the final sentence representing the conversion from sentence to Goat Latin_. **Example 1:** **Input:** sentence = "I speak Goat Latin" **Output:** "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" **Example 2:** **Input:** sentence = "The quick brown fox jumped over the lazy dog" **Output:** "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" **Constraints:** * `1 <= sentence.length <= 150` * `sentence` consists of English letters and spaces. * `sentence` has no leading or trailing spaces. * All the words in `sentence` are separated by a single space.
null
Array,String
Easy
null
118
hey what's up guys it is Nick white here and I do tech and coding stuff on Twitch YouTube check the description you get all my stuff and we are just doing a we're doing all the leak code problems alright so I'm still in the easy ones so and I'm trying to get better at explaining them over time which I definitely will but we're doing Pascal's triangle right now so Pascal's triangle is actually a pretty popular and common question it's an easy question but it you have to think about it there's like a trick to it a little trickier than some of the other easy ones so basically what Pascal's triangle is it's just a triangle of numbers where you take the preceding row and you add the elements you know diagonally to get like you know sub triangles basically like inner triangles right so you know 1 and then this one and this one get added to make the two this 1 and 2 added to 3 this 2 and 1 added to make the 3 and so on right so basically the problem is just there's some more advanced Pascal's triangle problems but this one is just 2 they give you a number of rows and then they want you to generate the triangle the correct triangle for that number of rows so the way to go about doing this is actually just you know two to four loops and it's pretty straightforward so first of all it's just initialize our return type right so this is the return type we're returning a list of integers right because we have this outer list where each element is a list and then each element of those lists is an integer right so list of a list of integer we're gonna call it triangle you can call whatever you want this is what we're returning though triangle is equal to new ArrayList just to initialize it and if num rows is equal to zero we always do this check for like algorithm problems if the if you're getting an input that's like zero usually you're just gonna want to return immediately we're just going to return triangle because there's zero rows and triangles empty our return ray is empty so that's about right so if it's zero if it's not then we actually do the solution for the problem right so these this is really this right here is the trick to the problem in each for loop we're gonna add something right at the beginning so right the first thing we're gonna want to do is create a list of an integer list of integers and this is going to be called first row and this is actually going to be the first row of our triangle right it's going to be this little list that just contains one so first row is equal to new ArrayList and you know obviously we just want to add one to this and then we're just gonna add this to the output array right so triangle gets added first row so right now our return arrays triangle and it all it has in it is a list with one so right it would be you know everything except for this stuff it would just be this list and it wouldn't just have a list with 1 in it so we do that because now we're going to iterate from 1 because we already have one list into it all the way until num rows because we want num rows sorry you have to do eyes less than num rows because we're iterating up to that number us because we're what we're doing is we're looping up to num rows each time we loop through we're gonna add a new list and right so the first time we loop through we would add you know this one then this one every iteration we're adding a list of integers until we finally have it done and we can just return this list of Lists right that's a good way to do it but you know the thing that we have to we add the first list first before we even do the loop so that we can do this double index grab right because we don't want an index out of bounds error and if we start it if we started at 0 and we did this problem the way that we're doing it's not going to work and you'll see that in a second so we're iterating from 1 to num rows because we already have one array in the output array and you know then what we do here is we grab the previous row and that's why we needed a row in the triangle already we grab the previous list we'll call it proved Row is equal to you know triangle doc gets of I minus one print and then we're gonna have current Row is equal to you can call it row or current row I'm just gonna call it row new ArrayList so we just initialize the current row and we get the previous row and if we were gonna do this without a row into it that would throw an error but since we already put the first row in the first rows already and we could rabbit so prove Row is going to be this one at first hopefully this is making sense you guys I know I'm not the best explaining these yet but you know we'll get better as we go on so we have the previous row in the current row and then what we're gonna want to do is every if you notice guys every single first element of every list is one so this is what we have to do for the second array like I said we're doing this in both cases in the outer loop we're adding the first row initially and in the inner when we get to the inner loop we're just gonna do row dot add one because we already know that we're gonna have one at the first element and we're gonna have one at the last element too so we don't even we're gonna add one at the end too then we do our inner loop so J is equal to one because we're you have it and we're doing this double index grab again so that's why we need to do this again it makes perfect sense J is less than I we iterate up to I because I is going to be the current row we're at each time we loop through this outer loop we're gonna is going to Inc you know the number is going to increase to the current number of elements we need you know there's two elements in Row two there's three elements in Row three and that's why that makes sense so then we do J plus so we loop up to I on the inner loop and what we do is just add to our row only has one in it right now so we need all the other elements and all of the other elements between the inner the first one and the last one are you know a combination of the previous rows elements like I said before the one in the two makes three the two and one makes three to do so to add that we use our previous row because we're looping at this let's say we're looping at this current row right now previous row then we have all the elements already so all we have to do is do previous row dot gets you know J minus 1 plus J plus proof rows plus pre road get J sorry it's hard to explain and type at the same time so this basically grabs from our previous rows the elements adds them together and then it puts it into our row at the correct spot really I'm trying to explain this as best as I can hopefully you guys are kind of falling along with me and after that we'll be at the end the very end because we're looping up to I and then we'll just add the last one and then we do triangle dyad because we are we have our completed row at this point so we add it to our final output array and yeah then all you have to do is return triangle because that's the output and that's how you solved the problem and it's a pretty cool neat solution easy first row to add row I'm sorry oh my gosh those are huge mistake sorry that you're adding the first road to triangle sorry about that just it's hard to type like and explain at the same time like I said um what's the issue here triangle that had oh my gosh oh wait okay it's fixed sorry yeah I'll explain it again in a second okay it works we got the right output and if we submit I should type before I finish explaining these from now on yeah we got it correct what you're doing is you instantiate the output array if the number is a 0 return triangle you have you get your first row you add one to it so we have our first list with one then you add it to our output array of triangle then we do our inner loops like I explained earlier the inner loop will grab the previous row and we instantiate the current row we had one of the current row at the beginning of the loop because the first element is 1 we loop through the rest of the elements to up to the number that we need and we grab four the previous row those elements so we can add them together and put them in the right spots and then we just add the completed row we had one of the completed row and then we add a to triangle and return triangle hopefully that makes sense you guys that's pretty much all there is you know if you have any questions or if you want to talk to me you can join my discord and literally just personally reach out to me I should be able to help you with anything that you don't understand and yeah thanks for watching and we'll be doing more videos so thanks see you guys
Pascal's Triangle
pascals-triangle
Given an integer `numRows`, return the first numRows of **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** numRows = 5 **Output:** \[\[1\],\[1,1\],\[1,2,1\],\[1,3,3,1\],\[1,4,6,4,1\]\] **Example 2:** **Input:** numRows = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= numRows <= 30`
null
Array,Dynamic Programming
Easy
119
117
hey everybody this is larry this is day six of the dissembly code daily challenge uh hit the like button hit the subscriber and drum and disco let me know what you think about today's farm populate populating next white point is in each note too and i usually solve this live um including the explanation so if you want to jump to solution you know go on 2x or jump near the end uh yeah let me know what you think about this format and let me know about your questions okay so let's see what do we want so basically we're given a tree which also have a right node um and we want to connect them okay uh there are a couple of ways you can do this um and i think it depends on you know how you want to do it if you want to use extra constant extra space that's gonna be a little bit trickier recursive with implicit stack doesn't count extra space just seems like really weird um cheating or something like that but really we can just do um a level what's it called uh level order first level first search uh or per level search or whatever it's called uh but basically and it is kind of what it sounds like right for each level you just go to the next level and then the next level you just put point them together um it is gonna um not use so if you do that's going to take a linear extra space because you're putting things on the key or something like that you can also use something like that but i'm not going to do the constant extra space one i think that just takes way too much effort um and you can also do this recursively of course if you just find out what the um what the recurrence is right and also just try to figure about what the invariants are and then variants are what as i always say the things that don't change when um when other states around you change but i am going to do for this one going to do a level order search um it is something that i actually have not practiced that much because it doesn't really come in that much so um was usually you just do my first search so yeah so i'm going to practice that um and i'm gonna do this live so let me know what you think so basically yeah the algorithm that i'm gonna do is just do it one level at a time and then for each level we put next level uh as in the process and that's pretty much it really so okay so let's say level is to go to md next level is equal to also empty uh actually that's let's do current levels you go to root right and then we can do yeah while length of level is greater than zero that means you have something to do on the next level uh so next level is equal to we don't even need it yeah so next level we just set it to empty and then four node in level next level.append node.left and no doubt next level.append node.left and no doubt next level.append node.left and no doubt right of course uh we have to do some things to just basically check that they're not nuns so yeah so if no dot left is not none right and that's pretty much it uh kind of maybe uh and then level is you go to next level right at the very end but before we do that before we do i mean we it doesn't really matter the order we do it and to be honest but now we want to um connect adjacent nodes right so for previous node in uh the zip of level and level suffix so this basically gives us two adjacent notes on the same level so previous note dot next is equal to node and that's pretty much it and i think we have to just return uh the root i think i mean we were trying to know but i guess it's not really clear which one but uh which one which other one would you return right so yeah so that looks good i think i boring i wish they kind of gave a little bit more but let's give it a submit one timeout oh i usually i'm a little bit careful about it but i think today i'm just a little bit tired that's my excuse i'm sticking to it but um but yeah it's just that this that's the only case where uh we don't check for none so we can do something like if root is uh not none we could do this which you know uh preserves the symmetry that we see here um huh level used before simon what oh i am being careless i'm washing a little bit this should be empty and then this should be leveled on the pen uh to also keep it consistent with the other stuff right and this is why we test rings i suppose cool uh looks okay a little bit careless today to be honest uh on the contest i have four wrong answers and here i messed up a really obvious example but now i have accepted and that's good uh so what is the complexity right well it's gonna be linear time because we look at each note at most once um well constant amount of times we but you should know we put it into the next level once and then it is in the level once you know so we put it in the next level once and then we take it out of level once right so it's going to be over one per node and therefore it's going to be our event in terms of space level can we actually add a lot of stuff to levels so it's going to be over n because we each know it goes into level and next level so yeah uh that's all i have in this farm i am a little bit tired today so i'm not gonna up solve it but let me know what you think let me know uh how fast you got this because this is something that's standard and it's the first time that i implement level first search or whatever it's called for in a long time so here's something that i'm happy to kind of do it relatively quickly even though i had a mistake um yeah so if you do it with that first search or breakfast search try to do it with another search let me know uh how you did it how you prefer uh that's all i have for this prom i will see y'all tomorrow have a good night
Populating Next Right Pointers in Each Node II
populating-next-right-pointers-in-each-node-ii
Given a binary tree struct Node { int val; Node \*left; Node \*right; Node \*next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`. Initially, all next pointers are set to `NULL`. **Example 1:** **Input:** root = \[1,2,3,4,5,null,7\] **Output:** \[1,#,2,3,#,4,5,7,#\] **Explanation:** Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 6000]`. * `-100 <= Node.val <= 100` **Follow-up:** * You may only use constant extra space. * The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
null
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
116
971
hey what's up guys uh this is chung here so today uh daily challenge problem number 971 flip binary tree to match pre-order traversal um to match pre-order traversal um to match pre-order traversal um so this is like another three problem basically you're given like a tree uh and then you're also given like the uh a voyage basically a sequence of a desired pre-order traversal of a desired pre-order traversal of a desired pre-order traversal of the binary tree and what we can do is that you know we can flip a note right so by flipping a note it means that we swap the left and right child for example we have this tree right here and if we do a flip on node one here it means that we swap the two child the two children which becomes to this one right and it asks us to find the uh the smallest number of nodes so that the pre-order pre-order pre-order traversal of the tree matches the voyage and we need to return the list of the values basically the list of the nodes that we need to flip right the other in order for the tree to match this up pre-order traversal and if it's not pre-order traversal and if it's not pre-order traversal and if it's not possible right we simply return a minus one so some examples here right so for the first one you know the tree is one two and the void is two one we return minus one because there's no way we can do a pre-order traverse you know uh do a pre-order traverse you know uh do a pre-order traverse you know uh with this two one because here you know if we want to do a swap you know if the okay if the node does not have any children then it we don't there's no point to do a swap and for this one if we do a swap for this one actually so for the node one here so the tree will become to this one right and then the pre-order traverse for this one then the pre-order traverse for this one then the pre-order traverse for this one it's still one two that's why we return minus one so for the second one you know the uh this one is uh pretty straightforward right for this one we simply need to do a swap on node one so we can get uh one three and two right and then first for the third one we don't need to do anything because it's already matched right the pre-order right the pre-order right the pre-order pre-order traversal pre-order traversal pre-order traversal okay and then the uh all the nodes all the values are unique right i mean so this one is like a little bit of variation of the pre-order traversal of variation of the pre-order traversal of variation of the pre-order traversal so first we have to be able to know how to do the pre-order to know how to do the pre-order to know how to do the pre-order traversal right so to do the pre-order traversal we can so to do the pre-order traversal we can so to do the pre-order traversal we can either do a recursive method or we can do a iterative method either way it works in this case and on top of that right we also need to compare basically to compare the voyages right so which means that you know um so we start from the root here right we start from the root and then we compare the current uh root the current uh node with the uh with the current voyage here and as long as it does not match and we simply we just uh simply return minus one because so what we are trying to do here is that you know let's say if the one ma matches the void is the first one let's say the first one is this one right and then we have some like numbers after one here and then we'll compare basically if the current node matches then we'll compare the next one with the ones the left node this is the left node right as long as this left node that's not equal to the to this next one then we know okay we have to do a swap right because otherwise you know we'll never get this uh the pre the desired pre-order desired pre-order desired pre-order traversal so which means that you know every time when we see a difference we'll definitely do the swap right which means that we're gonna swap this left and right subtree after swapping you know we can continue to our uh pre-order traverse uh pre-order traverse uh pre-order traverse right so and also after swapping we'll add this card node to the final answer and then we continue doing it until whenever we see a mismatch between the card node and the current index of the voyage then we know okay uh we find a there's no way we can uh we can get the desired uh sequence here because we already did the swap right and if there's still if still does not match and then we know okay it doesn't really matter how we swap the node we'll never get the desired sequence right so which means that you know we also need to maintain like the index right of the current voyage here yeah so i think that's basically the idea here you know we're doing we do a standard pre-order traversal we do a standard pre-order traversal we do a standard pre-order traversal but on top of that we also compare the uh the left node the current node the left node with the current with the index of the voyage if they are not if they don't match to each other we swap the left node at the left child and the right child then we continue to do this traversal cool so like i said you know if we want to do a pre-auto trigger so we can do to do a pre-auto trigger so we can do to do a pre-auto trigger so we can do either do a dfs or a iterative so i will do the iterative method here because it's more efficient but the dfs is more straightforward you know okay so we're going to have like a length of the do we need probably we don't need the length here so all we need is i equal to zero right because at the beginning pointing to the first voyage right and then we have the answer gonna be the empty and then we have stack right so for the iterative uh pre-order traverse traversal we use a uh pre-order traverse traversal we use a uh pre-order traverse traversal we use a stack right so current stack dot pop you know i'll just finish the pre-order you know i'll just finish the pre-order you know i'll just finish the pre-order traversal you know basically the pre-order reversal is like this so we if pre-order reversal is like this so we if pre-order reversal is like this so we if current dot right write then we do a stack dot append current dot right and then if the current dot left then we do stack dot append current dot left so notice here you know we're doing this kind of uh with pushing the push the right stack for us right child first and then the left that's how we do a iterative pre-order traverse because we iterative pre-order traverse because we iterative pre-order traverse because we want we always want to process the left one first that's why when we push those two child we want to push the right one first and then the left one so that when we do the pop we always pop the left one first and then again right you if this card left one has another two child we're also going to pop this one first and then this one second so that it will always so that basically the left child will always be popped first before the right child and that's the uh the iterative pre-order traversal the iterative pre-order traversal the iterative pre-order traversal and on top of that right so if the current dot value right does not equals to the voyage dot i right then it means that we will simply return -1 right and if the current one equals to the voyage and then we know okay we want to uh move forward move the index forward so that we can compare uh the next one with the left child basically so and then if the current dot left right so if the current left is not empty and the current dot labs dot value it does not equal to the voyage dot i so right and then we swap left and the right one right current.left and then we also add the current.left and then we also add the current.left and then we also add the current uh node to down to the answer right and in the end i returned the answer so that's it i mean so here you know i only compare the left one with the watch here so for the case let's say if the left one does if the left trial does not exist i don't swap because there's no need to swap right so let's say if there is a one here and then there's no left child but there's like a another two child here uh oh sorry there's a another right child here so in this case i don't swap it because you know in this case you know we will simply just try to compare the two the next the right node with the voice with the next voice here if they are not matched if they don't match right then we simply return false because there's no nothing to be swapped in this case right so basically so if the left one does not match the current one so the only chance we can still get the desired uh the sequence here is by swapping the two child nodes here right and then after swapping those two child nodes we continue our uh pre-order traversal and if the next uh pre-order traversal and if the next uh pre-order traversal and if the next one doesn't match then we know okay it means that we already tried try to try it out try our best basically we tried to swap it but still couldn't find the match then we'll simply return minus one so if i run the code here accept it submit yeah so that's it right i mean it's just like a standard pre-order it's just like a standard pre-order it's just like a standard pre-order traversal and then plus a little bit of check and then this swap here actually probably we don't have to swap it you know uh we can simply uh do a little bit of the tweak of the way we push into the stack so that we will not modify the original or root uh tree structure because you know for some of the interviewers maybe they said okay so can you convey not can you not modify the input right because here we are modifying that so for that case what can we do here we can simply uh just copy this one you know we can do it if and out right so it means that you know if the left one uh doesn't equal if this one doesn't match it means that we have to swap the left and right child but we if we don't swap it what we can do is we can just reverse this uh pre-order traversal right which means pre-order traversal right which means pre-order traversal right which means that we can simply do a left first right and then we do a right next so this one this is as if we are swapping the left and right child right and then we can just uh leave everything the same and in the house we continue that so if i run the code accept it yeah still works right um yeah cool i think that's pretty much everything i want to talk about for this problem and uh yeah thank you for watching this video guys and stay tuned see you guys soon bye
Flip Binary Tree To Match Preorder Traversal
shortest-bridge
You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree. Any node in the binary tree can be **flipped** by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: Flip the **smallest** number of nodes so that the **pre-order traversal** of the tree **matches** `voyage`. Return _a list of the values of all **flipped** nodes. You may return the answer in **any order**. If it is **impossible** to flip the nodes in the tree to make the pre-order traversal match_ `voyage`_, return the list_ `[-1]`. **Example 1:** **Input:** root = \[1,2\], voyage = \[2,1\] **Output:** \[-1\] **Explanation:** It is impossible to flip the nodes such that the pre-order traversal matches voyage. **Example 2:** **Input:** root = \[1,2,3\], voyage = \[1,3,2\] **Output:** \[1\] **Explanation:** Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage. **Example 3:** **Input:** root = \[1,2,3\], voyage = \[1,2,3\] **Output:** \[\] **Explanation:** The tree's pre-order traversal already matches voyage, so no nodes need to be flipped. **Constraints:** * The number of nodes in the tree is `n`. * `n == voyage.length` * `1 <= n <= 100` * `1 <= Node.val, voyage[i] <= n` * All the values in the tree are **unique**. * All the values in `voyage` are **unique**.
null
Array,Depth-First Search,Breadth-First Search,Matrix
Medium
null
168
hello in this video we are going to discuss the lead code problem number 168 Excel sheet column title in this problem they will give you a number right they will give you a number like what this they will give you and number you need to return the Excel sheets column title right for example yeah Excel sheet is like this right a one then they said up to the e z is that this is what twenty six then a will come right a that is twenty seven up to what the a series go a is that a e z in which number 52 then what will come b a right the series will like this be a 53 every 26 numbers it will change right 1 to 26 then 27 to 52 this is a is constant but the second one is a two is z right 27 for 28 what is this a b right a b this is twenty eight they will give you this number right 28 you need to return the column title like this a b how we can return this first yeah I create the empty string right I will create a string to return our return type is string like this a b like this so we need to return as thing so at the initial stage I create an empty string right empty thing I will create this then I simply I know this number right I go for the modulus of what 26 because every 26 the column will change right up to 26 it is single here to is that after that a b a c a i d is 27 to 58 so I just take modulus 26 modulus sorry 28 model is 26 is what this is the given number right this is given number you can assume that n percentage 26 is what two what is 2 in the table a equal to 1 b equal to 2 so I put B here now I just 28 divided by 26. another mathematical operation these two operations are very important first I take modulus then I divide that number 28 by 26 is what 1. now our number is what 1 so this operation is completed now we have B right after the modulus we get B now our number is what our n is 1 right we just divide by 26 to get the new variant right already we have n we just divide so we get another n now we have one ah do this operation repeatedly now we have n equal to one percentage 26 is what just check I will run yeah if I give one yeah the percentage value is 1 right T modulus of twenty six one the same way we will check for what 28 the modulus is 2 the newer n is what 1 right T this is for just example this is not actual problem I just first ah run the problem right run the what is logic wait a second now we have one so when we take modulus what it will return one okay now the modulus value is now the N is 1 percentage twenty six is one so in the table only is allocated to a so I put a over here now our answer is come now we just go for the new n 1 by 26 is what simply zero if the N will get 0 we are get we are done right we get our solution okay now I move to the coding part then you can easily understand what here I create an empty string Str this is m d string for the return purpose so I just say return Str right our returning is over now y I run a loop have ah which condition column number greater than zero if column number if our n will become 0 the loop get dominated we will get our answer now what is that Str we have I just column number we have column number I just take the modulus of 26 right 26 then added to the string right string it will add then I need to want I need to update the column number how by simply column number divided by 26. now I just update this is what if you think it is 28 percentage 26 what it will return integer okay but we are concatenate with the string here also this string type so you need to change this number to character for this purpose I simply add a character to each you know that a I simply added this for the safety purpose we can what you can type cast to this I simply added this character what is the ski value of a it is 65 you don't need to confuse that for here a is what just 1 right here value one you have the answer right plus 1 for the purpose of converting integer to character right it is it will give sorry we will it will give you an integer you need to concatenate the previous string so you need to convert this into character for that purpose I added a over here a has value of 1 so if we run this we will get what if here one means they will give you need to return a but if you run this by this code you will get B right because you add one voluntarily for another purpose but you added right so you will get B you need to you add one so you need to decrement one by every iteration that will solve your problem I just run the code sorry n is not there right column index column number sorry for that run it will give you the right answer so I just submit yeah it is running successfully thank you for watching
Excel Sheet Column Title
excel-sheet-column-title
Given an integer `columnNumber`, return _its corresponding column title as it appears in an Excel sheet_. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... **Example 1:** **Input:** columnNumber = 1 **Output:** "A " **Example 2:** **Input:** columnNumber = 28 **Output:** "AB " **Example 3:** **Input:** columnNumber = 701 **Output:** "ZY " **Constraints:** * `1 <= columnNumber <= 231 - 1`
null
Math,String
Easy
171,2304
1,405
everyone welcome back and let's write some more neat code today so today let's solve the problem longest happy string a string s is defined as being happy if it follows uh if it satisfies the following conditions it has to be made up of only a b and c characters it cannot contain three consecutive a's three consecutive b's or c's and it can have at most uh a certain number of a's a certain number of b's and a certain number of c's and those parameters actually are given to us in the input of this function so basically we're given three integers representing those counts and we want to return the longest possible happy string that we can build we're not given any string we actually have to build that ourselves and then return it the longest possible that we can make and there could be multiple happy strings that actually satisfy these conditions that are of the same maximum length and then if that's the case we can return any of them we don't have to build a certain one if it's not possible to do that to even build any string then we can just return an empty string and the first example is actually really helpful to even understand this problem so we're given one a one b and one or seven c's we don't have to use all of these characters but these are the characters we're given what's the longest possible string that we can build using these that satisfies these conditions now the real condition here is that we can't have three consecutive a's b's or c's right that's going to be the hard part now which character should we start with we could start with a lowercase a or a lowercase b but i think it's somewhat obvious that we probably want to be greedy here right if we have a bunch of sevens we should try to use these first rather than starting with the characters we have few of because remember we can only have two consecutive c so if we have a c and a c we can't you know we might not even be able to use all of these so we really need to save these a and b's to use them as like the in between right to reset it so if we put an a here then we can use two more c's and even after we use four c's now right we're down to three c's we have no a's so we still want to use as many c's as we can but we have to reset it so we have to put a b in between and then we're out of b's so now let's put two more c's c uh then we're left with a single c uh but we can't use that c anymore this is the longest string we could do uh is there a way that we could have rearranged this to make it even better well intuitively this is simple enough to see that we probably can't right we did as much as we could we put gaps where we could we maximized the number of c's and uh we were only able to use six of the c's but that's still pretty good that's the longest string we could have made now of course the a and the b could have been swapped right and it would have still been the same length and we could return that other string as well where a and b are swapped it doesn't really matter which one we return this is the longest that we could build and that's how we're going to do it now it's easy to over complicate the solution of this problem and that's actually the track that i went on when i first tried to solve it but it's actually more simple than you might think what we just went through is pretty much the solution where what we're gonna do is we're gonna always look at the most common character of the ones that we have right now and of course it's c so we're going to start with a c in our output so just to clean it up let's do it on the right side over here okay so we used a c now we're left with 6 c's now what do we do well once again let's look at which character is the most common again it's c so what we're going to do put another c here now we're left with 5. what are we going to do same exact thing c is the most common so we're going to put another c but wait a minute if we do that we're going to have three consecutive c's we can't do that so we're going to say well even though c is the most common we can't put a c here right we have to at least wait to put another character here so even though we know it's the most common let's find now the second most common character it could be either a or b let's just do a and then we'll be left with zero a's so let's just cross a out so we put a single a and then we continue our algorithm right now let's again find the most common character it's c now we can put a c here because we're going to look at the two previous characters before the two previous characters were both c that means we can't insert a new c but now the two previous characters are c and a so they're not both c so we can add another c so if we do that we're left with four c's now again c is the most common so we insert another c here and now again c is the most common but we see that the two previous characters are c so we can't do that so we're gonna insert the second most common the only other character here is b so uh we put the b here and then again the most the only character left now is c so we're going to add it at once add it twice but we can't add it the last time because the two previous characters are c and what we're going to say now is okay well what's the second most common well there are no other characters so we can't insert a c and we don't have any other characters so basically we pretty much ran out of characters so this is the longest we could do and this is what we're gonna return otherwise if we were able to add this last c then we would also stop because now we don't even have any characters left to continue building the string so in either case we're gonna stop like that so that's pretty much the algorithm actually but the question is how are we going to continuously find the minimum from the three characters that we had well we could actually do it a simple way we could literally just use a list it's only three values right like even if we had to sort it every single time sorting a list of three isn't gonna be very much three values is practically big o of one right it's a constant time operation no matter what since the size is only three but if we want to be more efficient we could use a heap and that's how i'm going to do it just because you know what if we had the exact same problem but instead of given three characters we were given 10 or 20 or 100 or even a variable amount then the heap is the technically better solution but you know using a heap adding and popping values from a heap especially if the heap is of size 3 is going to always be an o of 1 operation anyway but if you know we had n input values then the operation would be log n that's why we're using heaps because they're very efficient to find minimum and maximum values but in this case it doesn't really make a difference but the overall time complexity so in this case if we take each value push it to the heap pop it from the heap that's of size three each time it's gonna be an o of one operation but if we do it for every uh character that we're given right in this case the characters that we're given is basically the sum of all of these which is let's say n the overall time complexity is going to be big o of n pretty much i guess the space complexity is going to be big o of 1 unless you're counting the output string as extra memory so now let's code it up and we're going to first initialize our results and initialize our max heap because we always want to find the most common character the result is going to be an empty string so far the max heap is going to be an empty list because what we want to do to the max heap is go through every single character and its account pair so in this case so we have a b and c now and the first value is the count the second value is the character itself now the reason we have a negative here is python doesn't have max heaps by default but we can get around that by using negative values because by default it'll be a min heap but if we're popping a value and we're getting the minimum and the negative count is the minimum then we're actually getting the most common character by getting the negative count right and the reason we're even iterating through this and rather than just initializing the heap like this is because of one little edge case which is what if the count is equal to zero then we don't want to add it to our heap so if we have zero a's we don't want to add that to the heap but if it's not zero so in this case if it's not zero then we do want to add it to the heap then we'd say heap cue dot heap push to the max heap the pair of values count and the character let's move that to the next line so the reason we don't want to add one of the characters if it has a count of zero to the max heap is pretty much our solution that follows will kind of not work out and it would just be a little bit more annoying to implement it like that because we're gonna assume that anything that's on the max heap has a positive number of characters so if we add one that doesn't have any characters that's going to kind of screw up the rest of our solution so now we're going to iterate while the max heap is non-empty basically means that we do non-empty basically means that we do non-empty basically means that we do still have characters left we're going to always pop from the max heap the first value is the count the second is the character we're going to do heap q dot heap pop from the max heap of course what we want to do is now push this or add this character to the solution and then decrement the count by one but what if the two previous characters were the same so we have to check that so we're gonna have an if uh statement so basically first we have to make sure that the length of the result is greater than one meaning it's at least two values and that the previous two values we can get the previous value in python by taking negative one index uh and the second uh the second most recent value by taking the negative two index and if those are equal to the current character yeah it's kind of cool in python you can literally have a chained equals but if these are all equal to each other that means that this character was already added to previous times so now we're going to want to pop the second most frequent character but what if the second most frequent character doesn't exist so basically if the max heap is empty then well we can't really do anything right we have to return or in this case to make it a little bit cleaner i'm just going to break out of the while loop and then at the outside over here is where i'm actually going to return the result that's if we don't have the second most common character but if we do have the second most common character we're gonna get that so let's get count two char two uh from seikin heap q dot heap pop from our max heap and of course we're gonna add this character to the result it's the second most common character and then we're gonna decrement the count by one but remember the count in this case is actually negative right we added it as a negative value so instead of decrementing it we're actually going to increment it by one until it's equal to zero now the question is do we still have any occurrences of this character left if we do we should push it back to the heap if we don't then we don't push it back to the heap so we're going to say if count two is non-zero then we're going count two is non-zero then we're going count two is non-zero then we're going to do heap q dot heap push to the max heap this new pair of values which is count two and the uh character so the only thing that we updated was the count two this if statement was basically we couldn't add the most common character in the opposite case where we can add the most common character we're going to do exactly that we're going to uh to our results we're going to add that character we're going to increment its count by one instead of decrementing it and we're also going to want to push it to the heap right heap q dot heap push but we don't want to push it unless the count is non-zero right it unless the count is non-zero right it unless the count is non-zero right but also do we want to push it in this else case we should probably do that outside of the else case because we popped the value and we definitely want to add it back we didn't add it back here and we basically want to add it back regardless of which of these if else executes so let's add it out here so basically if the count is not zero then we're gonna do heap q dot heap push to the max heap this pair of values count and char so what's either gonna happen is we're gonna go through uh these add as many you know we're being greedy here we're adding the most common characters uh first and we're trying to add as many as we can either what's gonna happen is we're gonna add all the characters we possibly have to the point that our maxi becomes empty it'll become empty because the count of every character will have reached zero and then we won't be pushing them back onto the heap so then our heap will be empty and we're going to end up returning out here or we're not able to use every character but at the same time we only have a single character left now right we have the most common character but we don't have any secondary characters so we can't add any more characters so then we break here and then we return outside of the loop anyway so that's the entire code let's make sure that it works by running it and as you can see on the left yes it does and it's pretty efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Longest Happy String
all-people-report-to-the-given-manager
A string `s` is called **happy** if it satisfies the following conditions: * `s` only contains the letters `'a'`, `'b'`, and `'c'`. * `s` does not contain any of `"aaa "`, `"bbb "`, or `"ccc "` as a substring. * `s` contains **at most** `a` occurrences of the letter `'a'`. * `s` contains **at most** `b` occurrences of the letter `'b'`. * `s` contains **at most** `c` occurrences of the letter `'c'`. Given three integers `a`, `b`, and `c`, return _the **longest possible happy** string_. If there are multiple longest happy strings, return _any of them_. If there is no such string, return _the empty string_ `" "`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** a = 1, b = 1, c = 7 **Output:** "ccaccbcc " **Explanation:** "ccbccacc " would also be a correct answer. **Example 2:** **Input:** a = 7, b = 1, c = 0 **Output:** "aabaa " **Explanation:** It is the only correct answer in this case. **Constraints:** * `0 <= a, b, c <= 100` * `a + b + c > 0`
null
Database
Medium
null
100
hi my name is david today we're going to do number 100 same tree this is an easy level problem on lead code i want to solve it in javascript so we're giving the roots of two pi binary trees p and q here and here's the binary tree function and we want to see if they're identical or not so we can look at this example one and one is identical two and two is identical three and three is identical so we're able to see that the nodes are the same and also they're structurally the same as well so this on the right side doesn't have any extra nodes that doesn't that aren't represented on the left side so to solve this strap problem we can use a recursive approach and we can think of what will make this false so it will be false if the values are not the same and also if one of the sides has a value has a node but the other one doesn't have an o it's null so and if it doesn't hit any of the false cases we return true and if we iterate through the entire tree we'll get to null and then if both of the sides or both of the trees and all it's true so that would be part of the recursion so the first part of it is that if both p and q are both null so if p and q are both null we return true so none of the cases to make it false happens and we iterate it through the entire tree we return true so now we have to think of what will make it false so if so there will be three different cases so if p is null well q has a value we return false so if p is no well q isn't or all the way around q is null well p isn't or there's one more case and that'll be when the values are not the same we return false and then we call so we have to call each of these functions so return is same tree and we have to call it both on the left side and the right side recursively so 3 left for both and this same tree right we're both so we can do an and here so because we only need one of these to be false to make the entire thing false so and if it doesn't hit either of the falses we return true so let's look at our base case if p is equal to null and q is equal to null return true now we have to look at the reasons to make it false so there's three different ones so we have the inner parentheses here so if p is equal to null and q isn't equal to null or now we do the opposite p is not equal to null and q is equal to null or the values are not the same p dot vowel does not equal to q dot val return false and next we have to call this function recursively so return is same tree for the left side so we up and it takes both of them so p dot left comma q dot left and is seam tree p dot right and then q dot right great so that's it for this one so the time and space complexity we are iterating through the entire tree at the worst case both of them so it's going to be o of n plus m and then the space complexity or actually the lower the it will be the least amount of it so and then the space complexity will be also of n and n here where n is the shortest number of nodes between q and p because we're only going to iterate to the shortest one and then if the other one has longer more nodes we return false so we don't have to iterate through the rest of them and that's how you solve this one thank you so much
Same Tree
same-tree
Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. **Example 1:** **Input:** p = \[1,2,3\], q = \[1,2,3\] **Output:** true **Example 2:** **Input:** p = \[1,2\], q = \[1,null,2\] **Output:** false **Example 3:** **Input:** p = \[1,2,1\], q = \[1,1,2\] **Output:** false **Constraints:** * The number of nodes in both trees is in the range `[0, 100]`. * `-104 <= Node.val <= 104`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
307
Hello friends to Jhal Ajay, once again welcome all of you to my YouTube channel Tehri, so what is the question of the list in today's video, Rains is our problem of the day. In today's question, a little towards the concept segment. If you watch the complete video then you will understand the concept but please do like and subscribe button so that I keep getting motivation and you guys get such amazing content. So let's start with the question. So what is the question saying? Given in interior. In that handle multiple images of the following types update the value of elements and calculate the sum of elements of numbers between left and right improve where left so call them Tubelight so now this question I take it 1234 now what do I mean Jyoti 0123 for So where will the light value come from? Request 202 Dar 's value will be electronic waste. 's value will be electronic waste. 's value will be electronic waste. So tell me everything in between this range, like example, if the value is zero, Dadi RKVYA Sridevi, then zero to three means this entire survey work of this entire inch. If you tell everything about the entire range, then what time will its complete time be? Similarly, if the value of Maalu is given than the value of vande di art, then one se thi means two, three, four. If I want the sum of these three, then it should be the time of these days. If it will go or will not go then this means I have to do it. Now looking at the question, it is a traditional question which is a traffic jam approach to solve, in which we have to understand according to the range, then that too could have been written in it, but the updation which is happening in it. Nor will he have any problem in that, how like I apply prefix American approach at home, if I make it in the exam, then the professor will be with me, the former minister of 1 and 360 feet time has passed, now the item moment is done for the face if it is done with me. So I am fine, I mean, we can subscribe from here till here and this one also does it, then it will be available to me, but I do n't know what is the problem with us, that you too will have it, like if 1234 Initially, I would have kept my training as something like this: 136 my training as something like this: 136 my training as something like this: 136 If suppose I have any value change, then how do you remove my and write five. In that case, you complete this training from here till here. There is going to be a change, so what will I have now, for that, for every updation, I will have to update one more thing, that will increase the time complexity of the rest of my professors, hence there is a better approach, how most of the same is there in such cassettes, it also gives you a career. If there is an update in the career, then to pass it fast, we use that of the Secretary or from now on the commentary. From now on, the complete detail analysis of the commentary will not be possible in this video because the video will be very long. But it will increase so much that there will be a go through as to how the segment is working and how we are relating to it. The question is that if you want the complete video in this statement, then comment in the comment section, the complete video will come on it. So now we will start. Let's cement it, I give it some time to do the interest so that you will get ID like if I have a range, one is 1234, what did you say to me in the house that you have to read its segment, neither in the statement nor in the actual, every Doing a particular range has kept the values ​​towed. We use check entries values ​​towed. We use check entries for many functions other than free time. Now let's see how it is to become a secretary. Like, I make a segment criminal note. I don't feel like it in this note. This note is Malviya Inter Gaon, this is the next thriller, so this note will complete this entire morning from zero to K through, this is my favorite, this is debt and fat, I have placed my hand in this particular note which is zero. It will support all the time to drink from three. Okay, this is my favorite. Keeping this fat, I divide the one on the left side as the base, that is, the left side i.e. green, and side i.e. green, and side i.e. green, and divide the second one by the left, then here Hero Plus 3.2 is how much? Hero Plus 3.2 is how much? Hero Plus 3.2 is how much? Till 2107 I said on this note again that this mantra will support Kasam from zero but right yes Fali note which started from where, secondly it will support Kasam till Tuesday only, second means from this conduct till 30 A degree at the time it That unwanted seven intact swear similarly then after this I applied it once again and made the next note to which I said look zero plus 120 plus one divide into which interior division for division will happen then only zero will come so what is this life here zero From 0 to 8 such a range was formed that it became like this 121 Now there is 01 element so when we have come to the very base, we have placed the fields on the stomach and we have gone to the very bottom, then which top to bottom is this? The principle is that when the country reaches the bottom and only 20 elements are left, there you simply take Phulwani and give it because America has become a single element race of one, meaning the limit has been placed on the intact one. Which S2 is it now, which was the stomach then? What did you say, this Warriors French left side lieutenant will take an oath, the capital will keep this note of a knight, where did this note come from zero, then these two notes were added to a plus, the values can be checked to become a three, this particular is the consent tied with chains, similar. This note was also kept fat, when Zafar divided it also gave till where, 2012 soda single element came but it kept it ok, don't think that when it is ok, I kept it, here also single elements for taking Here also the single elementary and the fat of both the words is going on which contact is going then put the evening here how much is 437 and you can check this particular inch's complement is 30 and now the top free mode in the last chord How much time does it take to check dandruff? 1234 If you swear, then the segment itself is created like this. The record is made by making boiled calls and then the settings are kept for a Gotra. And let me tell you, some indexing in the segment is like this. Suppose the indices of this particular note are A ID then what will be the national of this particular note Tu Multiply ID How to multiply and e plus one to index plus one At this time but on the text this note is increased to * on the text this note is increased to * on the text this note is increased to * index A plus To that this problem is divided then flame I will take a little and this indexing for commentary from every house this is velvet you remember if this index is this particular note index is Ireland then its left yogi 220 plus one and its side Because 2018 plus two, we create such segments keeping this in mind, so first of all we do the work, now we have done this much work, first of all, Ram would code the statement in his court, how will the code be there, so come, I am not taking it today because Most of the time pimples and using java in points entry hence makes class 1st test positive entry Akshay What did I tell about the commentary if I make sugar where it will last for a decade the input is the size of how many numbers and notes go in the segment then we Na, how is this believed, this proof is bread that in the commentary, so many numbers of Vinod account holder notes, all this will remain, the entry in the job is confirmed, the size of winning the medal is for multiple ad, size of my size of hair, O A plus one, so many, its secretary. It should be made in every case, this is the rule, you can do it even today, that is, it is based on this only, if you lose 1 inch, then set your comment method or Adams' name with us here set your comment method or Adams' name with us here set your comment method or Adams' name with us here and cut it and make it in Unique for Multiple One Plus One Milan's management made it a thing in which all notes will remain thicker than notes. After reducing so much, now my biggest task will be to repair my secretary in Inside Ninth B. So what did I say, can it be put aside? To appear in the court, this salary account statement has to be made like an iron grinder, what is it doing on every note of ours, going on every note, this end to high 023 currency on the top note, the range has gone to the left here and there. If it goes to the left, every note is being enjoyed, so that's why what can we do, we have kept one point of calorie now, we will keep one point of Intex Coffee, as I told, the index of this note is Ireland, so for its left and its Bhima will have to shift the index for the night, so we have some yoga beam interest function, now first of all we sell our house and do this work just because when sister and sister will be equal like I showed in the example when by saving zero In the bottom test, only one note was making a difference, so in that case, what can you write on that particular track in the judgment cream, Airtel fitted the value of a single note, returned from here on segment recruitment, that now here we have reached the main house. What we have to do is to take out the meat, first the address of the meat is divided by two meats, now we have kept the fee as per the requirement that if left with wrong or right will go away, then what will we know for the electric, aye hi jaka your me log hi me kiya Will go in minute and index because I have the lieutenant's two in To * index plus two, index of taking right To * index plus two, index of taking right To * index plus two, index of taking right was told by Meena, current note index, if ID is to right to India plus two, it must have been made on both sides at the back, then what to do in the last, update the statement recorded to Krishna, what will be the DP on its left. Twin Toys Depression Plus 1 Minute Whose Height Wali Next Key Value 220 Plus Two Project With Both Two Notes But One Value Is Potato Also So What To Do In Comment In Kannada If This Sarcasm Is Two Then The Left One In Friend Values ​​Hey Vali Jitan Values ​​Hey Vali Jitan Values ​​Hey Vali Jitan Verizon Everyone has to store the evening so they did this and it is garden so many inside functions we have done now we dare to see the first query function will be done in the update bar by frying it will come to know that when we have alto So how did we take any extreme measure of the car, so let's see, first of all I do the centro which was made with me, first of all the note was tan and the range was from zero to three, on this side I had a Note, there was one person here, okay, here it was 020, eat, 0210 was two, so this will happen, after that, from here to where, so let's take the screen that it will happen here, from two to two and it is done here. 3 Sad on this earth, I correct it that it happened here and it was here, now here as well as here for in here Sherawat, now it should be known to me that NCR is now there will be eight such zones for that. What you have to do is this is what I have, my small, this case, this is my lower only pointers like it is also in the set, now it goes if it is h2r, then how can I do this, so see, I said if my which Low is if what is my low is greater noida request oo and have and what is my high is loosening and chhuare means completely overlapping do comparative vipin that means like it likes between zero to three add and so on or its total Meanwhile, in that case, by simply noting, I will return the same person. For example, if here comes zero to three, then it will simply be cancer. Ok, how is this complete overlapping, in which what has to be done, we should have checked this condition. That's our point A, which was av, which is bigger next, our ad, which is our high blood giving capital, means when it is complete, don't look at LG, I have made it like this, what have I said, it will be more like this, so it will be lighter or Equivalent to that, either like this or somewhere in between and it will be in the middle, but the question people are either coming in and will have maximum load, even then this outsider is not sent, this is also due to complete overlapping. In case she goes to St. Louis, most probably such outsider is not available. Even if she comes, she will return in this. This [ __ ] has the condition of complete overlapping of lips. On the This [ __ ] has the condition of complete overlapping of lips. On the This [ __ ] has the condition of complete overlapping of lips. On the basis of this, we submit it to us from here. This is complete overlap. Complete Overlap Now let's talk about when there is no complete overlap, there is no computer or laptop, as if we know that we are deprived, if we have complete overlap, then if the company will not develop exactly, then what will I do about it, because look here, it is fine with zero, otherwise I can't give it from the tanks, I should see it on Monday, in that case, what will I have to do, or in that case, will I have to make a left call, so how can I make a left call while riding, and after doing the middle, we will get another zero seven. But we will apply this, ask the guest and again by calling from zero in mind, we will check whether the range of Uber app is still not overlapped, we have done more, now we came here, so what happened to me in this case, like here. But if the soldiers of 101 are wanted, if they come into the case, then what was 101, has it become exactly equal, has it not been deprived, has it become exactly equal of 172? In that case, we said that we returned from here to Iyer because whoever had done whatever he wanted, we How to make it non-overlapping, how to make it we How to make it non-overlapping, how to make it we How to make it non-overlapping, how to make it zero, two plus zero, these two channels, when there was a case of complete overlapping of two to three channels, see, a case of complete overlapping of two to free came, then it was returned from here, 729, so we knew that If the time of the minister is not that then I simply say that after going on such a date, you have to remember 323 segments that in every problem, the segment is its used oil, if you heat any problem, then this is the criteria, its best, there is no other criteria. That criteria is first complete overlap. For complete overlap, I told you one condition which you have to remember. What is the condition? Remember that whatever your pen is, it should be of great think way bell i.e. Rose is, it should be of great think way bell i.e. Rose is, it should be of great think way bell i.e. Rose Mahal pendant which is your high voltage request allegation in that case computer and If you give whatever recent value is there in the judgment of laptop statement replay, then it is complete. Note, it is a matter of overlap. Whenever no one can overlap, it can be the company. Either your oil becomes bigger than R, that is. As if this was the growth of NCR and my buffalo is lying here, then it is completely out of the way, my NCR festival is going on here and the Range is going on, this is a completely novel pack, so in this case if the album today Is it bigger than or is it which is smaller than the people of elephants where being smaller than the districts means the range like NCR is here and is bigger than the people is here then in that case also there is absolutely no relation between these two. Is in that case Returns in incomplete doors If any case is made in Otherwise, what do we do We ask for the leftovers, which is where our eyelids come from Ali will keep such a deceased's capital Capital of adjectives and left index There is two internet access, there is one, we will take the right answer in A+, where will we like right cancer, the take the right answer in A+, where will we like right cancer, the take the right answer in A+, where will we like right cancer, the fist goes higher than the sky, the right key goes to Indore Express, I had told this in the set, so add these two. If you can do this then it will always come with three but how to remember this condition for complete overlap in the segment. If you write this condition for complete overlap discrimination towards world map in this condition spoil sport is the best update function of this then the update function has Bloody Mary function is this point this query why take interior because it will support so interior is what happened in the first one it will be hello capital one capital and one will be okay this is our small and one is our small high and one is our indexing first of all we do overlap What happens in case Coonoor lap, tell me now in Nobel application because if this increase my interest in Sector-86 or else increase my interest in Sector-86 or else increase my interest in Sector-86 or else half of my fun from the capital in that case return Jio phone because there is no point, today we will talk about it completely. Or five fruits, it is complete, by the way, if it is complete and gets up for the councilor, then what will happen in the double trap of the company, this scientist will become waste oil and your higher oil will become daily flight, activate this return commentary depending on it and drink the note directly. SK 50 laptop to be presented, where to return, take out in two very easy side plate, clay or media, nothing but help, luck only, divided by two to two, chapter alarm, set alarm, Captain Alastair will go, will get important in the function. In minutes it means that daily middle fat induction quintal plus one plus till the right side we will add to it any Amazon of the right side Amazon Me 112 that you our point will go towards Amazon Hello Hi and right intent to Indian Express to this we have That function is done, in this it is available in any segment by always remembering the three together. Now the update comes last. Now when the turn comes to update, let's see in that also, you will get one contact for update, which one will you get? Which next update to do next and whether to replace the valley. Neither update functions are found in similar phrases in the function of work. We will check this for our range meaning for index like first which note. She goes from zero to three. Now I take off the belt and it is made one. So I check that the index of Aamir is the middle pepper which is bigger than the mit. Can you make a small clay. If it is equal to the mit's holidays then tell us. Smaller than the meat. The area of ​​the left tell us. Smaller than the meat. The area of ​​the left tell us. Smaller than the meat. The area of ​​the left return from the meat likes in the left side and whatever further induction is from the meat, it does the light cream, that's all we will check that if our index is equal to the stomach, it's a small, then you are in the left side. Go in the night who will keep this stomach and then Akhilesh will update it. This is exactly the copy of this function, so I am copying it from here, I do this, I make some changes in it, I update it by changing the name of a question, plus in this first So it will not come, we will get American place, we will get one intact and one idiot, we will get value 21, we have to replace it with value, then when our base will go like in the video, then what do we have to do in that case, replace the value on centrifuge index, I don't think anything else. Don't tease anything, I took it out in the media, we will check that you have our index, if it is custom made on this day, then which side will I call the update, I will call the update on this side, for your left vision, you will have to update it here from the internet. Instead of this, what will have to be sent? Index will have to be taken and the value of valuation. Yes brother, everything is in sample boiled case or right with the update. This question is also put to me. This area has to be kept in complete trees in hair fall and tested. The index will go to the recipe and the ladies will go, after that we will have a value that will go up and do not call your two sons on Twitter and if you were busy in the matter that you will have to address then again I have given this complete information to us. Done Subscribe To complete this glass of mine, we delete an entry free in our class that after when we have character call, we will remove this from its object so update such and land how many told that name Short and DTH is gone and what to do in it, rubbing dot in shirt, entertain you, drink a yellow point because you have to delete it again and again, Kayal and Hee character mail told me that she will always be Jio and the value of Hee is said that Always the name start length is - is - is - that TTH minus one, it is with me, name toys minus one and half inch, so in a minute, let's see that the first input is patience, let us pass it to me, what is there in Bangalore, after Lokayukta, the court is our What is the pass, if there is index, then point So it is dot so what should I input? First of all the integer will go, after that the value will go. Which value is the confidence to be updated? What is the shape of my low, my high and my conducting neither centrifuge T-20 system to conducting neither centrifuge T-20 system to conducting neither centrifuge T-20 system to appear when Shyam wrote something inactive and the Last, when he asks for all this, do I have to return ? ? ? MP3 dot a very good very, what have I taken, if I go to very, capital, chapter saliva, capital will be the chapter of the house, only the chapter will be electrolyzed, after that the mail is my high. And minerals because the lower chairman is tricky, so this is also passed, now let's run it once, the suggestion was okay, what is the national insert, I need it, oh no, it is not the name, its name is submit, it is a good one, so you have come. Do you find any useful information about International Year and statement related to it, if you get any query, I will join you in the comment section and if you comment more, like and share this video more, then I am definitely centric above. I will make a complete lecture, see you tomorrow with another new video and another new question. Thank you Life1.
Range Sum Query - Mutable
range-sum-query-mutable
Given an integer array `nums`, handle multiple queries of the following types: 1. **Update** the value of an element in `nums`. 2. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initializes the object with the integer array `nums`. * `void update(int index, int val)` **Updates** the value of `nums[index]` to be `val`. * `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`). **Example 1:** **Input** \[ "NumArray ", "sumRange ", "update ", "sumRange "\] \[\[\[1, 3, 5\]\], \[0, 2\], \[1, 2\], \[0, 2\]\] **Output** \[null, 9, null, 8\] **Explanation** NumArray numArray = new NumArray(\[1, 3, 5\]); numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9 numArray.update(1, 2); // nums = \[1, 2, 5\] numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-100 <= nums[i] <= 100` * `0 <= index < nums.length` * `-100 <= val <= 100` * `0 <= left <= right < nums.length` * At most `3 * 104` calls will be made to `update` and `sumRange`.
null
Array,Design,Binary Indexed Tree,Segment Tree
Medium
303,308
56
hello guys welcome to algorithms made easy today we will be discussing the question merge intervals in this question we are given intervals array and we need to merge all the overlapping intervals and return an array of the non-overlapping intervals array of the non-overlapping intervals array of the non-overlapping intervals that cover all the intervals in the input so in the first example we can see that the given intervals are these there are two intervals one comma three and two comma six which are overlapping so we merge them into one which is one comma six and we return the output as follows let's see how the intervals get merged in the first example we are given this input and we need to check if any of the intervals are getting overlapped suppose we have a range from 1 to 18. now let's mark each of these interval given in the input so 1 comma 3 will be here then there will be 2 comma 6 and then the rest of the 2. we see that the interval 1 comma 3 and 2 comma 6 are getting overlapped over here so what we need to do is we need to merge these two into one interval which is one comma six why we are doing this we see that whenever there is a condition the start of the second interval is less than the end of the first interval in that scenario we need to merge it and this becomes our condition of merging the overlapping intervals so let's see how we can code this as we will be going sequentially from the start to the end of the interval we need to make the intervals as sorted with the start value so what we do is we'll sort the array first then we'll take a list for the result why we are taking a list is because we do not know the size of the final result at the very start we need to add the first interval into the list we'll also have a variable j which will point to the last value in the resultant list we'll then start our looping from the first position of the intervals we need to take the last interval which will be this now we need to write the condition that we talked about if the value of the start of the second is less than end value of the resulting array in that case the interval and value changes to the maximum of either the initial value or the end value of the second value if that is not the case we need to simply add this interval into the resulting array and increment the index j now we need to convert this list into a 2d array and we'll do this where the number of rows will be equal to j plus 1 we then loop and lastly we simply return the array let's run this code so we're getting the right result for this let's test it for the second input we forgot to take into consideration that the interval can be equal also so now it is giving the right result let's submit this code it got submitted the time complexity of this algorithm is of n log n because we are sorting the array and the space complexity is o of n thanks for watching the video see in the next one
Merge Intervals
merge-intervals
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_. **Example 1:** **Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\] **Output:** \[\[1,6\],\[8,10\],\[15,18\]\] **Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\]. **Example 2:** **Input:** intervals = \[\[1,4\],\[4,5\]\] **Output:** \[\[1,5\]\] **Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping. **Constraints:** * `1 <= intervals.length <= 104` * `intervals[i].length == 2` * `0 <= starti <= endi <= 104`
null
Array,Sorting
Medium
57,252,253,495,616,715,761,768,1028,2297,2319
118
in this video we'll be going over pascal's triangle so given a non-negative integer known so given a non-negative integer known so given a non-negative integer known rows generate the first numbers of pascal triangle so in this triangle we have an initial row of one and in each of the additional rows we have a one in the front and one and n and then the elements in the middle at the in the middle of the ones will be generated from the previous row so in this case we have a two here because we have one and one so we generated two and then in our next row we have initial of one and then our middle elements are generated through the previous row so it's one and two so we get three and two and one so we get three here so let's first go through the thought process so we'll be implementing a recursive approach for each of the row x we will first have our initial one at the front and at the end of the row so example we have one here of course with the exception of the base case we first then we will generate the row the previous row at x minus one then for each of the elements inside the previous row we will find the sum of the pairs and place the sum inside the current row so let's go over the pseudocode so let's validate the input parameter if num rows is equal to zero then we cannot generate any row so which is the return empty list and then implement a recursive approach to generate the triangle uh before that let's create a list results to keep track of the triangle and then what is what parameters do we need the num rows or we can say are the current rule and results list of overalls and then what's the base case if r is equal to one then we're just going to create a list with a value of one that's a base case so this base case and then add lists to results and then we're going to return this then each of the recursive call creates a create a list actually before that we're going to recursively find the list of the previous row the node as brief so it's r minus one so for example we're currently at this row we're going to find the previous row first and then create a list current to keep track of the values of the current row and i'm going to append our initial 1 to current and i'm going to iterate through the indices from 1 to end of brief which will denote as i so we're gonna append proof dot get i minus one proof dot get i miss one plus proof dot get i so find the sum of the pairs to current and then we're going to append the last one to current and i'm going to add current to resulting list and then we're going to return current and after we process all of the rows we're going to return the results and return resulting list now let's go over to time and space complexity so it's time complexity is go to of n times n plus 1 and then divided by 2. so it's equal to of n squared where n is the number of rows or the input value we generate a total of this many cells so basically keeping track of all the cells and our space complexity is also equal to this plus both n so let's go to of n squared and then where n is the number of rows and then this is the resulting list result list and then of n is the recursive call stack memory now let's go over the code so let's validate the input parameter if num rows is equal to zero then recur return an empty list and create a list to hold all the rows results implement the recursive approach to generate all of the rows and then we can return result after implement the recursive approach to generate the of the rows and are the current row also the list to keep track of all the rows and then what's the base case if r is go to one then we're going to create a new list with just a value of one then currents.add one then currents.add one then currents.add one and the results.add current and the results.add current and the results.add current and then we're going to return the current list and move this outside here if it's not equal to 1 we're going to generate the previous row first cursively generate the previous row and we're going to append one to current so we can move this out now and want to current iterator for indices we're going to find all the pairs the sum of the pairs from the previous row currents dot add the sum of the pair i minus one plus proof.get proof.get proof.get i and then append the last one at one and then add the current list to results and then we'll return current let me know if you have any questions in the comment section below
Pascal's Triangle
pascals-triangle
Given an integer `numRows`, return the first numRows of **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** numRows = 5 **Output:** \[\[1\],\[1,1\],\[1,2,1\],\[1,3,3,1\],\[1,4,6,4,1\]\] **Example 2:** **Input:** numRows = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= numRows <= 30`
null
Array,Dynamic Programming
Easy
119
231
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 power of two so in this question we are given an integer n and we have to return true if it is a power of true else we have to return false so the return type is a Boolean so this is the condition we have to check that n will be given to us and we have to find if x which belongs to whole numbers starting from 0 1 2 and so on and if this condition satisfies n is power of two so we return true now let's see how we can solve this question so instead of looping through all the integers and checking if it is matching through the input num let's represent the decimal number given in its binary format so this is the standard code right so if initially num is equal to 1 and if num is equal to 16 if num is equal to 3 and let's take other numbers if num is equal to 12 and if num is equal to 23 so let's start with one so we have to set the bits so here it is one and everything else is zero and for 16 this bit will be set to one and everything is zero for three the first two bits will be set to one and everything is zero and for 12 8 and 4 will be set and everything else is zero and for 23 16 4 1 and two will be set and everything else is zero and out of all this what are the powers of two only 16 and 1 are powers of two because this can be written as 2^ 0 and this can be written as 2^ 0 and this can be written as 2^ 0 and this can be written as 2^ 4 and all the others be written as 2^ 4 and all the others be written as 2^ 4 and all the others are not powers of two in the right answers you can see that only one bit is set as Power of Two And in non powers of two there are more than one bit set as ones so it means so we have to check in its binary format if only one bit is set to one in this case two bits are set this is greater than one so this is not a power of two here also two bits are set which is greater than one so it is not a power of two here four bits are set which is greater than the one so it's not a power of two only if it is equal to 1 it's a power of two and obviously negative numbers so if uh num is equal to -3 or if num is equal to Z is equal to -3 or if num is equal to Z is equal to -3 or if num is equal to Z these are obviously not powers of two so we check if n is less than or equal to Z then we can directly return false in the beginning as these are not powers of Two And in the next time onwards we count the number of one bit set if it is equal to 1 then we return true if it is greater than one then we return false now let's take a look at the code so here as you can see first we are checking if it is a zero or negative number if that is the case return false and now I'm using integer. bit count and giving the input n this will give us number of ones present in binary format and I'm storing it inside a variable count and if this variable is equal to 1 then we are returning true if it is greater than 1 then we are returning false for 16 it will have count equal to 1 so it will return true for three it will have count equal to two which is greater than one so it will return false so those are the expected outputs here so the time complexity of this approach is of one and the space complexity is also off one that's it guys thank you for watching and I'll see you in the next video
Power of Two
power-of-two
Given an integer `n`, return _`true` if it is a power of two. Otherwise, return `false`_. An integer `n` is a power of two, if there exists an integer `x` such that `n == 2x`. **Example 1:** **Input:** n = 1 **Output:** true **Explanation:** 20 = 1 **Example 2:** **Input:** n = 16 **Output:** true **Explanation:** 24 = 16 **Example 3:** **Input:** n = 3 **Output:** false **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Bit Manipulation,Recursion
Easy
191,326,342
1,647
hey everybody this is larry this is me going with q2 of the weekly contest to 14. minimum deletions to make out this frequency unique so this one requires a little bit of thinking and also a little bit of just thinking about the complexion of the problem so for me it turns out that how i solved it was just using greedy and you know greedy is a really you know whatever term so you have to think of a way you know a lot of different greedy algorithms that's what i'm saying and you could easily stumble into the wrong one so what i did is first i look at the collections of um i yeah i look at the collections uh um so i count for each character i count the number of appearance in that counter right and then i put in values and then i sort it so it doesn't actually matter uh and after i sort it so basically you're going to get oops you're going to get some counts i'm going to uh i'm going to show this here for the test cases for example so yeah so you have these counts that you can do stuff with right and the thing to notice is that why does greedy work and it's not even greedy in a way it's just you can as long as you can make a change you should make a change and then that would be good and that's the kind of greedy that you can implement that in different ways and why is why does that why is that good right i could i'll go over that in a second that's a good example so for example if you have this array um well you notice that the three are different right so you let's change it to two right okay and twos are the same so we have to change one of the two so it's one two three so that's two moves right another path if you think about it is two three and you go okay i know that i need to do it so let's change the two to the one and then change the one to a two oh sorry change to three to two right also two moves so i would argue that no matter what you do um what you do you're gonna get the same number of moves and that's the way to solve this problem that observation maybe you could guess it uh and the proof is around that when you remove one of the threes for example and you know you're forced to do it right because otherwise you know you um you're forced to do it because otherwise you did you know the invariant is not true which means that uh you the character frequency has to be unique right and if you don't do this then it will never be unique so you have to do it to one of them right and then that you get this and you could do it by um induction or whatever and in this case you also need to change one of the twos but the key thing to notice here is that coming from here going to here it doesn't matter which twos you change it to so as long as you change it to two once that will be good enough and then well okay so let's say that you know let's say we're convinced that gives us the good answer the second thing to notice is oh wow n is equal or n could be as long as 10 to the fifth so what is the complexity can this be too long well the thing is that i mean i even sorted it though actually it doesn't really matter you don't even need to sort it to be honest so let's we could just ignore the sword for now um but let's say we have a value of the frequencies right so this is all of n because we have to look at each character at least once to generate the table but also you just have to look at each character once no matter what algorithm you use otherwise you're gonna miss some characters uh because there's no structure to it right like you know so but after this well what happens after this right well count is an array of at most 26 characters one for each letters of the alphabet right so actually what happens is that in the worst case scenario you have 26 uh and you could go backwards right what's the worst case scenario for two characters right it's gonna be two what's the worst case scenario for three characters three right uh what's the worst case scenario for four characters well four right and so forth dot all the way to 26.26 right way to 26.26 right way to 26.26 right so and you know and you could kind of do the math i'm going to tell you the math which is that in one in 25 steps you can make this 126 and then 25 25s right dot 25 so that takes 25 steps and then 24 steps and then 23 steps and then so forth so that means that in the worst case this is going to take 1 plus 2 plus 3 plus 4 plus dot plus 26 steps which is equal to roughly 26 squared i mean you could do 26 choose 2 or whatever or 26 plus 1 times 26 plus uh 26 times 26 plus 1 over 2. 26 times 27 over two right n times n plus one over two so you can definitely do that to do the math but i'm just giving you a you know a big o notation right and as you can see this is the worst case scenario so that is always going to give you a good enough answer and what's the complexity of this if you want to have to put it in concrete big old terms well this is of n this is o of alpha squared so that means that this entire algorithm is going to be o of n plus our first square where alpha is the number of alphabets uh or letters in the alphabets and i don't and just to go over my code really quickly i just use a set to keep track of um whether a frequency is used so that like for example if we already used 26 don't use it we have to keep on decrementing until we find a good one and as long as we find a good one it's okay so that's basically what i did total zero uh if for each of the counts we and it's bigger than zero because if once we get the zero we fold away so that's a key thing to make sure you don't get a silly mistake on is that rev zero means that the character doesn't have a frequency so it doesn't even count so as soon as you do that you just increment by total and then you add it to the set at the end and then uh and then just return the total so that's all i have for this problem it's a long explanation for something that a lot of people priced up very quickly at the moment about 1500 people saw this uh let me know what you think hit the like button hit the subscribe and join me on discord and you can watch me solve it live during the contest next uh that was annoying when and i watched it so not great contest already uh i mean it was annoying but not that annoying okay frequency what's the frequency okay hmm eight 3282 um hmm yeah okay x isn't s and x oh ah thanks for watching everybody remember to hit the like button hit the subscriber and join me on discord and we'll chat about stuff later bye
Minimum Deletions to Make Character Frequencies Unique
can-convert-string-in-k-moves
A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**. Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._ The **frequency** of a character in a string is the number of times it appears in the string. For example, in the string `"aab "`, the **frequency** of `'a'` is `2`, while the **frequency** of `'b'` is `1`. **Example 1:** **Input:** s = "aab " **Output:** 0 **Explanation:** `s` is already good. **Example 2:** **Input:** s = "aaabbbcc " **Output:** 2 **Explanation:** You can delete two 'b's resulting in the good string "aaabcc ". Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc ". **Example 3:** **Input:** s = "ceabaacb " **Output:** 2 **Explanation:** You can delete both 'c's resulting in the good string "eabaab ". Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored). **Constraints:** * `1 <= s.length <= 105` * `s` contains only lowercase English letters.
Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26.
Hash Table,String
Medium
null
312
A Quiet Guys Welcome To Our Channel Code With Honey And Like Pyaar Dard Ko Statistics And Channel You Can Easily Noticed A Towering Back Again After Few Months Kepler Two And Three Qualities So Also Like It Notice The Day Is Relatives January First So And This Is The Meaning of the name It is soft for wishing everyone a very happy new year and wish you all the best to depend very easy to wrong answers from problems and also a restrictive channel lotus posted som quality post graduate subscribe like share and subscribe more comments Section Reveal 100 Without Wasting Time Let's Start With Heart Problem Life Is Problem Yes-Yes OK Yes-Yes OK Yes-Yes OK Subscribe Like [ Subscribe Like [ Subscribe Like Subscribe And Tours Click Here To Subscribe To The Amazing Subscribe Room Number Best All The Best And It's A The guy who stopped in more this point to the multiply subscribe and subscribe the multiplication subscribe and subscribe to subscribe our that then explain the examples 151 like putting that like what is the activated maximum number of jobs for peon in Lutyens take two My Videos For Watching My Video Lutb School subscribe and subscribe the Channel Please subscribe and ok thank you will be n 102 ok i did n't like in 250 words page ko more than 120 and evil 5 the time limit office problem subscribe and subscribe our YouTube Channel and subscribe the Channel subscribe And subscribe The Amazing to subscribe to problem electronic bulb example subscribe to ok plate me pickup da wa na example ok to itel it1508 padhare 1582 subscribe The Channel Please subscribe and subscribe the Video then subscribe to the Page if you liked The Video plz subscribe button Bluetooth English Person Candidate for Aid to Improve Modified in What is my new modified Video [ Video [ Video Subscribe subscribe to subscribe and subscribe Subscribe subscribe करे Ki Bigg Boss Yeh Still Not Post Any Objection Ok So Like Share And Subscribe Jaro Subscribe Into Into Into Doing A Guy Guy Guy ] ] Miding In The Monitor [ Monitor [ Monitor Total Subscribe Total Number Padharo This Is Not Always Know This Is Not Fair subscribe and subscribe the Channel subscribe kare subscribe kare subscribe kare subscribe to subscribe Subscribe * * * * * * 528 Other Looters subscribe and subscribe the Channel Please subscribe and subscribe the Channel Kishore Dynamic 110 Improvement Best Website for the Problem Maximizing Subscribe by clicking on subscribe button that China Multiplication Ready Different Awadhesh Matrix Subscribe to Multiplication Video Channel YouTube School Subscribe 158 Ok So Entertain Religious Loot-Loot-Loot-Loot for Crops Where is the Matrix and Chronic Maximum Maximum Number Off Kar Do That You Will Get If You Consider A Comment The Record Date Segment I Tujhe O That Think You Can Not Inform Se In Day Time Talking OTP Of 023 But Not Falling 1002 Talking Subscribe Like And Subscribe Like Subscribe 21 Subscribe 10 Kundan Likesji All Ki Nau Consider Tak Ki Sequence Posting Ko Balloon Right Nau To Aaya Sabse Zordu Talking About These Festivals Ko The The The Effective Best Smile On Ur Right Nau You Can See Date - 18-10-2012 12512 8 Nau You Can See Date - 18-10-2012 12512 8 Nau You Can See Date - 18-10-2012 12512 8 And The Boys subscribe to the Page if you liked The Video then subscribe to the [ [ [ Praise] Video then subscribe to [Praise] the Page How to Win * A Difficult Difference Touch dead after How to Win * A Difficult Difference Touch dead after How to Win * A Difficult Difference Touch dead after submitting a in this is used as a man can get the answer will get the maximum number of points in one cannot understand english play list play sakte ho to woh time talking about this like position erring 315 and avoid eating Every Day and a Total Time Video then subscribe to the Page The The The First Everyone Segment Abhirli Dushman Everyone Sid 100 [ 100 [ 100 Subscribe Button Dab School of the Match Subscribe To Ki Cricketers Ne Paper Cut Jo First Feeling Hit The Values ​​from like dushman Feeling Hit The Values ​​from like dushman Feeling Hit The Values ​​from like dushman dat do subscribe my channel ko subscribe ka haq hai to effect talking about ₹2 length and effect talking about ₹2 length and effect talking about ₹2 length and statement to the Page if you liked The Video then subscribe to subscribe and subscribe the Video then subscribe to Who is the Last Balloon I Just Stand [ Just Stand [ Just Stand That's a Comment on IG Were Kept Going to Vitamin NGO's Swine Flu Video subscribe The Channel Element The subscribe and subscribe the Products in Study * Study * Study * You Can Withdraw Subscribe Sleep Segment IPL Activists subscribe and subscribe And subscribe The Amazing subscribe The Channel Please subscribe [ subscribe [ subscribe and and and subscribe the Channel and subscribe the Video then subscribe to subscribe Pan Operations To Consider Maximum Number Oil Tube Skin Subscribe Will Always With You When You Will Love You All Subscribe To That Aaj Multiply Apps Laxman Ko Ok And You Can Easily Get Plus You Need To Consider All The Best But What Is The Maximum Volume Kar This Treatment Like And Subscribe Lutb Always Does Not Considering [संगीत] 125 subscribe and subscribe the Channel and subscribe Hoon To Aayi Gais Tempered Glass Toot Fact Weather Report In The Department Chief Leather Belt subscribe The Channel and [संगीत Leather Belt subscribe The Channel and [संगीत Leather Belt subscribe The Channel and [संगीत ] [संगीत] [संगीत] [संगीत] subscribe the Video then subscribe to the Page if you liked The Video then [संगीत] क्विद वृद्ध हुई अब्टूल वालू लुट्ब स्कूलिड कंटेंटन एंड क्विद वृद्ध हुई अब्टूल वालू लुट्ब स्कूलिड कंटेंटन एंड क्विद वृद्ध हुई अब्टूल वालू लुट्ब स्कूलिड कंटेंटन एंड कैंडेट एक इस टेट बे कैंडेट एक इस टेट बे कैंडेट एक इस टेट बे वेस्टेड इंटर्स और हैं है आर है क्या है करें विचार विशेष वेस्टेड इंटर्स और हैं है आर है क्या है करें विचार विशेष राधे राधे करें करें राधे राधे करें करें और subscribe to the Page if you liked The Video then subscribe to the Page if you liked The Video then subscribe to subscribe our Coldplay One to Three Liye Char to Paanch Subscribe Last Video subscribe and subscribe the Channel Please subscribe subscribe subscribe and subscribe the Channel Quintal Subha t-20 Daughters From Quintal Subha t-20 Daughters From Quintal Subha t-20 Daughters From 0 Like Comment Subscribe To
Burst Balloons
burst-balloons
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons. If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, then treat it as if there is a balloon with a `1` painted on it. Return _the maximum coins you can collect by bursting the balloons wisely_. **Example 1:** **Input:** nums = \[3,1,5,8\] **Output:** 167 **Explanation:** nums = \[3,1,5,8\] --> \[3,5,8\] --> \[3,8\] --> \[8\] --> \[\] coins = 3\*1\*5 + 3\*5\*8 + 1\*3\*8 + 1\*8\*1 = 167 **Example 2:** **Input:** nums = \[1,5\] **Output:** 10 **Constraints:** * `n == nums.length` * `1 <= n <= 300` * `0 <= nums[i] <= 100`
null
Array,Dynamic Programming
Hard
1042
318
hello YouTube this is another nickel problem called maximum product of long lenses keeping a screen or rewards find the maximum value of lens for both I multiply Lanza was Jay where are the two Bertino sheis common errors which means that there is no common arrows between the three words you may assume that were working keone no cases matters if no such were between zero so this example what to maximum last you 16 okay so let's do that if words is no playing zero in this case we return otherwise we lose the words ring flash class first it was the tubers needs to shear the torturer do not share any letters so which means that we can add character feel feeling failover letters into Sam we need this function so we pasted in this matter of a Douglas we add all the letters of bird into a hash tag so with s that we can check the following screens if for a particular screen they have the letter in the hostel Allah so here we are hashtag hirato and we look this world length I taught math as that words of kale I then brackets and between this edge set so here we get a sad ratio or we just feel keep it functioning what's the high and with this setup we check if the students after I that any word they have the same character that we have stored in this hashtag I plus 1j left for plenty of math we need a function to true or false if world call care we passing I stand here as that and we also pass a string here which means that we loop the word length I prefer if hashtag contains any word character which means there are common there was danger of those we just return false otherwise we can chew so here we need Co dysfunction his bald head assailant if world does not have a sentence with the hashtag about and with Verde J which means that we found two screens that they do not share common or she understand characters in this way we need next name variable so max names equal to mass top bags we can give initial a 2-0 my name's that words I initial a 2-0 my name's that words I initial a 2-0 my name's that words I taught length x words j to plants I think that should work finally we return the max next that doesn't work out put 24 should be six round we just add it here and if hashtag contends that oh sure we returned shoe here leave some for us we'll run code again the work to submit okay yeah that worked let me know if you have better to listen 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,689
hey everyone today we're doing leak coat Challenge number 1689 called partitioning into minimum number of deci binary numbers so in this challenge it tells us that a decimal number is called decibinary if each of its digits are either 0 or 1 without any leading zeros for example the numbers 101 and 1100 are decibinary well 112 and 3001 are not so given a string n that represents a positive decimal integer return the minimum number of positive decibinary numbers needed so that they sum up to n so if we look at the first example here the number 32 we would need three numbers to add up to 32 10 11 and 11. for the next example if it's this number right here 82 734 you need eight and uh really it seems kind of complicated at first if you're thinking about all these possible permutations of how you could add up to the number um but what you can think about is if the only numbers we're using to add up to each digit in the ones place in the tens place and the hundreds place are ones or zeros uh all we really need to do to solve this is figure out what our largest digit is and that's going to set the minimum number of decibinary numbers that you would need to add up to it so for example in this one example two eight is the largest digit of all of these numbers so it's a minimum of eight numbers needed to add up to that because that would be eight ones or in this example we have a nine right here so we would need a minimum of nine numbers so once we kind of understand that it's actually not too difficult to code this out so I'm going to create a variable called the max digit and we'll just set that equal to zero and we're just going to use this to keep track of our largest digit as we iterate through the input string so we'll set up our iteration here like I equals zero I less than n dot length I plus all right so in here we want to look at each digit and check to see if it's larger than the max digit that we've seen before so we're going to set max digit equal to math.max of either the current Max digit math.max of either the current Max digit math.max of either the current Max digit or number of n at the index at I and remember we do need to cast this into a number because this is passed to us in the form of a string in the function and then we should be able to Simply return the max digit at the end of this for Loop this should have found the largest digit in the number so let's see if that's working it looks like we're passing all the test cases there so that should be a valid solution and hopefully that makes sense this problem seems kind of complicated at first when you read it but once you know that we're really just looking for the largest digit in the number it's fairly straightforward to solve hope this video was helpful
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
943
hey what's up guys uh this is chung here again so this time today's daily challenge problem number 943 find the shortest super stream so this one is a pretty hard problem to be honest okay so you know this description is surprisingly short actually you know given like an array of string words right you need to return the smallest string that contains each string in words as a substring if there are multiple valid strings of the smallest length it will return any of them all right so and you may assume that no string in words is a substring of another string in words okay so i'm not sure what this won't do but you know okay i would we'll just leave it for now okay so what does this what does a super stream mean right i mean a super stream is a long it's a longer stream that can include basically you can find each word as a substring in this super string here for example we have this one you know we have alex loves list code this one is the easiest one because basically we're just concatenating these three uh these three strings together because there's no overlap and that's why you know all the permutation of these three strings will be acceptable right but when it comes to the second one this one is more complicated because as you guys can see some of them are basically are the can be overlap at each other for example you know this kind of uh maybe this you know we have a gcta right so that's the first one and how about the second one is it's like the uh a g yeah second one actually is what is the cta gt because you know this is this second one right ctaa gt now you can see right so we have some overlapping between those two words that's why the smallest one is this one and yeah and the constraints like uh we only have like uh less than 12 words and each word is at least at most 20 characters long right um so to solve this problem you know at the beginning i was thinking like is there like any greedy solutions let's say if we find the uh the two words right i mean that has the uh the most uh overlapping words and then we try to combine those together right and then we'll just try to do the same thing after that but i think to be honest i think the gritty approach doesn't work here be i'm not quite sure the reason being but you know it seems like uh with this kind of given constraints and the nature of this problem basically we have to try all the possible scenarios right so when i say possible scenarios i mean basically we have to try to concatenate the strings starting from any nodes here right and then we're gonna try to concatenate it with another one right basically you know when i say other scenarios it's like what let's say we pick you know we have to have a sequence right let's say we picked the first one this one c-a-t-g as the first one this one c-a-t-g as the first one this one c-a-t-g as the first word right and then after that we can we have what we have like um how many options we have one two three four right we have four options that we can place next to these words right then from there we have another one then so on so forth right and among all of those we're gonna we need to find the uh we need to find path basically a path doesn't give us the smallest string right the shortest string this one actually it's similar like a graph problem you know if you guys know there's like classic problem cause sales uh traveling salesman problem basically that problem is what it's like basically you're given like a graph here you know uh a graph you know there's like directed graph here you know basically we have different nodes here and between each node they're like uh they're like a weight right basically each node has like each two pairs of node has like a weight you know and your task is to only your task is to travel each node only once while the total cost is the smallest that's the traveling salesman problem and this one is similar to that so the reason being that you know we need because we need like the uh we can travel basically we can concatenate any word right after another one right then each pair have a different cost right so when i say cost what does it mean it means that let's say we have a we have two words right so the first one is like uh a b c d right this is the word one right and the word two is like what let's say we have a uh let's see the first one is the edf okay so this is the word too so the cost to con to concatenate this abcd and edf obviously is what is three because there's no overlapping that's why we have to concatenate everything from word to you know what if this one is like a cd sorry cd cde how about this one right we have cde here and then what's the cost to concatenate these two words i mean it's one right because cd is part of this one so all we need to do is we need to add like an e in the end of this word one that's why the cost is one all right and so with this kind of things defined right so which means that you know from two words so this is a directed graph because you know if we uh concatenating word two after word one and concatenating word one after word two that the cost is different that's why this one is a directed graph okay and after that right so for the traveling salesman problem you know there's a dp solution you know for this one so what's the dp's state so the dp state is like this we have a dp we have a mask and then we have a j so why we have two state okay so the first is the first one is the mass so what is the math mask is like zero one right one 0. so the mask record which word or which node we have been we have visited before and obviously the end state is what is one right so whenever the one whenever they are they're all visited then that's the end state okay and then why do we need the second state here so the second state is what is the ending is it's the last word in this mask so what does it means that okay so for example if the mass is 0 1 how many words do we have in this mask we have four right and this j means that you know which word ending is because you know we can end in this mask uh in different paths right we could because different last words will give us the different cost right because you know the reason we need to stay here like i said you know depending on because we need to know what is the last word in this mask like i said you know we because we have a sequence you know let's say we have already uh let's say three right let's see we have already uh visited these three words right and now we have some strings you know now let's say we are we need to visit uh this one this the next one gc ta is the next one but in order to find to calculate the cost right to visit this one we need to know what is the last word because only then we can calculate the cost right and another thing is that you know the because you know once we have already visited these three words you know we're going to have like a very long string right some strings that can uh will contain these three words and depending actually it doesn't really matter what was there before because we're sure the last one the last few words has to be one of each these words depending on this j here right let's say you know if this j equals to uh zero one two three let's say the j is equal to three it means that with this kind of uh is this kind of like a mask okay this mask may not be correct but i'm just showing you guys so and the last word is three which means in this case this is ttca so it means that at the current state the last four words it's the ccta sorry the last four letter ccta because that's how we define that it doesn't really matter the previously stuff right because all we as long as we know the last word is this one we can use this like calculation to calculate the uh the cost from the current from this current big string to the next one which is the which is followed by the gcta right that's why besides this mask we need this j here okay cool and then how about the state transition function right and obviously you know the state transit function state transition function is that you know since we're using like bottom up dp solution it means that you know we have to know what are the previous state basically how what are the states that we can get to the current state right then so then what's going to be the current the previous state that can get the current state is the uh it's one of these this one's needs to be zero right because you know since the current one is it's j right uh let me draw like a bigger picture here maybe that will help you guys understand the state transition function here so we have dp current mask right current mask and j so this is the current state right and then let's say for example we have 1 0 1 okay and the j is equal to 0 1 to 3 is equal to three right that's the current state so and we need to find out all the other possible scenarios that can get to the current state right so which means that you know the previous state is what is this one it's uh it's 1 0 1 because the current state is that you know the last one is 3 which means the previous one has to be zero right zero one two three it means that you know from the previously previous state we have this mask and that's why you know we can for the next one basically we are visiting this j word that's why the j's one will be changed from zero to one from the previous state to the current state right so that's the previous one and as you guys can see right so the from the previous state we have also we also have like a different scenarios you know we have three ones right so we have three words could a possible ending words and each of them could give us like a different cost right this because this these three are these three different words which means that we need to uh try all the three words here as like as an ending word so that we can get to the current one because each one of them will give us a different cost and we need to enumerate all of them yeah and actually you know we so basically this one is going to be a dp of you know we're going to have like a pre mask right so we're going to be pre mask and this one is going to be k so k basically k zero is between the zero and the k right and then plus the cost from what cost from k to j we need to get the minimum from this right so and this one this cost the cost from k to j this one should be pre-calculated and so and why we loop through everything including the zeros is because you know we can ignore zeros because at the beginning everything in this dp will be uh will be the system max size right and which okay so we need to get a minimum which means that you know whenever we're looking through the k where the k is uh pointing to a zero when it's pointing to zero you know since we never have like state with zero there you know that's why the net the value the dp value in that state will be equal to the system max size which means we'll just basically ignore that right and yeah and that's it right and that's basically the way we're traversing all of the states here and then we're also going to get the minimum and since we're we need to output the final string instead of the length right so in that case i mean we can while maintaining the length the smallest length for the db here we can also store the current string along with the length inside the dp that's one way we can do it or we can maybe try to rebuild the path and the under the final string in the end but i prefer to store the stream along with i mean with the dp with the length in this dp array here because it will make this uh code a little bit shorter and okay so is that being said you know let's try to code then so the coding will be a little bit a bit long so and just stay with me uh so first let's try to uh let's try to calculate the cost for each between each word right we have word one and word two right and then so again this cost of word one is like what's the cost to append were two after word one right so that's the definition of the cost we have n1 is going to be the length of word one and two length of word two right so i mean we can do this so for i in range of n and one right so basically if the word two starts with right starts with a word one uh do a slice of that you know and then we return what we return the uh n2 minus uh n1 minus i either otherwise we return to so what does this one do basically you know we have so we have a b c d right and then we have uh we have cd cde right cdef so basically we're starting from the first uh word and we're trying to see starting from the current location i here you know if the remaining is a prefix of this of a second word then we know okay that's the uh we have find the most common strain right then which means that you know we can subtract the length uh the length from the second word right which means that you know so here i compare so the remaining part is it's just it's a part it's a prefix of second one it means that we can subtract this much length from the second word right because an n1 minus i is a remaining length is that it's a common part and we do what an n2 minus that it means that we're gonna that's got that's the uh that's the remaining part we need to append right and if this thing never happens which means that we need to re append everything from n2 okay all right so that's the cost okay and all right so then let's build the graph right so the graph we have what we have um at the beginning you know we can initialize everything with zero and it's going to be n for one in range of n right since it's a directive graph and then for i in range n right and then for j in range and okay and then we have graph of ij you just look at cost right of words i and then words j okay and similarly we need to do the same thing for the j and i right because if you reverse the order the cost might be different so here we're also considering a word cons like concatenating with itself but you know here the constraint one of the concerns is that all the strings are unique right so which means that you know i would should not should never happen okay but i think this is fine because you know everything for i you know the result will be zero right which means that you know uh the same as the default value and it will never use that value so it's fine i guess okay so now the uh the dp's part right and so let's define the end state so end state is like this one right so that's the end state actually should be minus one but i just use n here let's do this minus one so this is one right so everything's one that's the end state and then for dp like i said we this is going to be a two dimensional dp so the third and since we are storing both the length and the string itself you know we're gonna have like tuple as an element so at the beginning everything is like the maximum the max value since we're getting the minimum right and the string of course is empty right and then for this one we have f of n at the inner sides and for the outer sides we have is kind of the range of and plus one right yeah actually you know what let's do this uh yeah let's do and the plus one yeah because we need from zero to two to this one right okay so all right for mask in the range of end and plot n plus one um yeah so that's the basically that's the current mask right and now we need to get the uh need to get the previous map previously previous mask and okay get all possible right previously masked so to get the previous mask uh we need to check which uh which bit is one right so basically if the mask and this one oh sorry uh do a for j in range of n right that's going to be the previous mask the beat of the previous mask if this one is one basically right if this one is one does not equal zero it means that you know the current this one uh was changed from zero to one that's why the previous mask will be what would be the mask to uh xor right half this uh of this mask so this is a trick here right i mean and why this one works a little bit about this one you know if we have one zero right let's say we're trying to change this one into zero so how do we do it we simply do a do us a mask of this one zero and we do xor between the these two and then we'll get what we want because you know for x you know at big first you know these two ones you know since they are the same they of course they will be come to zero and for all the others you know if the original one is one you know for since for all the others you know they're all zeros if the original one is one and then the current one is zero and the one x or zero will be one right and for if they are genuine zero x or zero is also it's going to be zero same thing that's why you know we can ring we can keep the original value regardless cool so that's the pre mask right and yeah and actually here there's like a base case right so basically if the pre mask equals to zero so what this is it means that you know this is the base case if this is the first basically if the j if j is the first word right then we just uh we can just simply set the value we don't have to calculate because if there's nothing you know the cost to include the first word is the word itself right that's why the dpf of mask j right equals to what the length of the words j right since we have two values in this dp of j and then and also the words itself is going to be the word of j right so that this is a special case otherwise we need to check if the previous one already has some words and then we have we need to check like the uh all the possible ending words right check all the possible ending words right from previous from first mask so the way we check that is that we just need to have like another loop here right so for each of that you know um so i'm going to have like this so the pre this is the pre length right and then the pre stream right because the dp of the pre mask of k so remember so this one like the it's the i think i already talked about this one so this one means that you know from the previous state ending with case word right and that's the uh that's the length and the string for that state okay and then for the current one right we have a current length and then the string we don't care actually the dpf mask of j right i'm just listing those half fun variables here and our condition is what so the condition is this so whenever if the previous length right plus the cost which is the graph of the from k to j if this one is smaller than the current length right and then we do then we know okay we find a better path to get to the current one so that we can have like a shorter string for the current state right that's when we need to update the mask of j right equals to what equals to the this one right the preview that's going to be the first element and the second one but what we have print string right so because that's the pre-string plus because that's the pre-string plus because that's the pre-string plus what plus the uh plus the string we need to append and what's going to be that and we're we are appending repenting the js words right and depending on the cost we already know what are the strings we will need to append right so which means it's going to be the worst j of what of this one actually it's the minors of this right so again right we have a b c d okay a b c d here and then let's say this one is like uh c d e f g okay so as you guys can see from here to here the class is what is three right because which means we need to append three words here that's why you know the preview the previous word is something like this right and abcd now we are appending the jsword which is the cd efg so now what we need to do we need to append efg to the end of the previous string here right that's why we have the previous string is this and then we plus we need to find a pen is efg and this ef-3 is like what ef-3 is like what ef-3 is like what it's the slice right it's the it's minor three slice okay actually i need i forgot this kind of colon here this is it's just like a basic uh slicing here right cool so and that's pretty much done you know the only thing left is that you know we just need to uh keep like a global minimum length and the final answer right and that beginning is going to be the max size and then at the beginning it's empty so here right uh here we need to check if the mask is equal to the ending and the dp of the mask of j and zero because zero is the length right smaller than the global minimum length right and then we know okay we update both those values the minimum length and the answer we can simply use the dp of the mask and j to update that right and then in the end we just returned the answer so that's it yeah so if i run the code this one works right submit cool yeah so that's it i know it's a pretty long one uh but let's take a look at the uh the time complexity so let's say this one is n and second one is m right so it's not that hard to analyze the time complexity so first we have this kind of uh the mask obviously the mask is 2 to the power of n right and inside the mask we have what we have another end right to loop through all the possible pre-mask and then and inside of here we have another end to check all the possible endings right so which give us like n square right and then last but not least is this one this a slicing i believe so here we have another m i believe right that's the worst case scenario so that's the uh that's a time complexity then yeah and the space complexity is this one space complexity is the uh o of 2 to the power of f n times n right so that's the space complexity or maybe uh plus times n i think times m because we have we also store the uh the string inside the dp here uh the dp here right cool so that's pretty much everything i hope you guys understand this one i hope i explained clear enough yeah basically you know this is just like a graph problem you know you have to figure out some small pieces and stitch them together and the first one is that you know we have to try all the possible scenarios right and among all the possible scenarios we have to find like optimal path right and then second one is that no it doesn't really matter how many strings we have contained the only thing matters is the last string it's the last word because given the different word and we'll have like different cost that's how we that's why we pre-calculate the how we that's why we pre-calculate the how we that's why we pre-calculate the cost between each words so that you know when it comes down to the previously state right we can know from the k to j right from k to j we need we know we have the cost and then with the cost we can update our stream and we just update the final answers in the end cool i think that's pretty much it is and i thank you for watching this video guys stay tuned see you guys soon bye
Find the Shortest Superstring
sum-of-subarray-minimums
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** words = \[ "alex ", "loves ", "leetcode "\] **Output:** "alexlovesleetcode " **Explanation:** All permutations of "alex ", "loves ", "leetcode " would also be accepted. **Example 2:** **Input:** words = \[ "catg ", "ctaagt ", "gcta ", "ttca ", "atgcatc "\] **Output:** "gctaagttcatgcatc " **Constraints:** * `1 <= words.length <= 12` * `1 <= words[i].length <= 20` * `words[i]` consists of lowercase English letters. * All the strings of `words` are **unique**.
null
Array,Dynamic Programming,Stack,Monotonic Stack
Medium
2227
143
welcome back to uncle Jess today's question is leak code 143 reorder list so you're given the head of a singly linked list those can be represented as l0 all the way up to Ln and we need to reorder the list in the following form so l0 points to Ln points to L1 points to Ln minus one L2 Ln minus two right so let's not waste any time and dive straight into the walkthrough so we have this link list here right l0 L1 Ln minus two Ln minus 1 and Ln and we need to create this result right so somehow we need to break this so that l0 points to Ln points to L1 points to Ln minus 1 and Ln minus 1 points to Ln minus two so firstly I'll give you a high level overview of how we're going to solve this we need to split this into two right we need to split at the middle so this is an odd length linked list so we're going to take one two and three for the left linked list and then we're going to have four and five on the right list we're going to break this connection we're going to reverse these two so five is going to print 4 and this is going to point to null and then we're going to have this linked list on the left hand side right so we have two separate link this then we combine these two right to give us this solution so that's the high level overview of what we're going to do so firstly we need to work out the midpoint within this linked list and how can we do that well there are a number of different approaches to resolving this but we're going to use a fast and slow pointer also known as The Tortoise and hair algorithm so the first point is going to move twice as fast as the slow pointer so after the first iteration fast will be here slow will be here then the second iteration fast will be here and slow will be here now we can say as long as fast dot next and fast dot next are available then we keep on searching for the midpoint but as you can see fast.next is midpoint but as you can see fast.next is midpoint but as you can see fast.next is pointing to null so we have the midpoint which is slow so here we can create a reference to this we'll just call this current right because what we're going to do is we're going to break this so we need to create a reference so that we can always get to this value within the linked list so we're going to break this and this value is now going to 0.2 and this value is now going to 0.2 and this value is now going to 0.2 no so we've broken the list up into two link this now we need to reverse this link list and if you want an in-depth link list and if you want an in-depth link list and if you want an in-depth discussion on how to reverse a linked list I definitely check out my video on the code question 206 reverse the link list but essentially in order to reverse this we're going to have 4.25 Point into this we're going to have 4.25 Point into this we're going to have 4.25 Point into null we have current value here we're going to create a previous value which we're going to set to null we want to break this point and have it pointing over to this null but in order to do that we need to create a temporary variable to 5 so that we can access this once we've broken this let's break this let's point this to null then we update the previous the current and the 10 points right so previous move to current moves to Temp and then we repeat that process so we want to break this point and move it here but we need to create the temp we break the point and then we update the pointers so previous moves to current moves to temp and now we're at a point where current is equal to null so we've reached the end of reversing this link list so now we have these two thickness all we need to do is combine them in order to get this output and we're going to be using pointers throughout this in order to do that so we're going to have a H1 pointer pointing to the head of this linked list and a H2 pointer pointing to the head of this thing list now as you can see in the results the one from H1 is pointing to the value from H2 so we want to break this and have it point to H2 but in order to do that we need to create a temp variable on two so that we have access to this so let's go ahead break that and make the connection so one points to five so H1 points to H2 now we update these pointers H1 becomes H2 becomes temp H1 H2 and then we repeat the process so we create a temp variable at so this is going to variable at so this is going to variable at so this is going to be here because we are going to be breaking the connection Five Points to two right so we need to break this five then points to two great then we update these points so H1 moves to H2 moves to 10. so the next step is to break this point right and we want H1 pointing to H2 so we create the temp here we break this connection and we make a new connection between H1 and H2 and then we update the point so H1 move to H2 moves to 10. okay so the final step here we want to break this point here so we'll create a temp here we'll break that point and then we'll point four to three and then we'll update H1 H2 and temp so H1 moves to H2 and H2 moves to Temp now as you can see H2 is at null so we can exit this if we have a look at where these are pointing well one is pointing to five is pointing to two is pointing to four and four is pointing to 3. which is ultimately pointing to null and as you can see that is the answer we're looking for so this solution that we just calculated is running at a n and space is going to be o1 for this so let's start off by finding the mid we're going to have a slow and fast pointer so slow is going to equal head fast is also going to equal head and then while fast.next and fast dot next are available we're going to update those pointers so slow equal slow.next and fast equals slow equal slow.next and fast equals slow equal slow.next and fast equals fast dot next once this is run the slow will be at the middle so now we can break this linked list so firstly we need to create a pointer so that current equal slow.next so that current equal slow.next so that current equal slow.next and then we can say slow dot next is equal to null now we need to reverse the second link list so let's create prev which is equal to null and then whilst current is available we'll create the temp which is equal to current.next current.next current.next current.next is equal to prev current.next is equal to prev current.next is equal to prev is equal to current and current is equal to Temp then the final step is to combine these lists so we're gonna have a H1 which is pointing to the head so the first link list and then H2 is going to point to prev right and up here we created prev we ran through reverse in the second link list so prev is now going to be pointing to the start of the second link list and then like we said in the walkthrough whilst H2 is available we need to create a temp variable so that we don't lose the next position of H1 dot next is going to equal H2 H1 equals H2 and H2 equals temp so first we find the middle we break the link list we reverse the second list and then we combine this together and this should run so let's give it a go submit it and there you go
Reorder List
reorder-list
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **Input:** head = \[1,2,3,4\] **Output:** \[1,4,2,3\] **Example 2:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,5,2,4,3\] **Constraints:** * The number of nodes in the list is in the range `[1, 5 * 104]`. * `1 <= Node.val <= 1000`
null
Linked List,Two Pointers,Stack,Recursion
Medium
2216
1,282
hey everybody this is Larry this is uh I guess September 11th on uh legal daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's poem 1282 group The People given the group size they belong to all right that's a very title uh that's what it's up what he's trying to say hope everyone's having a good weekend hope everyone's having a uh you know going to have a good week uh yeah that's I don't have much to say today other than that New York is pouring today so I got soaked but I got took a shower before doing this but it's okay it's a long gem day right so yep and people split into some unknown number of groups each person is labeled with a unique ID from zero to n minus one you're given an interest away group size where group size of I is the size of the group that person is in for example if group size sub 1 is 3 then person one must be in a good side doing okay we've done a list of groups such like each person I is a group of size group size I okay um there's at least one guarantee solution I mean I think greedy is good enough right I don't think there's anything tricky about this unless I'm really confused uh and what I mean by that is that if three if you're in a group size of three say the three people that's gonna be in that group right and if you're in the group side one there's only you're the only person and so forth so you just basically match up the group sizes right I mean that's pretty much should be the idea and they do guarantee that it will be valid so we don't have to even do any uh checking um yeah I mean I think that's the idea uh let's get to it then I think that's it right so let's just say I'll have a look up for lists yeah okay now for I in range uh let's just do IX and enumerate group sizes right maybe s for size uh groups of I that append oh oops group of s a pentai and then that's pretty much it and then we uh we have to kind of split them up I forget how you I think in pipeline there's a even a Slicker way of doing it but huh let's see I feel like if I find there's a this everything's in editor so it'll choose a Sprint maybe let's see let's take a look of inner tools uh strawberry goodbye no it's not goodbye but take well tea um chain now the opposite of chain hmm combinations no psycho sorry that I guess today's Farm is just uh Google I mean to uh to be honest I mean some of it is and obviously we can just do it manually if we really want to right you just take like you know basically what I want to do is for G and groups.keys right do is for G and groups.keys right do is for G and groups.keys right then uh yeah this is the size of S7 group.keys yeah this is the size of S7 group.keys yeah this is the size of S7 group.keys and then groups.s and then you want to and then groups.s and then you want to and then groups.s and then you want to split it up by um so each as chunks will be in a group right so that's basically the idea so but for me to be honest uh right now a little bit of a disclosure is that I'm trying to see if I can learn a little bit about python edit tools because you can definitely manually do it and maybe we will manually do it but T independent iterators no I feel like there should be a thing but maybe I'm mistaken uh basically what I'll take maybe now uh basically what I want to do is like um for oh is this groups maybe G and um uh something that returns in return to group also right so like I don't know I'll help the function I'm just trying to figure out how to name it uh get group uh break into groups Maybe of uh s right and then we just entered out a pen G and that's pretty much it but I'm trying to figure out if there's a way to uh if it's in other tools that's what I was going to say I feel like editors have every oh grouper is I think what I want but it's a recipe and not um hmm isn't more editors not editors huh I wonder can I do Cooper let's see if more editors is not in it and I mean they give you a recipe which you can write or copy and paste which I will do here but we can also write our own um right and that's just an editors like literally in the thing um and this is probably like race liquor than the way that I would have done it to be frank but that is a fun that I definitely would not have done it this way but I've just probably done a q type thing right so let's give it a submit and then we'll just do it manually because yeah it's fine right uh yeah it looks good 12 59 Day Street pretty slick pretty fast pretty okay and uh and of course like we said we can also just do it manually right so yeah um here then now you have maybe like a return and then uh and a couple of ways you can do it I think in free when I if this is a if we convert this instead of a list we convert it to a collections.deck then we convert it to a collections.deck then we convert it to a collections.deck then we can pop off the front I mean you can also just pop off the back but I think this here at least the lines of my thing more clearly so then now for IX in Array or enumerate away right uh if I plus one my S is equal to zero does that work was one two should be when you get one and two then yeah right yeah okay so do right uh is that is it like that clear or something I mean that would be much cleaner cannot find the equal key something like that right like we can do it that way there are really many ways to do it and this just you know maybe not the cleanest and maybe have a silly mistake but uh yeah and roughly the same thing that is in the given input uh yeah I mean yeah I don't think there's any other thing to say about this one I think the observation that if you're in a group of size X literally X people are in that group including you so that so it must appear x times and there's no other way to kind of group them so yeah uh let me know what you think what is complexity here right I mean this is going to be linear time linear space just because it really did it this way um you can probably also just done it I mean you could have done this like more live but it's still going to be the same complexity um and the linear space you can really do better because that's the size of the output and then your time you just kind of go through everything once here and then another time here uh which is technically here maybe so yeah uh what did I do the first time I am curious wow that was what year is this is like three four years ago uh and yeah at that time I kind of wrote it in a quick way uh that's the thing that I said I could do but I don't want to anyway uh yeah that's what I have for this one let me know what you think have a great week everybody stay good stay healthy to good mental health I'll see you later and take care bye
Group the People Given the Group Size They Belong To
number-of-valid-words-for-each-puzzle
There are `n` people that are split into some unknown number of groups. Each person is labeled with a **unique ID** from `0` to `n - 1`. You are given an integer array `groupSizes`, where `groupSizes[i]` is the size of the group that person `i` is in. For example, if `groupSizes[1] = 3`, then person `1` must be in a group of size `3`. Return _a list of groups such that each person `i` is in a group of size `groupSizes[i]`_. Each person should appear in **exactly one group**, and every person must be in a group. If there are multiple answers, **return any of them**. It is **guaranteed** that there will be **at least one** valid solution for the given input. **Example 1:** **Input:** groupSizes = \[3,3,3,3,3,1,3\] **Output:** \[\[5\],\[0,1,2\],\[3,4,6\]\] **Explanation:** The first group is \[5\]. The size is 1, and groupSizes\[5\] = 1. The second group is \[0,1,2\]. The size is 3, and groupSizes\[0\] = groupSizes\[1\] = groupSizes\[2\] = 3. The third group is \[3,4,6\]. The size is 3, and groupSizes\[3\] = groupSizes\[4\] = groupSizes\[6\] = 3. Other possible solutions are \[\[2,1,6\],\[5\],\[0,4,3\]\] and \[\[5\],\[0,6,2\],\[4,3,1\]\]. **Example 2:** **Input:** groupSizes = \[2,1,3,3,3,2\] **Output:** \[\[1\],\[0,5\],\[2,3,4\]\] **Constraints:** * `groupSizes.length == n` * `1 <= n <= 500` * `1 <= groupSizes[i] <= n`
Exploit the fact that the length of the puzzle is only 7. Use bit-masks to represent the word and puzzle strings. For each puzzle, count the number of words whose bit-mask is a sub-mask of the puzzle's bit-mask.
Array,Hash Table,String,Bit Manipulation,Trie
Hard
null
915
hello everyone and welcome back to another lee code video so today we're going to be solving the lego question partition array into disjoint intervals all right so in this question we're going to be given an area called nums and the goal is to partition it into two contiguous sub areas called left and right so we have a few conditions which is that every element in left has to be less than or equal to every element in right and left and right are both going to be non-empty right are both going to be non-empty right are both going to be non-empty and in this case left has to be the smallest possible size so we can have uh several different solutions to this but we want the one where left is the smallest possible size now the goal here is to return the length of left after such a partitioning and it is guaranteed that we have such a answer so one quick thing over here is the fact that we minimum we have to have a minimum area size of two because uh we need two contiguous sub areas which are not empty so that is something that is covered over here the minimum length is two and now let's just look at one solution to see how we can work on this so this over here is one of the questions we have triple 1 0 6 12. so let's just make a few observations now one of the observations so let's just look at the answer here before that so over here the length of l is four okay so one two three four that's the length let me just change the color real quick um sorry okay so one two three four okay so this over here is the partition that we're making so this everything over here is the left sub area and everything over here is the right sub area okay and let's just go to the checks real quick okay they're both non-empty quick okay they're both non-empty quick okay they're both non-empty obviously and this is the smallest possible size left can be oh and i'll go through that again and over here everything in left is less than everything in right and keeping that in mind we can actually come up with a simple observation and that is the fact that left right since everything in left is left and right left is going to have the minimum value for sure in the same way right is going to have the maximum value so what's the reasoning behind this it's pretty simple the left everything in left is less than or equal to everything right so that automatically tells us that the smallest value cannot be in the right value in the right area the same way the maximum value cannot be in the left sub area so that's why l is always going to have the minimum value and r is always going to have the maximum value so that's one thing that we know for a fact now let's go on to a second observation that we can make so over here we have the values 1 0 and 6 12 for the right sub area so let's do the check which is everything in left greater than every less than or equal to everything right so the way one simple naive way is it's one less than six and we keep doing that is one less than six great okay so now we're done checking for six so now we need to go into the second area oh sorry second element in r which is twelve so it's one less than or equal to twelve so we keep doing the check for everything and out so this over here is going to be very computationally intensive so one really simple way to look at it is remember l is going to have the smaller values compared to r and r is going to have the greater values so one really simple way to just check for everything instead of doing this several for loops we can just look for the maximum value in l and compare that with the minimum value in r so what is the reasoning behind this so like i said l has all the small values and r has all the big values so if you just take the smallest of r and the largest of l and if the maximum value of l is less than or equal to the minimum value of r that's the same as checking each value of l against each value of r so in this case let's just do an example l is the largest in l sorry a one is the largest in l and uh six is the smallest so in this case one is less than or equal to six great okay so we have these two observations and let's try to put that into a solution so what i want to show you first is a solution that i kind of came up with and why this may not be the best solution so uh actually building upon this solution we reached the final answer but i just want to show you the solution that i first came up with and why it may not be that good so what i did is i came up with a two pointer method which is i had a pointer which starts off at over here so at zeroth index and one which starts about the very ending so let's just call it l and r okay so what's happening is that each time we move l and r to the left right respectively until we have some sort of division okay and now what are the conditions for the division so one thing i'm using is the fact that left has a minimum value and right has the maximum value so what i'm doing by default is i'm moving l to the minimum value by default so l in this case the minimum value is zero and by default i'm moving r to the maximum value which in this case is 12. so this is going to be our starting point so that's a pretty good place to start and now this is where it gets a slightly complicated how do we move l and r in this case okay so in this actually it works out pretty well remember this condition which is pretty important left has the smallest possible size so over here we can either move l or we can move r now obviously we can't move them both because we can't have them at the same place so we're only going to move one of them and in this case we're always just going to choose to move r and the reason for that is because we want the smallest possible l size right so now we move r and we perform the check and remember the way that we're doing this is we're keeping track of the minimum r so in the beginning the minimum r by just because there's only one value is 12 and the maximum l in this case is one okay and the condition applies so we're good to go so now when we move r to the left by one so r is over here now the minimum r now becomes six so that's what we have and the condition still holds true so that's great so in this case we actually found a division because l and r are right next to each other so we have a division here and we return the length of l so this actually works out perfectly and this is what i did for my first solution so let me just get rid of this okay and you can see the code for this over here uh but there's actually one place where it never worked out so over here i went to the smallest and largest value and then i did the loop that i was talking about earlier moving l and r and like i said i moved r first because i wanted the smallest possible l so this is one test case which failed okay and let's just look so the output i got was the index 7 for l and the index uh 10 for r so this is the value 22 and 46. so this over here is slightly weird and i use the same loop over here but realistically for our final answer the l and r have to be right next to each other but in this case what happened is let's just look at this so the maximum and the left is 42 and the minimum on the right is 46. so let's say we move 62 over here right now 62 automatically becomes too big because 62 is greater than the minimum in the right so we can't do that and if we move this to the left over here we're going to have another problem because it's because when we do that we get 16 and 16 over here is too small 16 is less than 42. so that over there is a problem by itself so this actually is a problem and we just get stuck in the while loop so the actual answer over here was 11. so the base of so what that means is that l had a length of 11. so this includes all of this area so all of that is l now this is where the slide problem comes so when we initialized it l started off at the smallest value which is six and r started off at the largest value which is a hundred now by default we always first moved r and in this case that actually did not work in our favor so because of that we had a problem and we did not we weren't even able to find a solution so we could actually rewrite this chord a code to make this work but it just becomes too complicated so now let's look at a better solution that we can come up with which is uh better than this as well so for our actual solution we're going to use the same idea which is we're going to keep looking for the maximum and the left sub array and the minimum and the right sub array and we're going to compare those two and we're going to do this by keeping track of each of them at each instance so what does that mean so in this case what that means is so uh let's look at the max of l and we're going to create a new array okay so what we're doing is we're assuming that we have so this over here is our left sub area so if only this value is part of the left sub array what is the maximum and left well it's going to stay as one okay so we write one so now we're going to assume the fact where both of these are part of the left sub-array sub-array sub-array now the maximum still stays as one uh and now we keep going on so we assume three of these are part of the left sub-array sub-array sub-array so maximum is still one now we have zero so again the maximum stays is one but now when we go to six the maximum becomes six and now when we go to twelve as well twelve becomes our maximum so we have this one area over here okay so this tells us that given a left so considering everything up to the certain index so let's say we go to index two so let's say everything up to an including index two is considered as the left sub array the maximum value is going to be one this is what it tells us now we're going to do the same thing but for the right values okay so let me just actually just use a different color and we're going to find the minimum of the right values so now when we're doing the min r we're going to go from right to left and the reason for that is because when we're going from left to right for finding the max of the left sub array this is how it looked like right so let's say we wanted the fourth cell of index it's we're considering this entire thing right from zero to the fourth index now for the right sub area we're going to consider from the ending to whatever index so let's say we want something up to the second index then we're going to go from the ending up to the second index right oh sorry here right so we're going from the right to left pretty simple okay so in this case first we're going to have just the value of 12. so in this that case the value is this minimum value is 12 we have no other option now we have 12 and 6 so in this case 6 becomes the smallest right so now we go to zero and zero becomes the smallest and now as we go to the left uh whatever we do zero is going to stay small so let me this is gonna become zero this stays zero and this place zero okay so now that we have these two areas our question is how can we actually use it to actually solve our question so the idea is going to be the same right so at any given point max of l has to be less than or equal to the max r value right and keeping this in mind what we're going to do is we're going to iterate through this area now the way that we're going to do this is for l we're going to start iterating through this zero with index but for r over here so min r we're gonna start iterating at the first index now why are we doing this the answer is super simple so if we're doing this what we're assuming is we're making a partition over here so what that tells us is that the zero index everything up to there is going to be part of the left sub array and everything and for the right subarray everything up to the first uh index is going to be part of that right sub array the minimum value is zero and considering that this is part of the left sub-array the maximum value is one left sub-array the maximum value is one left sub-array the maximum value is one and so we're going to compare these two values and with the same condition which is max l has to be less than or equal to max r okay so in this case it's not so we're going to move it so this color is over here and this goes over here so in this case the same condition one is not less than or equal to zero so now we move both of them again same thing over here one is not less than or equal to zero and now one and six so over here we this condition is true one is less than or equal to six so keeping this in mind that means that we've found our solution and what this is telling us is that the partition is right over here and the reason for that again is it's telling us that the left sub array is going to be from the zeroth index up to the first second third index including the third net x and the maximum value is one and the same way the right sub area is going to be from the ending up to this index over here which is um what zero one two three four up to the fourth index and that value the maximum value there is going to be six and the condition is meant and one more thing going from left to right this way actually gives ensures that we have the smallest value for the left sub area in size so this over here is going to be our final solution and the size of this is just going to be 1 two three four so we've returned the value four all right so we're gonna start off by actually uh creating our two areas so we're gonna have the left array where we're gonna get the max so we'll just call it l max and we're just gonna define an empty area so we just have them with nuns and the length of it is going to be the same as the length of numbs okay and we're going to do the exact same thing for the right so right but except this is going to be right min and the same thing over here as well so now we're going to have the first loop which is going to be filling up everything for l max so the way we're going to do this is we're first going to have a value called current max and we're going to assume in the very beginning that the current maximum is at nums zero right and that makes sense when the left sub array just has whatever is at index zero okay so let's have a for loops over x in range length of nums so over here uh the first thing we're doing is we need to update current max if its value has changed so current max is now going to be the maximum between composer between current max itself and whatever the current value we're on is which we get using nums x okay so now that we have a new updated current max this is going to be the value that goes into our left um sub area so l max so l underscore max at the x index is going to have a value of the current max okay now we're going to do the exact same thing for everything in our min so over here we're going to have a current min and this over here is going to be the opposite it's going to be the last value so nums negative 1 and we're going to do the same thing so for x in range but now we're going to iterate it backwards so length of nums minus 1 we're going to go up to the zeroth index so zero minus one and uh we're going to decrement by one each time okay perfect so over here we're going to do the same thing we're going to update our current minimum so we're going to take the minimum between the current minimum and the current value that we're on which is numbers x so now that we have the updated minimum we go to r min go to the x index and it's now going to have a value of current min perfect so now we have of l max and our min completely filled up so the next thing to do we have these two areas we just need to do the comparison step and the way we're going to do this is by using a for loop and remember like i said sorry one second okay yeah so like i said we're going to start iterating for max l for add to zero index but we're going to start min r at the first index okay so keeping that in mind one simple way we can do that is we can have a for loop where we start off at zero but we're only gonna go to length of nums minus one right so we're gonna go to the last but one value and the way we're gonna do this is that we're gonna check if so we're gonna go to l of max and l max we're gonna go to the index x and we're gonna check if this is less than or equal to r min but this is gonna be at the index x plus one okay so this is the comparison that we're having and at this point if this condition is true we have to get the length of everything at the left and the way we get that is that's just going to be x plus 1 right because remember we're going to the index x for the left sub array and its length is going to be plus one since lens starts counting at one while indexing starts at well zero so let's submit this and as you can see our submission was accepted so hopefully this video was helpful and thanks a lot for watching
Partition Array into Disjoint Intervals
generate-random-point-in-a-circle
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: * Every element in `left` is less than or equal to every element in `right`. * `left` and `right` are non-empty. * `left` has the smallest possible size. Return _the length of_ `left` _after such a partitioning_. Test cases are generated such that partitioning exists. **Example 1:** **Input:** nums = \[5,0,3,8,6\] **Output:** 3 **Explanation:** left = \[5,0,3\], right = \[8,6\] **Example 2:** **Input:** nums = \[1,1,1,0,6,12\] **Output:** 4 **Explanation:** left = \[1,1,1,0\], right = \[6,12\] **Constraints:** * `2 <= nums.length <= 105` * `0 <= nums[i] <= 106` * There is at least one valid answer for the given input.
null
Math,Geometry,Rejection Sampling,Randomized
Medium
914
967
Hello friends in today's video Let's solve with good problem of the day for daily challenge problem numbers with same consecutive differences so we need to return all non-negative integers of to return all non-negative integers of to return all non-negative integers of length L and such that the absolute difference between average or consecutive digits is K and we need to exclude previous prefix zeros right reading zeros and answer could be written in a new order right so we are given sample n equal to 3 and k equal to seven uh and here means the length of the sorry and N equal to 3 and k equal to 7 so n over here means the length of the digit okay length of digit a length of number sorry not t here digit is definitely a single number and K is the absolute difference required right so for n equal to 3 and k equal to 7 what I could what are the possible is 181 why because the absolute difference between 1 and 8 is 7. and 8 and 1 is again 7 so this is a valid number and one of the other possibility would be 818 why because absolute difference between these two is seven and again this is 7 so which is equal to my K and the length of this number is 3 correct so this is one of the valid so we need to return all of the valid possible things right and we are also see we can see that the constraints are very small right so it would some it would be something uh recursive right means we could try out all of the ways and then we could find that if it is a valid way then when then we would put push back into our answer Vector okay answer so how could we do that see I can start iterating from see I have n equal to let's say three so I have three places to fill so I can see initially this place can be filled with only either one to nine right because we need we did not require any leading zeros correct so this place could have one two nine this place could have zero to nine and similarly this place could have zero to nine digit that is the case okay so now I can start iterating from this place means in this place I could try placing one or two or three until nine right and then in the next place what I could place my I am given k equal to 7 right so if my in my first place I have placed one then in second place I can test for all of them I can test if I can I could place the numbers on which numbers I could place so I could either place one plus seven which is eight why because then only see if I place 8 over here then only absolute difference would be 7 correct so either I could place the previous number plus the k or I could place previous number minus K that would be minus six but I could not place any negative number so we because this case is eliminated uh so here I could only place one then again at this place what is the previous digit 8 previous digit is eight so either I could place eight plus seven that is fifteen or I could place eight minus seven that is one see fifteen is not a digit it is an I would say two digit number why because we need only we have only one space left and we need to place here only right so we need to place digits not numbers so I would this case is eliminated and I would have to place again one right so that's the absolute difference between these two would be seven which is all required so let me quickly code it down and in case if you have any doubts then we could look into it so let me take one vector end of answer I would start recurring from NK and answer okay see and now as I said we need to first film the first position so in my first position I could have only integers from 1 to 9 that is a special case hence we are handling exclusively right so then I would call a DFS on my the previous digit or I would say current number what is my current num and K and answer and finally I would return my Vector of answer correct so yeah see now uh while calling DFS see what would be the case I have three places let's suppose initially now I have placed the one over here right now how many places are left n minus one similarly when I place any number over here let's say two then how many places are left n minus two right so since I am placing a first digit over here now my next uh now only uh what my what positions are left n minus one correct so that is why I'm passing n minus 1 this is my number this is the size of the number this is the difference which is required and this is my and answer vector if my see if my size equal to 0 then I have to then I have reached my result and I am pushing back my number into my answer Vector correct and then I would return simply from here and else if it is not the case I would find out the last digit see last this would be numbers mod number modular 10 why see this is these are the three let's say these are four places I have placed one two three four five six till this point right now I have to place next number so now my what is my last digit number modular 10 would be give me the last digit so last date is six and now what I can play 6 plus 7 is 13 or either I put plus six minus seven equal to minus one so if both of the cases will then I cannot Place anything right then I would simply return it back from here I cannot do anything and for our case see one is placed eight is placed now it is two are placed so now what is my last digit eight what I could place eight minus 7 that is 1 or 8 plus 7 that is fifteen this is this case is eliminated and so I could place only one definitely so then this is the case right so now last number is this see I will check if my last plus K is less than or equal to 9 right because we need only single digit number so if my last plus K is less than or equal to 9 then definitely I could place that and how would I increment that number right now see let me take one more uh one more example and explain to you see I have placed the one over here now these two places are left and my n equal to 3 and k equal to 7 as we are taking case of first example right so n is placed K is left so now I could place one plus seven right one plus seven is eight Which is less than or equal to 9 and so I could place eight now see my current number is only one uh sorry current num is one now what would be by num when I placed it num would be now 18 right so how would I change 1 to 18 see what I could do I would multiply num by num into 10 and then I would see my what is my last digit one then I would increment last digit and my k value right so K value is 7 and plus 1 is 8 so that is what I need to play so now I'm equal to num into 10 plus last plus K okay number is equal to number into 10 plus last digit what I pulled out and plus K this is what I would place this is what would be my new number right you should yeah you if you are not getting it try run on write on some cases and you will get it right so number equal to now my number would be number Plus or I would say yes number into 10 plus last plus casings I will place a field one of more positions and I would reduce my n value and also I would check if my K is not 0 right K is not equal to 0 and my I would check if my last minus K is greater than or equal to 0 or not if this is the case then I could place that number also and that would be number into 10 plus last minus K and I would decrement my uh size so this is the these are the simple cases see in the second test case what I am doing see I have placed one and eight now what is the next number I could place seven one right I need a difference of seven so now my eight minus seven which is greater than or equal to zero right so now what is my current num is 18. I need to change it to 181 correct so what I would do number equal to number into 10 plus last digit was 8 minus k seven so number equal to number into ten so 18 into 10 is 180 Plus 8 minus seven this is 181 because I got it so this is a simple formula and you could deduce it from a basic mathematics knowledge right so this is done let me try to run it on sample test cases foreign let me try to rerun it again samples fast let me try to submit it yeah we are getting correct answer so in case you are liking the content don't forget to subscribe to the channel and like the video okay and in case you have any doubt comment it down thank you
Numbers With Same Consecutive Differences
minimum-falling-path-sum
Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**. Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed. **Example 1:** **Input:** n = 3, k = 7 **Output:** \[181,292,707,818,929\] **Explanation:** Note that 070 is not a valid number, because it has leading zeroes. **Example 2:** **Input:** n = 2, k = 1 **Output:** \[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98\] **Constraints:** * `2 <= n <= 9` * `0 <= k <= 9`
null
Array,Dynamic Programming,Matrix
Medium
1224
406
hello everyone today's question is Q reconstruction by height suppose you have a random list of people standing in a queue each person is described by a pair of integers H K where H is the height of the person and K is the number of people in front of this person who has a height greater than or equal to H write an algorithm to reconstruct the queue the number of people is less than 1100 so now I will move to a pen and paper and explain you the question so in your problem statement you have given a random list of people standing in a queue so each pair is a person so that is described a pair of integer which is first is index 0 is H it's denoted to height of the person K denotes the number of people in front of this person who have a height greater or equal to H okay and what you have to do basically you had to construct reconstruct a queue according to this given so you have to pick out a tallest group of people and sort them first you have to sort them descending order according to their height and so but what I will do here first I will sort these people according to their height okay so this is 7 and 7 there is only two group that is 7 0 and one okay so next site is six so in six there is only one person in this side seven six one and next there is this is five next is 5 in 5 there is this there is 5 0 &amp; 5 0 &amp; 5 0 &amp; 5 - okay so 5 0 &amp; 5 - the next group is - okay so 5 0 &amp; 5 - the next group is - okay so 5 0 &amp; 5 - the next group is for height for group so this is only four and poor now what we have to do we have to place each person index will be just as is given we have to place this person which index will be just as his Kevin okay so we'll place this place we will create or reconstruct a queue according to their key value okay so first I will create a queue reconstruct a queue so that is reconstruct a queue here so first is 7 and 0 this is the we play 7 in 0th index cause K value is 0 and next I will place this 7 in 1 index 7 1 now next one that is 6 1 I will place 6 1 despair in 1 index six-one and now no now I will place six-one and now no now I will place six-one and now no now I will place spike in 0th index 0 to index already have seven zero so I add 5 and 0 now next well that is 5 so I will place 5 to despair in to in index 2 so index this is 0th index now 1 index and 2 &amp; 3 is 0th index now 1 index and 2 &amp; 3 is 0th index now 1 index and 2 &amp; 3 so in to index this there is another where that is 6 &amp; 1 where that is 6 &amp; 1 where that is 6 &amp; 1 but I will replace that is 5 &amp; 2 and but I will replace that is 5 &amp; 2 and but I will replace that is 5 &amp; 2 and next to you six seven and now this is left is for I will place this is height for this pair right four pair is 4 in Gatesville you index this value is a value is 4 so I will place this pair in fourth index so this fourth index is now 7 one so this is our desire answer so I hope problem statement you understood this problem statement what you have to do so now I will move to the solution part first I will take a dictionary that is B and now I will traverse the whole list and I will add I will make H as a key in dictionary and then I will add the heightened cap here in say my key okay first I check if it is not in dictionary then I will make H as the key this HK pair as a bell and if this is already present in our dictionary I just append the next pair now additionally for 7-0 so first seven is additionally for 7-0 so first seven is additionally for 7-0 so first seven is our key and first in our first iteration I add 7 0 and next at 7 1 so now I will sort the dictionary key in descending order sort reverse equals to 2 means sort this dictionary key in descending order so tallest height first and then next to next and now I will pick group and sort it okay so sort it so now I will take a result list and inside this result list I have reconstruct a queue basically result list is a reconstructed Q so in reconstructed queue I add a reconstruct according to their K value so I will add this pair in gate index in Reza list gate index so if the Restless is empty we just add this group inside this result list finally we return there is the list the solution is not a space efficient solution now check it is working or not yeah it's working no submit yeah now I'll move to another approach that is more space efficient solution so first I will take a result list and now what I will do I sort this list sort this people list using lambda function so people comma key because - lambda people comma key because - lambda people comma key because - lambda X first sort the zero index in descending order and then if the 0th index value is same then I will sort index one sought index 1 according to ascending order so now I will traverse this people list sorted people list I will reconstruct it according reconstructed in our result list according to their cave and so I will insert it in K index so I will insert every pair in K index so as I already explained you in North so explanation part so no we just return the result list so now I check the code is working or not yes it's running successfully and now I submit it yeah it got accepted thank you for watching this video please consider subscribe if you are new to this channel and don't forget to hit the like
Queue Reconstruction by Height
queue-reconstruction-by-height
You are given an array of people, `people`, which are the attributes of some people in a queue (not necessarily in order). Each `people[i] = [hi, ki]` represents the `ith` person of height `hi` with **exactly** `ki` other people in front who have a height greater than or equal to `hi`. Reconstruct and return _the queue that is represented by the input array_ `people`. The returned queue should be formatted as an array `queue`, where `queue[j] = [hj, kj]` is the attributes of the `jth` person in the queue (`queue[0]` is the person at the front of the queue). **Example 1:** **Input:** people = \[\[7,0\],\[4,4\],\[7,1\],\[5,0\],\[6,1\],\[5,2\]\] **Output:** \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\] **Explanation:** Person 0 has height 5 with no other people taller or the same height in front. Person 1 has height 7 with no other people taller or the same height in front. Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1. Person 3 has height 6 with one person taller or the same height in front, which is person 1. Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3. Person 5 has height 7 with one person taller or the same height in front, which is person 1. Hence \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\] is the reconstructed queue. **Example 2:** **Input:** people = \[\[6,0\],\[5,0\],\[4,0\],\[3,2\],\[2,2\],\[1,4\]\] **Output:** \[\[4,0\],\[5,0\],\[2,2\],\[3,2\],\[1,4\],\[6,0\]\] **Constraints:** * `1 <= people.length <= 2000` * `0 <= hi <= 106` * `0 <= ki < people.length` * It is guaranteed that the queue can be reconstructed.
What can you say about the position of the shortest person? If the position of the shortest person is i, how many people would be in front of the shortest person? Once you fix the position of the shortest person, what can you say about the position of the second shortest person?
Array,Greedy,Binary Indexed Tree,Segment Tree,Sorting
Medium
315
1,011
okay they're given the two things one is a real weight and one is the target states they skip so i still sort of i still try to understand the question like exactly okay so he says that's packaged on the other copier belt okay and has the weight of okay so i think every package so it was like weight zero is the zeros package that's the weight of the zero package so this is the weight of it each day we loaded ship with package on the copier bell okay we may not load more than weight than the maximum weight capacity of the ship okay this weight capacity of the ship that will result in all the package this is kind of confusing um can we see the first example okay so this example so weights days five okay so um we need to return the minimum of the capacity of the ship yeah so here he said it's 15. yes it means we can't even 14 it doesn't work yes i don't know how did he get 15 yeah okay so for me the answer should between the first uh if the weight is sorted or not either array is sorted or not i don't think it's sort of see it's not solid okay it's not sorted so i think the uh first the return need to be between the first weight and the sum of the or the weight uh the sum of the array because the sum of all the weights yeah so the sum is so yeah imagine that if we have the days equal to one yeah we need one day to carry all the package so we need this oh so okay so that's the capacity right so if okay so how do we find the capacity is when we set the days to one and then basically we want to ship all the ways in one day as a capacity so that's a cut i mean that's the max capacity max okay so max capacity and the mean and the minimum capacity is the weight of the first package uh i don't think we can show you water because the water is depends on the hum like the water of the package right so like it's based on like okay zero one two three yeah and then so for example imagine that this wave starts with 10 and we if the capacity is smaller than 10 we can't start well so you see it says 10 yeah i mean if the first weight is 10 okay if this is 10 right yeah it's 10 and we get the capacity smaller than 10 we can't spend so i mean the minimum capacity needs to be yeah it's needed to be the max of the weight because we can't carve the weight into two parties okay i see what you mean that's all yeah so the minimum capacity so the minimum weight capacity will be the minimum number in this array yeah it there the minimum number of the in this array but the whole the maximum capacity will be the sum of four so yeah so for the max capacity the base is equal to one i mean in one day we can send the order or the package and if we get the mean capacity so if the max of the array the days and needed to be the dance of the array uh not really no okay so i think our goal is to find this main capacity right no we want to find the this way capacity okay within the days yeah but we need to we have the condition of the days okay the day so i mean we don't have the condition of data we can say that the mean we can calculate the mean calculated the mean and the max easily but now we have the days so how we can i just so this is the weight this is five right so and then we found out the max is what the mark at the max thing is 55. i mean the sum the 10 the mean is 10. um it's a question of uh better research i think yeah but how do we search so we have to mean at a max so we can do the banana research maybe we can try yeah so yeah like my first idea is to find see like i find the left and right like so left is the like right the right is the total capacity right is max because i can't so i go through each weight and i sum it so right is this and then left is the max so max of the so left is the max of the whole array so you'll be 10 in this case so yeah so i think that we can do the binary research now but what's the condition that's why i'm trying to figure out like what are we searching so yeah why we should so we need to uh for example now we have a meter yeah there is a left plus the right minus not depressed by you so we suppose that the media is the day is either right uh no the media is the weights okay meat is the way so we try to calculate is that if we get the capacity in the mid if we can send the package in i think we need to create another function or another method to calculate that uh with the in the enter is the array the base and the capacity and we will return true or false to better let us know if we can send this package in these days uh so okay so we need another function to calculate if this mid if this capacity of mid is able to send all the weights in the given days yeah so if the retaining true we will calculate the left side and if the reach retains for us we will calculate the right side so we can say okay what does this function they do so this function is does this function is doing so for example we got a min okay we got a mid and then we check the mid right we checked it if like if that is true of course if it's like if this function so we can emulate check capacity so we're taking the integer mid and then the days right the array and the date wait hold up yeah we have three intern do we need the array no right yeah we need the array we need the phase and the meter so the capacity we want so if wait do we need this why what do you mean let me think oh yeah okay we do need this right because we need the weights and then we need to check if it fits in these days and then with this cupboard okay so if so okay so let's see how can we do this i think it's better to finish the first message because this one we kind of think about that later yeah here you can see that if the check is true yeah you check we know that if it's true we know it fits we know it can fit in this days so the right is equal to the mean why hold up because you know that for all the capacity bigger than the then the mid we can send the other package in these days so we as we need to find the minimum so we will check the left side of the meat okay can you say it again can i just show myself yeah okay let me give you the thing thank you so uh for example we have the meat that is equal to five oh yeah we have the left right mid and right and the right so if b for b we can send all the package in the days in these days all this product we can also send package in this space because it's bigger i mean the capacity okay capacity is bigger so we need to make the right we need to make this right okay uh we need to keep minimize the mid we needed to find the minimum so we need to minimize over the minute so we need to decrea we need to make sure the right is we need to update the right to mage each time until you don't until it's false right until yeah so it's first we check we decide we put the left to the mid plus one to this side to find the to find if it fits again okay oh okay thank you hold on let me share mine well thank you for clarifying man it's very helpful okay so i go so because this case right yeah so we have left right yes okay so we want to make sure the right recorder right here is the easy control yeah okay means is false because we want to make sure it's bigger than this so here yeah because we are sure that the base doesn't work so yeah maybe it didn't work okay and now we just need to implement this game so in the end we need to return the left tension over the uh left is minimum left right is the smallest one so we need a different left yeah i think it works so we can say like uh yeah for me we uh for example for the first example one two three four five six two ten for the first day we try to put all the things maximum to the capacity so for example the capacity is the five i used 11 for example so for the first day we try to put 11 in this in the first day so we put the one and we calculated that how many capacities left and we put the two and we calculated i said what do you mean now so we try to we for each day right we always try to put the capacity so you can i think you can you say well they is bigger than zero well they yeah and we will put we will try to put all the things in this day and uh in the end it's a day minus one you know what yeah when you decrease the day okay so here what do we do here so we need to so you mean like we need to so maybe we need an indexer also we also need the indexed now we can just like loop the way right we can loop 2d i don't see um i think i can write in the same time because i'm not sure it works so i try my best okay oh you're only sure okay yeah i think should be worked but i mean maybe it's complicated okay so this idea so the idea is we want to check so we want to check if the weights can be wait what okay so i see so this capacity is for each day right yeah it's for each day so wanna so our goal is to check if all the weights can be put in it can be put in oh it can be uh how do you say this can be shipped within these days right let me show you in water right so here is a here we can use this dupe right so we use this dupe to access each weight yeah so that's why i want you to put the loop at first yeah so for every weight we try to put it in the capacity effect so you can create an another variable called capacity left okay it should be the capacity because there is a noisy and every time we try to use the capacity maintenance the weight to check if it's bigger than zero well why zero hold up right here um i will uh i try to see a message okay so i mean we have the capacity yeah in this case is 10. yeah okay that's okay so for each weight wait we will check if it can we can put the weight in this if it works the remaining will manage the weight for example at first the capacity is 10 and we the member is one two three so the first we try to put the one in this one and there is nine left and we try to put a two in this one and we have seven left three but four left and a four we have zero left so we know uh we can't put the file in this ship so the first day is over yeah we will restart another day we got another ship so we try to put a six in this shape i see so okay so we always checking the if the remaining so okay so bigger than zero if using uh yeah if it's smaller than zero which means the ship is we can't put anything in the ship so we try which we will put i see what you mean so okay so it's like this um okay so we got a remaining right so it's voice and we got it we can say current remaining day two shouldn't that no you can use the days minus one yeah so if right so we can check many is bigger than zero i'm and the ls so we reset the capacity right yeah but uh you can't you will not we calculate it for this weight so you need your capacity minus weight wait this part honestly wait and the days lead to minus one because you start another day you go to this i mean yes another day but you still have to put this package in this way in the new day if you want yeah so the remaining is the capacity manage the weight okay because you are in the loop oh i see we will not recalculate this weight again so we need to change the way i see so and then until so we do this until the stage in here yeah we can do it here too right yeah so you can delete the line in the ship or not okay so maybe you add a indexing the 9 53 and every time in the end of the in the end you is less than so if how do we know is true though in what sense will return true written force and if the index is equal to the yeah so if you if the index is equal to the weight because you go to the way it's going is finished yeah it's finished so it's true it's okay it's our first try so i don't know because oh okay his weights right wait six times six wait what's your 65 so what happened here can i find simple index oh okay so it's because it's outside the loop because i define index inside this loop yeah this one don't work in java all right so it's wrong but expects is expected we got 55 the expected 15. is the max capacity okay so this one don't work let's check you can try with the temperature yeah i want to try with the example so let's see let's lose this example so can you add some print oh print we can print our ink decks or bring out the remaining yes we can print on the remaining me okay mid is here oh wait uh let me just pre-on wait uh let me just pre-on wait uh let me just pre-on me first it's confusing 32 44 50. which means even for the 32 it's facing it doesn't work so we need to factor the function into the segment function and we try to use the mean that can certainly true and try to understand the way it could retain force okay so if the min is 32 right remaining is 32. so weights index so we go to the loop and then so this is yeah this is five the index is zero less than the length what's net yeah okay f remaining yeah remaining right now is 32 is greater than zero so we said remaining so remaining equal to 32 minus one right yes okay and then yes so i just try to so we have one two three four five six seven eight nine ten so it's 22 so the first day we can send is one two three four five six seven yes the rondo see and uh yes we can go to the six seven i think because we have the capacity 32 okay so the first day we can send it to seven and the second day we can send eight nine ten but specific example here should be like this yeah because the capacity is 15 here but we use the same example right yeah but for us we use the capacities setting to you now we try to check if the setting is worked okay so if we set it to it works we will find in the left so the answer of this check needs to be true because the 32 straight it should be worth and can i just choose screen okay just look at the cold in the 9 18 something yeah okay the on bottom 73 and 74 can you just print the index maybe we need to use index minus one but you can run the code and do this yeah wait so whenever we run the index ah because you start the index every time in the 61. oh okay so it's 10 plus 15. it's still wait so it's 10 so never updates with what okay so here is 10. here is always 10. so which means it always returns true for these questions okay so why is 10 so it's should i print it put it inside a loop right yeah it's always true when it's always true let's put it inside ah okay because the loop is running inside right okay yes so yeah and the ear fit and the if is out of the well but in the forward yeah so we need to finish the well and yeah because you need it you're out of the way i think dude yeah what is it okay because it's not the same lines okay oh missing written statement because he said we don't have returns yeah i think you can say written for us same okay so it didn't matter so why is always 10 i think we can look at it look at the solution because like we don't want to waste time right like i think we are pretty close very close but something is wrong in this thing yeah i think it's just to check the first function yeah i think it works first function definitely works but this is wrong like something wrong is here the logic some somewhere let's look at i don't wanna like i don't wanna take much too much time so you i want you to go too so i want you to can be able to talk today the same dude i don't like him hold up let me see if there's better solutions oh i think i found a better solution this guy is good here oh no yeah no sticking here so this question can you see the screen yep okay so this is a this is the question but here is the example okay so yes you see his function yeah which is see we did this one we did the exact yeah we did the same one see like right here this thing so yeah capacity what's capacity is mid okay so you don't need the array you just need the capacity um yeah because the array is already i mean yeah if you define this function in this function oh okay so he defined this okay guys yes it doesn't change so here days starts at one why yeah because he said it's the first day okay the total and the total is almost the same thing all these things oh it's different so he calculated this he calculated the page and he want to check if the day is passed past this thing yeah okay so we wait what's this yeah so for the first part okay just here yeah so you can call the first day in today yeah there is one wait which one wait what you want to say you need to use no i define here oh it's different though it's different i see yeah thank you it's different so we look to the weights and we so we use total is a total class equal to great truth and the eve totally it is heavier than a capacity we need to increase the date and then we need to do what to the total why oh uh we check if it we check here do we add the first one later here we check if day is bigger than this right this we check if it's too heavy right yes oh whoa is it running oh we got it bro wow it's just the second function we've got some pokemon yes just this we got a first part already but just like this thing is hard this thing checks wow
Capacity To Ship Packages Within D Days
flip-binary-tree-to-match-preorder-traversal
A conveyor belt has packages that must be shipped from one port to another within `days` days. The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days. **Example 1:** **Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5 **Output:** 15 **Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. **Example 2:** **Input:** weights = \[3,2,2,4,1,4\], days = 3 **Output:** 6 **Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4 **Example 3:** **Input:** weights = \[1,2,3,1,1\], days = 4 **Output:** 3 **Explanation:** 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1 **Constraints:** * `1 <= days <= weights.length <= 5 * 104` * `1 <= weights[i] <= 500`
null
Tree,Depth-First Search,Binary Tree
Medium
null
62
welcome back friends today we are going to solve lead code problem 62 unique paths so before we start looking or details of this problem please subscribe to my channel i often create good videos about lead code java solutions and java j2 related interview helpful videos so please subscribe to my channel it helps the channel to grow so let's you know look details of this problem so a robot is located at the top left corner here uh of m by n grid so this one is a three by seven grid right three rows and seven columns and uh the robot can only move either downwards or right at any point in time the robot is trying to reach the bottom right corner so right robot want to reach here how many possible unique paths are there so we have to find out the possible unique path so let's just take this example over here so for example what is a possible unique path means one of the possible path is like this like robot can go rightward and then downward so this is one possible path other possible path is robot can go downward and then all the way towards right so it will reach the finish right so we have to find out all the possible paths that are there in this matrix right so we are going to use a technique called as dynamic programming where we will form a dp array so our original matrix is given is a m by n matrix right so m rows and n columns which is a three rows and 7 columns right here so we what we will do is we will in the beginning create a dp array and dp array is again of the same size of the original matrix so this is our dp array and it will be three by seven right means m by n basically here m is three and n is seven so we created three by seven uh dp array and in the beginning everything will be zero in this array right so uh now the robot is allowed to go either towards right side or downside right other directions are not allowed for the robot to go so if robot is starting from this position and want to reach this cell it can go like right word and it will reach here right so there is only one way to reach here only one path is there to reach to this cell similarly if it goes straight again on the right side then it will reach this cell so there is only one possible way to go here right like this if robot goes to it then only it will reach here so it is one way only similarly for these cells there is only one possible part to reach to this cell for the robot right like going right basically so this is the way we will be populating the first row of the dp array so as you can see we have populated here first row all the values will be one because there is only one way to reach to this cell for the robot basically as i explained right it will just go right word and it can reach to this cell similarly if robot want to go and reach this cell it has to go downward right so there is only one way to reach to this cell and there is only one way to reach to this cell so we have just marked this as a one for the first column right so we have populated the first row and first column of the dpm dp array right so now we have to populated populate the dp array for the remaining cells right so what it how we can populate the dp array is whenever we are at any specific cell we have to get some of the diagonal cells so for this cell two the diagonal cells are these right these are the diagonal cells so as you can see it is one plus one that is equal to two so similarly for this cell the diagonal cells are these cells right one and two these are the diagonal cells so it will say one plus two is equal to three similarly you we can calculate four three plus one is four plus one is five plus one is six plus one is seven so we have populated this row right all the way similarly we can start now populating the last row uh this way so this is the cell we are looking at so we will have to get the diagonal sum of the cells so 2 plus 1 is equal to 3 right so we just put 3 here so 3 plus this 3 6 plus 4 is 10 plus 5 is 15 plus 6 is 21 and 21 plus 7 is equal to 28 so our last cell that we got for this dp array is a 28 so 28 ways are there unique ways are there for the robot to reach to the last cell right from the start point so if you look at the answer then it will be 20 at right so this is how the 28 came from so we will populate the idp array gradually first we will populate the row and then first row and first column and then we will populate the remaining cells so let's take a look into the details of the uh you know of the solution that i have here so let me just quickly show you that code so as you can see here first we have created an empty matrix because we have been only given you know m by n size so we just create an empty matrix here of the size m by n and we are passing it that matrix to our total paths method so total paths method is this one and we will just you know get the m and n here which is size of the matrix and we have created a dp array of the same size here right and then as i said you know we will be just moving like a downward there only one way to go to the downward so we are populating first column here right i zero means uh it will go like all the rows will go from 0 1 2 3 like that so dp of the first column will be 1 and dp of the first row also we populated as one right so that's what i explained here all these ones and all these ones so that's what we are doing here and then we will iterate through remaining cells so remaining cells will obviously start with one right so i is one and j is one because first row and first column we are already done so now we are doing the remaining cells so what we will do is we will um get the sum of the diagonal cells basically so for every cell this is the diagonal cell for example for this cell 2 if we are looking at this cell 2 then these 2 will be the diagonal cells here one this is the diagonal cell so in the logic we have said that i minus one j and i j plus one so this is what we will do the summation and we will assign it to dpij basically and at the end we will just return the last cell basically which is right most cell right so uh if let's just execute this code once and make sure this is working so three by 7 is given us which is 28 and we will take 3 by 2 also the other example that they have given us so we will just run the code quickly and make sure our code is working fine with this so we got 28 as i explained here right 28 ways and for the other one we got three which is also correct right three so now we will submit the code so the code is 100 percent faster so this is a maximum like faster code right so this is the way you can solve the unique paths for robot from start to end using a dynamic programming approach you can just create a dynamic programming array and you can first populate the rows this row first column and then you can populate the remaining cells right using the diagonal summation of diagonal cells so uh as i said in the beginning of the video i often create lead code solution videos using java and java j2e interview related helpful videos so please subscribe to the channel it is really important for the channel so please subscribe thanks for watching the video
Unique Paths
unique-paths
There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The test cases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** m = 3, n = 7 **Output:** 28 **Example 2:** **Input:** m = 3, n = 2 **Output:** 3 **Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down **Constraints:** * `1 <= m, n <= 100`
null
Math,Dynamic Programming,Combinatorics
Medium
63,64,174,2192
101
foreign so let's code so just a second okay so what do i have to do is this sorry okay so substitute if root is equal to null then obviously return okay let me do this full screen return solve okay root left comma root right again root left or root right function star r2 and then if r1 is equal to null and r2 is equal to null though base conditions return true if r1 val is equal to r2 val then sorry if they are not equal then return false okay now the last condition will be the recursive choices let's run this code hope everything is fine okay something is wrong just let me see okay r1 left okay sorry are too late now let's run it again okay it is fine let's submit it okay so it is done so it's nothing hard here to understand uh i will suggest you can read the solution block you can do it using a queue so that's also an option so if you understand this understood the solution then it's great so thank you
Symmetric Tree
symmetric-tree
Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center). **Example 1:** **Input:** root = \[1,2,2,3,4,4,3\] **Output:** true **Example 2:** **Input:** root = \[1,2,2,null,3,null,3\] **Output:** false **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `-100 <= Node.val <= 100` **Follow up:** Could you solve it both recursively and iteratively?
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
87
hey so welcome back and this is another daily kill prom so today's March 30th and the deadline for today's problem just passed so I hope you did a good job with it but um yes let's take a peek at what today's question was so it was called scramble string and oh I don't want to give the answer just yet and so it's actually a dynamic programming problem and I'll be giving you a top-down like memorization giving you a top-down like memorization giving you a top-down like memorization solution for it and so what you're given is two strings here S1 and S2 and we're going to scramble say S1 in this case and we want to see if we're following this particular kind of scrambling pseudo code you want to see if you can formulate S2 to see if S1 is I guess could be a scrambled version of S2 okay and so the logic here is recursive logic and they're very explicit about it that's why it was very natural to come up with like a top-down minimization up with like a top-down minimization up with like a top-down minimization solution and so first case is you want to say okay if the length of the strings are one then just stop there and return true okay and so then following that okay well if the lengths are greater than one then we're going to just follow these three steps here and so we want to divide it at some random index so it could be between 1 and the length of the string kind of minus one because we need at least these two sub strings that we're splitting in ha or not in half but splitting into two parts to have a length of it Greater Than Zero and so they have to have at least one character in it and so the second part is we can either two options here we can either swap the two substrings that we just kind of split at a random index or we can keep them in the same place and so from there you're just going to kind of keep recursively performing this call until they have a length of one okay and so let's go ahead and implement this so we're going to return the result after calling our DP function that we're going to implement and so we're just passing the two strings that's given to us so let's define our function with S1 and S2 again so we're going to want to Cache this result so this is going to take up a little extra space but it's going to give us that uh performance benefit in terms of time so it will reduce their time complexity plus only code you get like a tle or I can run out of time if you don't do this so and for the solution to work you have to do it and so from there what we're going to do is okay we're going to return true if these two strings match because then we know that yes they are in fact it would be scrambled such a way that they equal each other and so if that's the case then let's return true immediately we don't have to do any more work this is our base case and so from there what we want to do is if none of these paths work there's kind of four paths that or more than four paths there's several paths that you can go down either by you split at a particular index and then you keep them in the same um and then you don't swap them or you split them at a particular index and swap them and so this path these two paths that you can go down kind of recursively happens and it can go down you know either way at each iteration and so from there what we want to do is say okay where can we split at well we can split up between I from 1 to the length of the string of S1 so I from 1 to I didn't type this out enough in range from 1 to the length of the string so this is all the places where we can make that kind of partition at and then we say okay well what if we split from this string and we don't swap the ordering then well we say okay if S1 from I onward so you split at this particular index and we want to compare then the first Chunk on the left hand side and so what that would be is this and we compare it with S2 so we haven't swapped the order and we would just want to compare the first chunk that they equal each other and so then we're also going to want to do the same thing but for the opposite side of this chunk so all the way up to that particular index that we're splitting at and this is the case then we want to return true and then finally we also want to check the opposite of this case where well what if we do actually um swap at this particular index and so from there you do negative I and so this is kind of saying okay where we compare everything from I onwards so like from two onwards and then we compare the swap from like everything up to two okay so let's take a peek at that and so same thing here we want to reverse this logic great sometimes I tip it out wrong yeah and that's uh today's daily Eco problem so I totally get where it's kind of a hard problem because well there's a bit more logic to this question like the explanation isn't quite straightforward there is much code that you have to write behind it but it is like a dynamic programming solution and you do actually have to had some memorization in order for it to pass and so this just recursive relationship is quite complicated but when you write out the code it's very simple like having to read a developer skill that wrote this like I think it's very understandable um it's more for me was understanding the relationship of adding this negative I here and comparing with the other half when you're performing this case where like hashtag is swapping the ordering that took a bit of effort and you kind of have to draw it out that you know the slicing that you're doing on these arrays but yeah so this is today's daily Lico problem and I hope it went well for you so have a great day thanks for watching
Scramble String
scramble-string
We can scramble a string s to get a string t using the following algorithm: 1. If the length of the string is 1, stop. 2. If the length of the string is > 1, do the following: * Split the string into two non-empty substrings at a random index, i.e., if the string is `s`, divide it to `x` and `y` where `s = x + y`. * **Randomly** decide to swap the two substrings or to keep them in the same order. i.e., after this step, `s` may become `s = x + y` or `s = y + x`. * Apply step 1 recursively on each of the two substrings `x` and `y`. Given two strings `s1` and `s2` of **the same length**, return `true` if `s2` is a scrambled string of `s1`, otherwise, return `false`. **Example 1:** **Input:** s1 = "great ", s2 = "rgeat " **Output:** true **Explanation:** One possible scenario applied on s1 is: "great " --> "gr/eat " // divide at random index. "gr/eat " --> "gr/eat " // random decision is not to swap the two substrings and keep them in order. "gr/eat " --> "g/r / e/at " // apply the same algorithm recursively on both substrings. divide at random index each of them. "g/r / e/at " --> "r/g / e/at " // random decision was to swap the first substring and to keep the second substring in the same order. "r/g / e/at " --> "r/g / e/ a/t " // again apply the algorithm recursively, divide "at " to "a/t ". "r/g / e/ a/t " --> "r/g / e/ a/t " // random decision is to keep both substrings in the same order. The algorithm stops now, and the result string is "rgeat " which is s2. As one possible scenario led s1 to be scrambled to s2, we return true. **Example 2:** **Input:** s1 = "abcde ", s2 = "caebd " **Output:** false **Example 3:** **Input:** s1 = "a ", s2 = "a " **Output:** true **Constraints:** * `s1.length == s2.length` * `1 <= s1.length <= 30` * `s1` and `s2` consist of lowercase English letters.
null
String,Dynamic Programming
Hard
null
93
Hi gas welcome back to my channel so today our problem is restore ip address so what have you given us in this problem statement here have given us a sting s in which what is there are only digits and what you have to do is to donate here All possible valid IP address can be formed by inserting dot in S OK so what you have to do here also is basically divide S into these 4 parts OK and how to divide it by inserting dot and you will return valid IP address here OK So, if you have to return as many as possible, then what is a valid IP address? We understand what is given here. This valid IP address consists of exactly four integers separated by single dot H. Wait for it between zero and two five. Five inclusive i.e. whatever your five. Five inclusive i.e. whatever your five. Five inclusive i.e. whatever your digital number is, not digital, whatever your number is, it will be your number, from 10 to 25. The number here should not have leading zeros. Single zero will do, but there should not be any leading 0, so let's take an example. Let's understand through these two, see what is your valid IP address, how is it zero here but it is single, it is not leading anyone, here you are a zero van, that is, it is in the range of zero to 255, this is fine. And this is also whether yours is in the range of zero to 255, then both of these are your valid IP addresses. Now look here, zero is single, it is correct, but here zero is zero van, i.e. here, if the last one is zero, then this is i.e. here, if the last one is zero, then this is i.e. here, if the last one is zero, then this is your valid. No, ok why is it not valid because here it is 3.2? valid because here it is 3.2? valid because here it is 3.2? What should we do? This digital number should be from zero to 255. It should be 3 1 2. It is not valid here and look here if there is a special character then it is invalid. Okay, so here science has given you that all the characters in the string are your digits, there will be no special character, you will not get it, okay, but here in the example, I have explained to you that this is your immobility. Okay, so what do we do, example. Let us understand the problem through this, how can we solve it? What is the problem? I hope by this time you must have understood what the problem is. Look here, what have you given yourself a consent for? Tomorrow the length will be till 20. We don't even need to go till 20. Okay, if we have been given till 12, then what can we do? We can change the invalid IP address. If 12 is occupied by one person, then we can't do that now. You will ask how to see, this is your example, we take it, if there are how many numbers here, there are 1 2 3 4 5 6 7 8 9 10 11 numbers, here there are digits, if this is here, what should I do here, divide 255 into 11135 like this. It is possible that even if the fourth digital people become invalid like this, because 255 people, anything, 10 people, whatever, there will be more than 255, neither will you get invalid like this, right, even if you have done it here, then you will be saved here. If it remains till 12 then what will you do now? If 12 remains digital then people will divide it by three. Nah, divide it by three. Then later you will see that now my number is not more than 25 type but before that you will come to know that brother. Even after dividing into three, if our number is left, then it will be invalid, if we give it a party, we will divide it into four, then what will happen if you do it in four, we are making one seat on 25. For this you are confirmed right, so what will happen here if it is till 12 then we can decide three each and after that we will see whether it is more than 255 or not if not then now I am valid if If it is within 25 then it is valid and is exiting it but if you already know that we will take the board then it will exit at 25 then only these will be valid, otherwise we will check beforehand. If the length of my string is more than 12, then we will simply turn the IMT vector of steam. Why because we can't make it, that's fine. You know this. Now let's come to how we will solve this problem here. What will we do, make disinentary and show it to you, so let's take black color, first take the example 2552 5113 5, okay, after one digital, okay, I have done it, then you will say, I will apply it after 25, you will apply it after digital, okay Yes, that is also correct, then you will say no, I will put it after 255, okay, you can take the fourth part in three parts, are you sure about this? Four people have been invited, so why will we take the fourth part? After that, we will be here. Look, now you will not find valid in all of these, so what should I see here, this is a very long decision tree, so what do we name, let's understand before moving ahead, who can I get from where, who can I get, okay so Here you are, look, you have divided it into one part, now you are left with 10. Even if you divide it into three parts, at least one digital will be left, your three digital people will definitely be divided and you will be left with an invalid. You are never going to get valid, how come you have divided it here, now this is what is left, this is a child, this much is left, so in future, you will not get valid anywhere else, otherwise this road will be your own block. It is over, there is no need to look further, we are fine, you will look further, you will not get a valid answer anywhere, now even in the case of 25, let us see what we will get if we take it in hand and move ahead. So you are five, here you have divided the child, come on, you will get the next one in three, so here you are seeing that you will get 525, you will get 511, you will get 135, this one is in your range, both of them are from the range. If you are going out then here too you will never get a valid answer. If you don't get it then now you can get it in a case in 255. So we will now take a decision from here. Now from here too now three decisions will be taken by the people. Now what should I do from here? 255 I have put this much of the dot, now what do I do? I have put this far, now I will put the dot after you. You have taken a decision, then you have taken the decision that I will put the dot after your five, okay then? What do I do, so you have done it in three parts, now what about us here, if you have done till here, look at this one, let's see what we can get in this, but he will get invalid because our decision tree. If it is longer then we will see only the valid one. Here we decide whether it should be expanded further or not. Okay, so after you, if you put a dot here, you save this and this, then see it will become extra digital here. In one, only four A's will be taken, so if we move ahead from here, we will not get valid, we will not get it anywhere, now let us see in this one, if we take 25, here we have taken dot, then we divide it into two parts in three times. If we do this, then it will be 5/1, it will be 135, do this, then it will be 5/1, it will be 135, do this, then it will be 5/1, it will be 135, so here also you will never get it, okay, then we will see further, why let's see here, for this, let's see the decision here, because here you will get it, if you If you do it three times like this, then what will happen to you, will you get valid? Now you decide once that you five dot, after five, what will I do, I will take dot on van, okay then you here dot after 25511. I will take it, okay, now here you have taken it, okay, after the van, you have taken the dot, now see what you have done here, you have divided it into 3 parts, the fourth chapter, just this whole number is left, so in the fourth part, you have four digital people, so here Will you ever find water on this path? Will you ever find a belly dancer? What won't you find? So here we will move ahead and see. Okay here let's see van dot okay van man dot put here 35 what can happen next. In this you can take two decisions you guys 255 25511 ok what do you do three dot take three dot if three dot is taken then you have taken it in four parts ok but you have taken it in four parts here you have divided it into four parts Have you taken it, but now this one that has come to you, this one is here, has not reached the last one, has not reached here, that is, even here you have not got a valid answer. Look, you also have to keep in mind that it should be divided into four parts. And the total divide is not that we divide it into four parts on the half itself, here we have made three dots on it has been divided into four parts, but I am yours right here, I have not reached till the last, I have not done all my things. So even here you will not get a very good answer. Okay, now let's see what is there here. Now you have 255 25511. Now you will take both three and five together. You have taken 35. You have come to know. Hey, here is the number. It is not only that, this is your four, all the numbers have been divided into four parts, how are all the numbers, because you have reached here, after five, you have reached here, that is, you I = has here, that is, you I = has here, that is, you I = has reached, the sting has reached further to the dot size. Okay, and our part has also become four, so this will become our base condition. Part four has become and I, we have reached the size, that is, this is our answer, we will take it and store it, that is, we will get this answer. Now look here, what will you do here too? Three decisions people, you will do three dots, put two dots after three, if you put dot after three, then your five is left, this five is left, you are here, you are divided into four parts. Gone, won't get it from here, okay, what do we do now, what do we get, we have got it, right, now we have got this, so what will we do, what will you do, store it, okay, done, now ahead, there are three people here. You want to take three, but you do not have three, the right is not there after 35, otherwise it will not be made here, there should be your length, here too, there should be three, to take three, so till here I got 35. Till the answer is this, isn't it your 135, have I made some mistake here 11 I have taken this one and this one I I I see okay look here what I had here was divided into three decision parts and right here This is now after the van, this is yours here, if your eye has reached here, otherwise since it has been divided into four parts, your eye has reached here, otherwise it will be yours valid, no, what will we do next, we will take 255 25511 after that we van three Okay, we will put a dot after 13. If we put a dot, will we get this invite or not? Because it has been divided into four parts, but it has come here and has not reached the dot size. Your index is here in the last place. It's okay then it will be yours otherwise what will happen here 255 Here we have reached 1135 last, we will put a dot here because here we will put a dot, if we are storing it, then we will remove the last one, we will remove the last dot, okay So what will we do in this way, if we decide here then what will be our base condition? We will make the base condition that if we have reached the i dot size, okay we have reached the last and we have also been divided into four parts if If both the conditions are met, what should I do? Store the string that we have created in a vector because we have to entertain the vector oxide. Right, if it is possible that you have divided it into four parts but your size is not till the size of i dot. The string has not reached the dot size. This is where you have divided it into four parts. Is that your valid answer in the middle or not because you have to divide the string totally into four parts. So what will you do, you will simply track it from here to here. It will go back to the previous function and then it will move forward. Okay, this way we will reduce it, so let's see the code too. So see what is here, what we will take is a vector of steam where we will finally store our answer. Okay. And here what we will do is see what we have here is to be divided into four parts so at least there should be four digitals so give this lace if it is four then if this is your garden then it is 12 then return answer ok Whatever answer is golden, make it a adverise. Take a sting time in which what are we going to create? We are going to create a valid IP address, let's take it. There is a solve function which we will call. Our answer will be stored in answer. These 10 will fast in this. This is your index, this is your part, into how many parts it has been divided so far and the string that you have given in your original is the one. Now let us come to the solve function. Okay, let us come to the solve function. Here we will write the base condition S dot size. K is equal to I and you have divided in part four, so what is it, what should I do in the answer, push is your temp o sub string, here I have made a mistake, yours should be from zero to temp dot side minus. Van is fine, this should be yours because we have put a dot in the last also, because see in this, what will we do in the sub, we will put a dot in the last, which you have submitted, I will show it, I think, what will happen here. Look, this is your base condition, what will you do, you will store 10 substrings from zero to 10th dot of size 1, that is, the length should be this much. In the last dot, we store it here, so we have to remove this string, neither this dot. To delete, we have taken this here, okay, I hope you have understood, then we have stored it, now we have to back it, so we will return to the previous function, okay if this condition is fully fulfilled by you. S becomes equal to dot size i and part 4 or means if part four is done but you have not reached i and size then it is ok if i has reached dot size i.e. you have reached sting and size i.e. you have reached sting and size i.e. you have reached sting and size but not divided into part four. If this is happening then understand that valid is not received, simply return it without story, so if this condition is happening here, then I will store, will not adrevise, will go back. Okay, if either of these two is getting full, adrevise, what will we do? Three distances will be taken, three decisions will be taken, whatever is the answer in the solve function, C in 10th i.e. you will do whatever is the answer in the solve function, C in 10th i.e. you will do whatever is the answer in the solve function, C in 10th i.e. you will do first sting, after that you will put dot I + 1, you will do part van i.e. you have done one part, you I + 1, you will do part van i.e. you have done one part, you I + 1, you will do part van i.e. you have done one part, you will do part plus van like this, then it is fine if yours is sting. The dot size is up to i + 1, if it is greater, then size is up to i + 1, if it is greater, then size is up to i + 1, if it is greater, then what should we do, we can take the next two strings, that is, after the next two, after the two digital ones, we will put a dot, okay and it should also be valid, so what should be the valid, whatever you make. You are making a part, it should be valid, how will you check that, we have created a function for this, what you will do in it is you are sending the part and seeing if it is of van size then return it, you are fine. Yes, if it is more than the van side, okay, if yours is &gt; 3 is more than the van side, okay, if yours is &gt; 3 is more than the van side, okay, if yours is &gt; 3 and your leading digit is zero, then return will be false because the part of the posting that you are seeing should not have more than three digits. You know this and If you know that its leading should be zero, it should not be there. If it is not there, then in that condition, if both these conditions are being fulfilled, then Dan will fall foul. What will we do, we will change the string into number, will we also check this? Is it exceeding 255, is it greater than that? Then we will return false. If this condition is not fulfilled then finally we will return true. Okay, this is our is valid, this function will check that whatever part we are creating. Yes, it should be valid for us, okay then it should be valid, what will we do after that, in 10th, we will do S dot substance I, we will take two digitals, here there is two length, we will take two digitals, after that we will put dot, okay, we will do I + 2. Now you are already put dot, okay, we will do I + 2. Now you are already put dot, okay, we will do I + 2. Now you are already taking two digitals, so you will have to skip the index, you will have to pay I Plus, you will give I Plus, after three, you are putting a dot, after three, then here you can check the part which you are making. Going, if it is valid then what will we do? Solve answer: 10th plus s substance should be like three, answer: 10th plus s substance should be like three, answer: 10th plus s substance should be like three, after that dot i plus three, that is, what will you do to the index. If you are putting dot after three digitals then you will see next to it. No, that's why you will put I plus three, here there will be part one, that is, you have divided it into one part, then we will do it like this, okay, and finally whenever our base condition is fulfilled, then the answer will start like this Pankaj We will call, our answer has been stored, we will finally return the answer. Okay, so I hope you have understood this and what will be its time complexity. Look what are you doing now, you are taking three decisions every turn, right. If you are taking three decisions then what will happen here, three here, how far can digital go, can go till 20, but till 20, we have already checked, if till 20, if we go till 20, if we have the length, then we will go at the same time. If we are doing it, then whenever this condition will go, this much will happen, it is sure that it will happen only till 3:12, only then we will sure that it will happen only till 3:12, only then we will sure that it will happen only till 3:12, only then we will go, okay, this is done, in a way, you can say that there is no constant timing, right? Only then will we complete this decision tree, this back tracking etc. How will we call? Right, what will be your time? So I hope you have understood this. If you liked the video, then please like, share and subscribe. Bye, thank you. You
Restore IP Addresses
restore-ip-addresses
A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros. * For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addresses, but `"0.011.255.245 "`, `"192.168.1.312 "` and `"[email protected] "` are **invalid** IP addresses. Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order. **Example 1:** **Input:** s = "25525511135 " **Output:** \[ "255.255.11.135 ", "255.255.111.35 "\] **Example 2:** **Input:** s = "0000 " **Output:** \[ "0.0.0.0 "\] **Example 3:** **Input:** s = "101023 " **Output:** \[ "1.0.10.23 ", "1.0.102.3 ", "10.1.0.23 ", "10.10.2.3 ", "101.0.2.3 "\] **Constraints:** * `1 <= s.length <= 20` * `s` consists of digits only.
null
String,Backtracking
Medium
752
225
in this video we're going to look at a legal problem called implement stack using cues so the goal is we want to implement a stack data structure which is a lasting first out so the last element that we inserted onto the stack is the first one that we remove out of the stack so we want to implement stack using cues and the goal is one implement stack that supports all those functions that a normal queue can have right so in this case a queue has push pop top and empty right so basically push we push items onto the top element on the stack right and pop basically remove the element on the top of the stack and returns it and the top basically returns the element on the top of the stack we're now removing the top item which is returning that item um off of the uh on top from the top of the stack right and we also have a boolean method which basically returns true if the stack is empty return false otherwise and it's kind of similar to how we did it in the implement queues using stackdish problem we basically have to support those methods um and in this case you can see we have an example right where we adding items onto the stack right and we if we were to remove right the top or pop we are removing two right because two is the last element that we inserted off the stack and if we check to see if it's empty in this case it is uh false because we still have one elements left in our stack right so that's one so to solve this problem uh we can use two cues to implement stack so the idea is this so if i were to have those items here and we want to remove the top items that we have on our stack so in this case we have a queue where we have one two three and if i were to remove this item or remove the item from the queue in this case it's gonna be the first item so in this case we're just gonna get all the items that we have in q1 added on to q2 so this will look something like this because we're inserting last right we're inserting from the back so when we enqueue right we end q on the back so one and two and you can see we get the last element in this case after we insert one and two we get the last element so we can just remove that element where peak the element right if we were to remove this element we're just gonna remove it um and then we're just going to swap the order but if we want to pick the element in this case we can just return this element and then we can just insert this element back to q2 and then what we're going to do is we're just going to swap the order so in this case we're going to get q1 points to this cube and q2 points to this q right here so that we have two queues and q1 is in charge of pushing items right getting items onto the onto this uh stack data structure and uh q2 is there to basically a temporary cue that basically stores uh temporary elements onto the queue so that we can uh transition or uh points or swap their uh swap the pointers point to a different cue right so at the end you can see we still back to the state where we have one two right so we're just removing one items off the this stack the structure which is the top element that we remove so in this case if we were to pop items out you can see the time complexity in this case is big of n we're in this number of items that we have in our cube and if we were to add items onto this stack to the structure we're adding inserted to the back so we're basically um getting a constant time complexity for insertion so this is basically how we use two cues to solve this problem so let's take a look at how we can use only one cube to solve this problem so the idea is pretty uh is the same like if we were to remove element three out of the stack basically we're going to do is we basically insert these items onto the queue right we insert last and then what we're going to do is we're going to rotate this current q right the goal is we want to rotate this current q um basically k number of times and k is basically the size of the current queue right so in this case we rotate so we remove the top element out of the um out of the uh sorry we remove the first item that we have in our queue and add it on to the back so you can see we have two added onto the queue and we have one remove one and we get one added onto the cube in this case we have three two one and if we were to remove item we can just remove the first items that we have right so you can see here we basically remove two and remove one so we basically uh rotate two times okay and if we have three elements in the stack we would basically rotate if we have three elements in the queue we basically rotate two times and in this case we just have to return or peak the last element that we have um in our queue right so this will same thing if we were to remove items it will give us a time complexity of big o of n but the space complexity in this case is going to be constant so to do this in code we're going to use a cube and uh basically we're just going to push items onto the queue then once we push items on the queue we're going to rotate the queue right um k minus one times where k is basically the number of items that we have in our queue and we rotate that number of times so that the last element will be the first items that we have in our queue right so in this case we insert q dot add x so then we have size right so the k is equal to q that size and we're going to iterate uh okay number of times but in this case k minus one right so in this case it's going to be uh k minus one times so that the last element will be the first items that we have right so in this case we're going to say integer first is equal to q dot remove and we need to add this element on uh back to the queue right uh to the back so q.a first so q.a first so q.a first so we basically enqueue this item and then at the end we basically rotate the q k minus 1 times and if we were to remove in this case we can just remove in constant time complexity so in this case we can just remove return q dot remove right and if i were to get the top items that we have in our queue or the top items that we have in our stack for the first item in this case we're just going to return to that peak right because every time we add items in we already rotate the uh the queue and for check to see if it's empty we're just going to return if q is empty okay so now let's try to run a code and let's try to submit and you can see we have our success
Implement Stack using Queues
implement-stack-using-queues
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`). Implement the `MyStack` class: * `void push(int x)` Pushes element x to the top of the stack. * `int pop()` Removes the element on the top of the stack and returns it. * `int top()` Returns the element on the top of the stack. * `boolean empty()` Returns `true` if the stack is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a queue, which means that only `push to back`, `peek/pop from front`, `size` and `is empty` operations are valid. * Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations. **Example 1:** **Input** \[ "MyStack ", "push ", "push ", "top ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 2, 2, false\] **Explanation** MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `top`, and `empty`. * All the calls to `pop` and `top` are valid. **Follow-up:** Can you implement the stack using only one queue?
null
Stack,Design,Queue
Easy
232
799
Everyone Today Will Be Solving This Champion Star Question Bed for the question of list to demand challenge so let's get started in this question in this tag classification of pyramid against forest who has one glass to control is strong glass and should contain dowry And whatever is the roll number, the number landed in that row and Larsen and Toubro are Mittu, the first to leave is the third, there will be friends in the hunted, in the middle of the darkness, the glass holder, Apollon Cup Champion, there is a cup champion in every glass, okay, late evening, champion intention. Champion is point to the class first class 8 stop looking first class initially we people champion and do while the top most class fool any access liquid code will pay for equal to the glass immediately to the left flashlight off but okay so it means This is something like the class in which the MP board is doing is a detox class, if the time is the first thing then it will store that tweet in itself, this is fine and even after that, if there is some champion left then whatever is left is his horoscope part left. The match will come and there are equal parts and the exams page were two, this top champion is the first one, but we support the two wires, so in this I would have got it, after all, it is okay, one text would have been saved, one meant a week, but where do you keep the cigarette? hai to me dost classification fool any access champagne will fall on the left and right of two slices and soul sahii baat hai a glass and bottom row health tips 1000 which is sahih and juhi chawla stroke owner this last thi which this cross If the owner is the last one, then if he gets access to the champagne, the waiter will select the top one in the hotspot class. This is the thing. Okay, so you have a question whether it is the Nano or the champion which is initially in your question. The code will be there, how many sets will be on the pin. We have to tell the people and the query roll and the query glass are nothing that they are the Romans particular and the class is the glass number, so they have to tell that till the time every class which is CID from Baroda, then how much champagne is there in that particular class at this time. If you want to tell us then let's do justice to this white gold and then let's take interest in the program. First take one minute from you and let's do it. In this, I have a paste of 1 minute in every class, one is about the story. How much more is left in myself, now that means there is nothing left, zero, if nothing has happened to me, then there is no need to do anything else, it is fine and if there are units near the attacks, then draw the free mode, first of all, let's do this volume, zero, I Whatever M is, it means in the cost, he will break it himself according to the calculation, then how many people will the child have, 52 units, we are two cup champions left, so I will take half and go away, if the base right does not go here, then half from here is fine. It will go here and half of it will go here so two said you as much as 133 1 rectangle and he got up and said ok so this is done Delhi will become 110 001 and now there will be nothing left, so either you are left with nothing in these glasses These three upside down glasses give a pick and an example of the present time, the little one who is big in front, let's try the wife at this time, so when we will support, then he can save himself completely from the tweet from here, now the decision of half idiots in the past is here and When you came here, then half of the four books came here and you are here now looking on the left, you are a barren person, two of you have come, you are one unit, one, this whole minute of puja will be taken by this one. The whole flower is unlimited, of course, how much cake is there, one is left, so now where is the half of the one left, is it okay and if you come here, where is God's half, the weight is far away, that 3.5 of a fresh one means half. The cup will also that 3.5 of a fresh one means half. The cup will also that 3.5 of a fresh one means half. The cup will also come here and the point price is fine, so that means wherever there is half cup, it is fine, so now if the cup is not completely full, then there is no single condition for overflow and whether you play it or not, this is a frill and it has yielded results. Practice Pura-Pura, the yielded results. Practice Pura-Pura, the yielded results. Practice Pura-Pura, the hero should be an extra in the films, as if the first screening of two units has come here, then he should become one, it is okay, one cup champion, and one jo bhakti huske half of it is here, the body and the hand, you will come here, it is okay. If half of the one comes here then the point will go to you and one said that this point has come here so in this case it is right that it is fair so if the point party comes to this one of 2.5 then it will be 2.5 but point party comes to this one of 2.5 then it will be 2.5 but point party comes to this one of 2.5 then it will be 2.5 but Yadav will have 38 people. If you look carefully, point five, the shopkeeper should say that point five, one, I am coming from here, zero to one, since when has this person been coming, the total in this will become one, meaning this compound is correct, it is the lineage of the people of Old Delhi, if there is no extra then overflow. There will not be some fixed white user point so the only thing to notice in this is that if any like if there is give one cup then if the accuracy in it is more Paul is getting champion only then it will overflow thanks to all ugh it will not happen okay so let's Kodak If it gets looted then it is ok and what is it, initially if we become total fennel then we do not take an average, those people take 0002 staff appointed person, they are western, that is why we are taking today match time because it is the giver, we people 20101 The comment is definitely not something, it is just a complete representation of Glass. Okay, so he is in China, so he will be given the Matrix Play Store. He was appointed mission director today, what is the name of the class, the products, the double of the scientist, the Indian horror show, the initials are his zero, okay? What do you do, what they saw is that they support the whole situation in the first glass of champagne, we are also animals, that is the first class, only the famous one, to fulfill whatever initials we have got in it, we watch this video. We were forced to flirt with others that this one was in the glass in a shirdi, initially everyone was okay with this, so we will report on this initially, so we have left first, now the rest of the classes will check what grade this guy is. Now, if we want, we can subject whole glass i.e. eggs, but that does not mean that every time we should stop the can subject whole glass i.e. eggs, but that does not mean that every time we should stop the can subject whole glass i.e. eggs, but that does not mean that every time we should stop the various classes, either they should fit the glass on the needy toe and take these symptoms of Lieutenant General Dhahi Vyas to the pimples. Shopping now We will check whether Malak is there in the current class. Shankar goes to one unit. If this is the maximum sample, then it means that if it is so then it is ok for the fruits. Now how much will be the overflow. In the left and right, they check that people have entered these tomorrow. How much will be the bubble overflow if it is possible to double, whoever we have, who is in history, it will be - 12 SIM will start and we will turn it off, it will be - 12 SIM will start and we will turn it off, it will be - 12 SIM will start and we will turn it off, okay - the ministry is on the other side to okay - the ministry is on the other side to okay - the ministry is on the other side to do that, the glass is there, divide it on one and the rest on the other divide, that's why If it is on the left side, you are fine from now on, whatever you told us, we put cloves in the pass, left, right, left, leftover, youth, plus, today, Shri Ram, take this year, okay, it is okay and will be taken in the torch light one too, plus one. This is the thing like if we had given a pun then its f10 is ok so this subscribe so here in the village and on and we will ask both the questions now we will turn off the gas ok so it will be curved so the book in the class is school that child is ok and this If you type, then it is more than double as it was and always set that from outside in both the necks that Ruknuddin, you are nothing, now you press that button, till then brother sent the request, whoever is a hero in many classes. A very good ko a very strong hai achh ok hai all earthling tits set2 ko luck solid loot hoge bhram hai hua tha inch ka sankalp hai problems internet nahi kar do jhala ok ba ok hai fidjit 15 minutes located in water point to on Facebook If there is, then see this snake in it that whatever it is that it will be blasted in a particular way, then it means that if there are more wires then there will be overflow, it will go here and there, it will not go, and one thing to pay attention to. The one was that the owner is falling into it from somewhere, okay San Pedro, as if he was unmuting Vanshi 2, then it can fall from multiple glasses, some classmate, then what he is doing as a total champion, keep adding, it is okay with us So that's why add this and what should be, so this is a test question. Okay, so if we talk about time and space complexity, then we have used a to-do vector, then we have used a to-do vector, then we have used a to-do vector, then the order of thumb and square will be tight. We will use its Tubelight. Now we used plaster to present class then space complexity will be there and there is difference and same time complexity also order fans up exit is going on twice ok end square complexity will be there because final end comment kamal can ask by doing 1010 glass Finally, in the case of Bigg Boss, the last class will be held, so both time and space will be the same to make 100 difficult, thank you send your feedback video, miss you for date videos on YouTube, please like video, a rally, motivate, quote in medium, more videos and Yes Thank You To MP3
Champagne Tower
minimum-distance-between-bst-nodes
We stack glasses in a pyramid, where the **first** row has `1` glass, the **second** row has `2` glasses, and so on until the 100th row. Each glass holds one cup of champagne. Then, some champagne is poured into the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it. When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on. (A glass at the bottom row has its excess champagne fall on the floor.) For example, after one cup of champagne is poured, the top most glass is full. After two cups of champagne are poured, the two glasses on the second row are half full. After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now. After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below. Now after pouring some non-negative integer cups of champagne, return how full the `jth` glass in the `ith` row is (both `i` and `j` are 0-indexed.) **Example 1:** **Input:** poured = 1, query\_row = 1, query\_glass = 1 **Output:** 0.00000 **Explanation:** We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty. **Example 2:** **Input:** poured = 2, query\_row = 1, query\_glass = 1 **Output:** 0.50000 **Explanation:** We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange. **Example 3:** **Input:** poured = 100000009, query\_row = 33, query\_glass = 17 **Output:** 1.00000 **Constraints:** * `0 <= poured <= 109` * `0 <= query_glass <= query_row < 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree
Easy
94
854
so welcome to this problem number 834 it is the case similar strings it's a lead cold hard problem and it's a problem on strings as the name suggests and as I usually say this is not a hard problem this problem just requires basic understanding of how you know things are did you know representing this problem into an easier format and you just have the answer right in front of you right so let's quickly go through so in this problem we are given two strings a and B and they are called K similar for some non-negative integer K so for any Nene non-negative integer K so for any Nene non-negative integer K so for any Nene or non-negative integer K their case or non-negative integer K their case or non-negative integer K their case similar if we can swap positions of two letters in a exactly K time so that the resulting string equals to B right so we just make a swaps of individual characters in a you get B right and what the question asked us to do is given two anagrams a and B return the smallest K for which a and B are K similar right you do an A and B and you just you say that you know you forgiven a they are find the minimal lowers web-shooter are find the minimal lowers web-shooter are find the minimal lowers web-shooter required for it to become be all right and given B what are the minimum number of swaps required for it to become a right that is the simple question so you know what is the thinking beside be behind this question the best way of doing this would be the thing this in terms of red tree and so let's you know basically a tree in which the first node is the you know there's no earliest I in the string play starting every subsequent the root nodes of those two other tree are nothing but just once swap away like the strings which is this one stuff away and the children of those node should be one stop away them will be once away from that word but gradually we make this tree and if you what we then need to do is we just need to BFS through the entire tree and find the LD string we want and then the height of the tree or the level of the tree will be the number of strap we require ID because each and every strap just like each and every layer just adds one sir it's just you know for example it's simply like let's say we have the string ABC the three would be so this is just imagine this is a tree the tree would be like C B a so we just wrap bigger a B and C then D will be a see right and it could be like also a CV like these are all valid various strings but so basically when you are given this input ABC and we see a b c here does not come in this enter string so at least the answer of this is not one like the minimum number of stretch is not fun but now i actually replace this then we'll have BCA and subsequently forever right but this came in the second lever then so too is the right answer because we required two steps book reach this but similarly if we are able to you know have a basically made of three of the entire this entire setting and then just do a BFS and the height of the tree is what we need right so somehow we would want to write a function called BFS which would take in these strings a and B and it will return the they are returned the exact a height of the tree or did on the number of strands which are near to right so before that so basically the this will this is something which will require a lot of slaps so to actually make us make all this rough slight right is swap our function right so basically voice rapper the C++ standard template library rapper the C++ standard template library rapper the C++ standard template library already has a swap function but sometimes in some cases I strongly recommend that I mean you know Rika melech recommending to implement C++ melech recommending to implement C++ melech recommending to implement C++ functions again is a bad idea you can or you should not implement like the implement of complicated functions but some functions because you know this is the character level function sometimes the C++ level you might act funky in the C++ level you might act funky in the C++ level you might act funky in those this similar function so you should define them yourself because these are like easy so we need to what we need to do is we just need to swap characters this is this very simple you know corrector swap which you learn in the maybe the first few days of your programming the first lecture where you know swapping would start this is a classic pointer example and you know character temp is just a character type will store a raid a in term a will then become B and then B becomes temp right now in this very have the Szabo method so we will very easily able to shop whatever we need right so now let us define the entire BFS method the BFS method right so yes so be the basis method is not what the BFS matter we are rhydian's the end is the height of the bring it we assess what it takes if it breaks up to string addresses you know be in we let's have small and small V and what you want to do is you want to make be the root node and thence find the entire string and at each a right you make a the root node or be the root node it does not matter but the off without the loss of generality will be the root node right for this demonstration so first thing is clear that if in any case in a is equal to V right if a is equal to B then we are pretty sure that there are no swaps needle right we are there will be one to be right now what if like you know the general normal case when a is actually not equal to B then we will have to do the BFS right so okay before we do the BFS we will want to define a few variables we want to define a variable for i DX which will actually determine exactly where the straps and you know we'll be able to defining these believers for straps which will actually define the actual numbers fact we will have a string called current which will make sure that you know you're processing in store current string you're processing and then there will be special variables which are you know the Q variables so basically if you want to do a BFS you need to have a Q and you will need to have a you know container in which you can store what I have previously seen right for stowing what I have previously seen I can have an unordered set right an ordered set of strings right all this so this is what I have already visited so if I you know I will be skipping or whatever I have visited in this unordered set right yes so that is the case the second array which are you know this the second table thing which we would want is we want to how few but this is a special type of queue the VSS IQ which stores the data in this one restores the string which you are you know currently talking about then you know the ID where it needs to have the modification ID where it needs you know I think basically your idea until we're sorting is done before matching is done so on ideal which you know we have already matched the string which we need right so when the idea becomes full then we have the entire string what we needed well the mash idea until match right and the second thing would be swaps till here so to switch to this string how many subs needed right yeah so if you have a custom you know the implementation key so we'll just use the standard template ability we'll have a queue data structure what so basically how do you do this we'll have this pair we will make a pair of string right comma a pair of integers right yes so this is just understand it is a pair of pair all except is a pair with string comma the these match if these match and the straps right the ID and this room's right cue and we have the visited array so the first thing which we actually do is we first you know input this the V arabia's also we might want to initialize the answer so that if everything fails the minimum is 0 so basically if there's some corner case then we will do initialize the answer to be 0 will get you pair string this is Q the first thing which you push in the Q is you push in the QB right the root node right so basically what we do is Q dot push okay how will you push so basically we'll have to make so there is an impious function V you can use that but for simplicity I'm making this using this pair function q dot B and the other would be make zero comma zero so until we know is sorted and we have not made any straps to reach here because we are in the beginning right visit salute not right we also have to push you know basically insert will have to insert be here so that we know B is inside of the ends of the visit if you already visited me right so this is done so let's actually start the vsms starting the BFS alright okay so as usual we start to be a BFS until Q is not empty is not Q dot empty right I might have a strong spending but that is something which you can figure out later yeah until Q is not ending right what we do is we would want to have a variable a high quality to be Q dot front right so how do I link to the Q dot front if once we have this you know once you have Q dot front what we would want to do is we would want to support the current string is nothing but you know he got first right because it is like this is the first element in the queue right yes so you know T dot first that is the string that is the current string and once you get the darn string what we need is we need the ID x like the very we actually have very stressed to us like how many straps have been matched to until now that will be T dot second not first right why because it is in the second pair of the of over of our cube right of the Q structure right the number of swaps will be nothing but in not second right to the second of the second where we will be dust up the cube one sweep of the queue so basically we have to Bob the first animal the queue because we just use and process the first event so now let's so now what we do is find the character the index to be swap right so we want to find the index which is needed which is to be struck now to disable you really key IDs is what needs to be stopped it but it might have funding is in the target area after the IDS it'll all would already be mass right so until we find something which is not matched like vial here not by DX is equal to you know current dot ID X right we have to increment ID x until we find out something which was not matches right you know once you have something which does not match ID X then what we can do is we can simply we can see we can simply start from there we can simply start a for a loop from there is equal to 0-2 for loop you know not is equal to 0-2 for loop you know not is equal to 0-2 for loop you know not from 0 but from you know I play basically from the next element so basically we know that this is where the strap is to be on do you have to find which element we want to start this with for the next element like from ID it's this one - I do - the until the end of this one - I do - the until the end of this one - I do - the until the end of the string so D do we have any end of the string so let's have because since my gosh Anna graphene sponsoring which you can just shuffle and make it into another the both of them are the same size so like int M is nothing but let's say beer or chunks right it's like me watching good now so now basically if right if we see that the element at via where we are current of I if that is equal to a of ideals right so basically now be a found out element of curve H after parent of idiots which we now actually map with your Phi DX right now we need to swap that element right so if this is true what we want to do is you would want to do you know me Tom you would simply want to swap the element so that is why beyond this handy-dandy supper method beyond this handy-dandy supper method beyond this handy-dandy supper method illest rapper the spelling yeah this yeah you know I did not need this job because they might over at the STD swap function at sharper current of I should we just modify the parent of I to current of ideas right so musically just swap so basically the IDF's is where they supposed to I supposed to be is where it is so we just from you know parent do ideas now we match that's some pose you know if this you know if the hair and you know if the new current so now the current actually change if all right is equal people to what we want and you know a then we just simply return swaps plus one right so this Plus this you know probably the different stuff which are going on until now Plus this stuff which we manually pay plus one is the answer to the question right if not right if this is not thing is then what you want to do is we would want to push this into the queue so you'd want to just say Q dot insert again then we will first check that if you are not visit at this right if not visited so basically if vis dot count of current is they basically if not if there is no count of this then what we do is we push it in the cube so basically Q dot push once again make pair make we make bet make pair of the current write gamma make pair what we make when we make pair of you know ie comma is basically the idea express once basically is one more element if they started in this and the straps which we manually did right to reach here it's so simple ideas plus one and we also have to push this into the not Q which will start in such so he will be in insert this into the visualization snake in the visa so we start insert but right yes so this is all done pretty sorted now we need to yeah so much done right this is now what we need to do is we need to return it default value right now two different it now you know - it only default oh now you know - it only default oh now you know - it only default oh before we did on the default value yes we will need to make sure that this array is back to where you are so basically we you know inserted this shop but we found this match but you know the actual shopping can have a hammer anyway even after I show you laughter if there are any matches until L and we would want to stop this so we just make sure that until this course you know the I actually agreements we just make sure that we put all of this thing in the right place right so once again I and exs dropped again so we just you know strapless and inserted into the and let this process normal yes it was doing right so this is done once you know the end our while loop is over and must be function if nothing happens if there is no return then we the straight of them is obviously answer right yeah so let's test this is for score out fingers cross this might not run in the faucet I might have some silly mistakes but I'm sure you leave on them yeah okay simple comma resume then you do a lot of programming in a lot of different languages you know these things happen oh yeah what is the other okay I did not write what is the increment condition right so we'll just do I plus here yeah so it's C Company nombre recording debugging and actually moving this along with that is actually a part of part and following a path of the process we need to do it along anywhere you want to submit code will have to do it and we need to do it accepted let's try to submit this and submitted right so what I'm saying this is a simple question and this is this was just like looking at this tower saying this is a BFS and 200 V of course there are more efficient ways of doing it but this is almost simple this is a very simple convert this into VFS and find the height of the three answer and it's a very it's a simple valid answer as I was saying that in number encoding you might not get accepted the test case might not run in the first instance you might have made a lot of mistakes make sure that you have enough time left in the end to actually debug those silly mistakes right and make those silly mistakes over you don't make them yet right but that's the spot so thank you so much guys we'll see you in the next video with a new problem in the lead quad high capital right thank you so much
K-Similar Strings
making-a-large-island
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input:** s1 = "ab ", s2 = "ba " **Output:** 1 **Explanation:** The two string are 1-similar because we can use one swap to change s1 to s2: "ab " --> "ba ". **Example 2:** **Input:** s1 = "abc ", s2 = "bca " **Output:** 2 **Explanation:** The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc " --> "bac " --> "bca ". **Constraints:** * `1 <= s1.length <= 20` * `s2.length == s1.length` * `s1` and `s2` contain only lowercase letters from the set `{'a', 'b', 'c', 'd', 'e', 'f'}`. * `s2` is an anagram of `s1`.
null
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Hard
null
1,288
Everyone welcome to my channel let's remove all the cover in travels from 100 relationships interview problems on the channel back to back has been sold time when withdrawal remove all in impatient will be subscribed to olive oil this cream withdrawal from doing So will give way that a hum abhi the insight like sis this point md sameer win the interval between this play nvc and discovered recently in the central and remove all subscribe mother will be 313 at 66 subscribe be stopped 10 shots in the first period Itself does for here that and third one will be 321 so after settings close start this will method our interview boat full list rowdy travels withdraw from chronic and you will get ready for this is it only and bank winterwears to start sombeer when I will get In Lagi 828 Awadhesh 332 63 Veervansh subscribe to 6 total equal to two the snow fall will start from last 4 decades know how will complete soon for comparing date will create a temporary like do enrollment se ki end Will's Direction Turn and Enjoy - Way end Will's Direction Turn and Enjoy - Way end Will's Direction Turn and Enjoy - Way in the Minds of Keeping an Industry All the Best Suv Start and Travels in Between 0 and Will Stop Comparing for Comparing with That and They Will Withdraw from Subscribe for This Here and This is the Current Now Interviewer Ne Is And Deliver's Slide In Current Aware Inch And Crotch Interviewer Plessis In Like Share Subscribe Plessis Where This Subscribe And Subscribe The Total Subscribe Thank You Welcome Like Share Subscribe Like It's Not The 1518 210 Shoulder Left From Current Aware This That Garlic Avengers New Royal Wedding Is This Interval Is Hindi Right Side As Well S T Spoon Right Party Somdat Sudhir Vidron In Middle Chief Subscribe The Channel Subscribe Must Depend Icon Subscribe To The Days Of Travels Were Intervening Gandhi Effigy Of Doing Well In This Will Sadhe Start From 90 - 20th In This Will Sadhe Start From 90 - 20th In This Will Sadhe Start From 90 - 20th that you stir sorting method define overcurrent interval from enrollment it is like you all new introduce 209 also visit all the interviews in interview also elected call in interviews na ho let's also define na result which will have to written in hindi and so Enter pimple 2018 thursday 200 here first will check is the kar this interval ne is interview of start this great and the current interval of star and internal of and on this day also great dan current intervened in the case and current interview with the interval of students And update your hair with just different interview of which is the meaning of this only and only at the time interview of subscribe to that NCC cadet passing ki sawaari forget to treat acid bases of two things so let's computer knowledge that smoking late time decoded the fifth accepted To what is the time complexity of this chanting in law and disciples and several time complexity of dissolution and log in and complexity subscribe me to the noble prize like and subscribe my channel
Remove Covered Intervals
maximum-subarray-sum-with-one-deletion
Given an array `intervals` where `intervals[i] = [li, ri]` represent the interval `[li, ri)`, remove all intervals that are covered by another interval in the list. The interval `[a, b)` is covered by the interval `[c, d)` if and only if `c <= a` and `b <= d`. Return _the number of remaining intervals_. **Example 1:** **Input:** intervals = \[\[1,4\],\[3,6\],\[2,8\]\] **Output:** 2 **Explanation:** Interval \[3,6\] is covered by \[2,8\], therefore it is removed. **Example 2:** **Input:** intervals = \[\[1,4\],\[2,3\]\] **Output:** 1 **Constraints:** * `1 <= intervals.length <= 1000` * `intervals[i].length == 2` * `0 <= li < ri <= 105` * All the given intervals are **unique**.
How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm.
Array,Dynamic Programming
Medium
null
258
so this question is question number 258 and it's add digits given an integer now repeatedly add all its digit until the result has only one digit and returned so how do we do this one so um there are two ways actually let's do the way that first came to my mind and uh if you've uh watched my previous videos that could help a lot for this one uh also this is an easy question and uh okay so i'm kind of gonna call uh a function and again uh because there's like let's say we have an example num38 and the process is at three with eight uh it will be eleven and then add eleven one and one it will be two then it stops here so you just basically return two so that's what i'm gonna do um so the first thing is i'm gonna actually uh define a function here def and add and i'm going to give something and that would be num i'll say x here and i'm going to say uh while x is not 0 because i'm basically going to divide x i mean with 10 and find the remainder and uh so basically it will be 38 divided by 10 would be eight and uh the remainder would be eight and then next one it would be um whatever that number is divided by uh 10 and i think it will be 3 divided by 10 and that would be 8 plus three would be eleven so that's what we want basically so while x is not zero we wanna say uh let's say r is zero at first that's the remainder zero now i'm gonna say r plus equal to dividing that x and getting the remainder with 10 here and then x is what x and divide equal it's like integer division equal to 10 here so that would give us back uh that will change our x each time so the first one would be 38 we'll say oh it's not zero so we're dividing getting the remainder basically that would be eight here so r would be eight x would be three though because uh that's the integer division of x on 10 uh so that would be three so three again we check it's not zero so three divided by ten the remainder is a three plus eight that would be eleven uh and then we check three uh initiatives and ten uh it will be zero so it doesn't go inside this anymore so that would be basically uh our last result here so it will just give us return r here so but this function basically needs to be called uh because we're doing this again and again so this whole function was actually this one uh so it returns 11 here so what do we do here to make sure that this is getting cold uh as many times as po as we need it to be called so one thing i want to do is that i'm going to just say num equals to um add num so i'm going to call that one time so say this is 38 i'm going to call this and this will be 11. so 11 will be going into num here so that's what we want to do but then we say while none is bigger than nine so while number's bigger than nine you just do that again not equals to add yeah but then if it's not then you just return no because you don't really call it again so this is what you want to do instead if you run this should work yep it works and if you submit this it works so let's explain this for a second so this one is getting called one time so 38 it gives you 11 and it puts 11 into the num and it says hey if this is bigger than 9 if it's not bigger than 9 you just return that let's say it's 2. you just basically uh return that 2 here but if it's not if it's 11 you say you put 11 inside this you do this again and 1 plus 1 would be 2 it returns 2 here you put 2 inside then you check if 2 is bigger than 9 which is not then you return that 2 here so you do that again and again so that's one way of dealing with this um so let's uh just comment this out because i want to do it in another way also okay so this way is different and what we want to do here is uh okay this is another way which is a very straightforward mathy way i mean the previous one was matthew a2 uh but let's do this one is very straight forward basically if num equals to zero i'm going to say return number right which is zero then we don't really care about it just zero um if the num mod nine equal to uh actually if this is equal to zero yeah so um so if it's like 18 you would say eight plus one is nine right and then um yeah so let's say if it's 18 if 18 divided by 9 which is like the remainder is 0 return 18 divided by 9 which is uh basically zero here so that would give us the answer yeah but if it's like uh else actually so if it's not the remainder of uh num divide by nine is not zero then return again return num actually this should be nine uh yeah because it's actually a plus one and nine yeah okay yeah just made a mistake for a second this would be num divided by nine yeah the mod nine so if none uh mod nine is equal to zero which is 18 let's say you return 9 yeah 3 plus 1 would be 9. let's say 27 mod 9 2 plus 7 is 9 let's say i don't know something else like 36 6 and 3 is 9 so that would be just 9. but if it's not then what do you just return num divided by nine so let's say it's a 37 so that would uh give us one actually i think here let's say 37 here let's say run code yeah you see there's one here so that's how it works um so this is because of that property that division of nine basically so you would say anything that is divided by 9 is divisible by 9 so it would return basically it should be zero because the remainder is zero but you're giving back nine because that would be the last one uh that you will be here appearing here uh so it will be the one digit uh and it will be nine always so if it's 27 it will be the same thing divided by nine the last one will be always nine and it'll be 30 if it's 36 it'll be the same thing and so on but it feels like something that is not divisible by nine you just say uh 37 um okay so you just say three plus seven will be what ten so ten divided by nine it gives you one at the end so one plus zero one here remember if you just like check one let me just check one more something like let's say 21 uh 21 okay 21 is um divided by nine and this is basically three right so if you divide this by nine this will be the remainder will be three so that's uh this gives you three here so that's how you solve this question let me just submit this uh and you'll see that yep this works also and that's how you solve this question number 258 add digits
Add Digits
add-digits
Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it. **Example 1:** **Input:** num = 38 **Output:** 2 **Explanation:** The process is 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 Since 2 has only one digit, return it. **Example 2:** **Input:** num = 0 **Output:** 0 **Constraints:** * `0 <= num <= 231 - 1` **Follow up:** Could you do it without any loop/recursion in `O(1)` runtime?
A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful.
Math,Simulation,Number Theory
Easy
202,1082,2076,2264
368
hi guys this is a so we are going to Sol solve the today's lead code question which is largest divisible subset so we are given a number of we are given an array and we need to find the largest subset answer such that every pair of elements in the subset satisfies the condition one of these two condition should be satisfied so let me give an example so that we can understand better so this is the given array suppose let's take only 1 2 till 4 this is the um given array and we need to find largest subset such that all the elements which are picked from this array should be divisible yeah let's consider like then we can pick A1 and a A2 and A1 and then A3 and then A2 and then A3 and A1 so these are the different possibilities which we can pick from this Sur to different elements suppose if uh this particular case any one of these condition should be saf that means A2 should or A1 should be divisible by A2 for this particular case A3 should be divisible a or A2 should be divisible by A3 for this particular case A3 should be divisible by A1 should be divisible by A3 so these are the two conditions which should satisfy so that it will form the largest subset such that it satisfies one of these condition so how can we remove this two conditions into one condition so that we can check easily suppose let's think A1 is less than or equal to A2 and is less than or equal to A3 why because we can start the array and then from that we can say always largest number is divisible by smallest number so we can say that right because the largest number cannot divide the smallest number so by using that logic we can sort the array from that array we can get the whatever required subset we can get and then for that particular case we can divide and then check whether it is possible or not so for the these three possibilities what should be the conclusion suppose let's say A2 should be A2 and A1 is picked then A2 should be divisible by A1 why because A2 is greater so A1 should divide A2 so A2 divides A2 is divisible by A1 and then for this particular case as we are saying A3 is greater than A2 A3 should be divisible by A2 and what about this one A3 should be divisible by A1 right this should be done but if we see this carefully suppose let's think A3 divided A2 divided A3 and then if we say A1 divides A2 then we can say A3 will be divisible by A1 right why because let's consider here 1 comma 2 comma 4 so suppose if this is true that is uh 2 is divisible by 1 and then 4 is divisible by 2 then we can say that four is will be divisible by one as well so we can remove this condition when these two conditions are satisfied so we can check this uh we can check this like for this particular condition the next element should be divisible by previous element and this particular case the next element should be divisible by previous element so for any case we need to consider the current and then previous element If the previous element divides the current element then we can say we can form the subset and then it will be largest based upon the length so that is theic so one more thing we are going to store is DP of Index this will store the length of subset we had picked length of largest subset we had subset largest subset we had picked and inser index so what we are saying is it will be the largest subset we had picked and then it ends at this particular index suppose let's say we got DP here DP of A1 and then DP of A2 uh this will be index let's say I2 and then this is i1 and then this is I3 DP of I3 so these indexes will store the length of the subset we had picked and then it should end at this particular index so whenever we want the answer for this particular case we are going to consider previous elements are as all the previous elements so this can be I2 and this can be i1 so out of these two cases whichever we find like it is divisible by previous elements suppose A2 is divisible A2 will divide A3 then we can say that we can form the subset and we Al we also need to take care that particular case should be largest subset that is DP of I3 should be less than whatever uh element length we are getting so that is the logic for this particular case so we are going to code the same thing and then as we as they are saying like we need to return the largest subset answer so here we should not return the length we should return the largest answer so we need to take one more array which is parent of more one more array which is parent of index suppose let's say this is parent of I3 suppose this is the largest length we can form then parent of I3 will be I2 why because the previous element is this one and then for this if this is the case then we can store i1 so uh let's code this up so that we can understand so let's take TP of index as it is saying like 10^ 3 so we index as it is saying like 10^ 3 so we index as it is saying like 10^ 3 so we can solve it bya n² time complex so this is DP and then we are going to take one more which is parent of 1 and then we are going to Mark every index two minus one and then par in 2 minus one and then we need one more thing is Vector of answer which will store the largest subset answer and then one more thing we need is maximum index so let's assign this to 1 minus one as of now and then one more maximum length this will store maximum length we can get from the subset array so let's take it as minus one as of now and then we'll go through each and every element in the before that we need to sort the nums why because as we had mentioned if we did not sort then we need to check all other condition like two of this condition if it is sorted then we can directly calculate and then uh do it so we are going to sort this so I'm sorting here so this is parent and DP initialization and this is answer and then we'll go through all the elements which is present in the nums and then we are going to take all the previous Elements which are previous to this particular index and then for the previous one we need to check this condition like uh the current whatever the current A3 should be divisible by A2 so we are going to check that if nums of I is divisible by nums of J and one more thing is we need to take care of DP the length of this particular case suppose let's say there is only one element then we are going to say that only one element is formed and then that length is one so here we are going to say DP of I is less than DP of J + is less than DP of J + is less than DP of J + 1 then we are going to assign the DP value which is DP of I equal to DP of J + 1 and then we need to store the parent + 1 and then we need to store the parent + 1 and then we need to store the parent of I which is J like the previous element will be J because this is the largest so we need to store that and again after this we need to store the maximum index and then maximum length so that let's say the maximum length is formed here at I3 so we need to know this index so that you we'll get here on the previous uh like the parent element will be this one so we'll get here and then previous element will be this one so we'll get here and then at last we'll see the minus one so when we get to minus one then we'll solop so if maximum answer is less than DP of I then going to say maximum answer is DP of I and maximum index is going to be I so let's take this as maximum answer and then after this we are going to call maximum index not equal to minus1 till the this time we are going to insert into the subset which is nums of Maximum index and then we are going to say maximum index move to the parent and then we are going to return the answer so let's check whether we have any errors so we are taking the DP to store the length we are taking the parents so that we can store the previous element and then for this we are assigning to minus one and then we are taking Vector answer so that we'll store this answer and then we are taking maximum index so that we'll know where the maximum length is present the end of the maximum length and then this will store the maximum answer length and then we are going to sort the given array and then we are going through each element in the array and then we are saying the maximum like the minimum it can be uh with the length of one why because we can take one subset like it will be it doesn't need to satisfy any of because there is only one element there are no two different elements so for this particular case the previous elements can be it starts from 0 to IUS one till IUS one we can pick any previous element and the current element is divisible by previous element and the answer which we get from that particular which is the length which we got the T at J + one the length which we got the T at J + one the length which we got the T at J + one is less than what we had already calculated then we can say DP of I is equal to DP of J + we can say DP of I is equal to DP of J + we can say DP of I is equal to DP of J + 1 and then we are going to say parent of I will be J and at last we are going to compare with global maximum answer which is DP of answer is maximum answer is less than DP of I then we can say maximum answer is DP of I and maximum index will be I and then while we are traversing in maximum index we are going to push all the elements which are present here like suppose if it is A3 we are going to push and then we come to A2 and then we move to A1 This Is The Answer let's see let's run this yeah let's sub me yeah it's fast yeah thanks for watching the video do share do like if you like the video thanks
Largest Divisible Subset
largest-divisible-subset
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies: * `answer[i] % answer[j] == 0`, or * `answer[j] % answer[i] == 0` If there are multiple solutions, return any of them. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[1,2\] **Explanation:** \[1,3\] is also accepted. **Example 2:** **Input:** nums = \[1,2,4,8\] **Output:** \[1,2,4,8\] **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 2 * 109` * All the integers in `nums` are **unique**.
null
Array,Math,Dynamic Programming,Sorting
Medium
null
203
Hello Everyone Welcome To Day Twelfth Family Got Talent And Polish Of Making This Video Let's Subscribe Must Visit Subscribe And Will Give You All Subscribe 123 456 Subscribe Do Three Four Five Returns The Video then subscribe In This Example A To Remove Clips Element To Tourist Places Prithvi Subscribe 560 Interested in Doing All the Best subscribe The Video then subscribe to the Page if you liked The Video then This Note to Wisdom in Noida and Died Letter to the First Snowfall in That Unwanted Topics Effigy of Eternal Values ​​Subscribe Now To Two That A Green Beans Activist Video not Will Processes And E Do Not Want To Listen Nov Dec 6 Withdrawal subscribe Video Subscribe Next Time With U Hai So Let's Famous Veer Width And CVC Dabeli Subscribe my channel thank you look at the example which is also very interesting example Veerwal Dhool of the Video then subscribe to the Page if you liked The Video then subscribe to the Andar Ghanta Par Singh Noida Points Collect Not Vidron It's A The word you see mystery at the volume undercurrent nodia think again st in the previous next point ko is point ko main bhi thodi later to hyride against this again subscribe Video subscribe do subscribe button click ho ki kami dot s the distance between channel subscribe time subscribe Now To Receive Main To Idhar Post Website Designer Node Value Of Discipline More Acid liked The Video then subscribe to the Page if you liked The Video then subscribe to subscribe our Channel Subscribe Like Comment Me Dard World In The Form Of W Dot Tribes of a Hain Akshar Pred Time Complexity of This Approach Free Samples for Deaf and Boys Previous subscribe and subscribe this Video subscribe button
Remove Linked List Elements
remove-linked-list-elements
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_. **Example 1:** **Input:** head = \[1,2,6,3,4,5,6\], val = 6 **Output:** \[1,2,3,4,5\] **Example 2:** **Input:** head = \[\], val = 1 **Output:** \[\] **Example 3:** **Input:** head = \[7,7,7,7\], val = 7 **Output:** \[\] **Constraints:** * The number of nodes in the list is in the range `[0, 104]`. * `1 <= Node.val <= 50` * `0 <= val <= 50`
null
Linked List,Recursion
Easy
27,237,2216
880
hey everybody this is larry this is day 20 of the league code daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's problem so i do solve and explain these problems live the cool thing maybe is that i go through my thought process and not just the solution so you know feel free to fast forward or watch it on a higher speed if you want to go straight to solution or watch another video it's fine um anyway so today's prime is decoded string at index so okay where is it what does that mean okay so basically whenever you see a number you repeat everything that's the prefix of that a number of times and then you have to find the cave index of that string okay that sounds reasonable okay and okay so for one digit it's just one so we don't have to worry about like pausing at 22 is just two twice okay just d minus one more time okay so uh okay well it i guess from here we can clearly see that uh it does not make sense to generate the string because we repeat this a lot okay wow um to be honest i was just reading the problem i don't my first incarnation is just to generate the string in some way and looking at the constraint it doesn't seem like you know obviously you can't really uh you can really generate the string from scratch and then even k is big so you can't really do anything that's capped on k on a constraint so you have to really think about how to do this hmm and how would i do this i mean i think when it comes to this problem the way to do it is probably gonna be some kind of what i call bookkeeping or keeping track of certain variables in a way that allows you to keep going um for example every time you see a number maybe you could either use a stack or some kind of implementation to kind of figure out um within that how many things to take care of right and i think that's actually not that bad but in terms of algorithm i feel like i could figure it out it the implementation is always also going to be tricky so this is probably tricky on both parts so let's do it together let's um well yeah i think my idea is that okay you know you right have a stack or some kind of data structure to allow you to go from left to right and then every time you see a digit you know the current um the current length and as soon as we reach k we know that you know we don't have to pass the red end of the string um but then now the question is how do you combine these strings right um i mean i know that here we can combine these two just multiply them and that's fine that's easy but if you have something like actually even this one uh how do you combine them in a good effective way um is it just counting because here you know that there's four characters up to the two now you know that there's eight characters nine ten eleven twelve and then times three so that's gonna be 36 characters i don't know if this is 36 characters but that's the way to kind of go um is that good enough not gonna lie this is a tricky problem for me because there are a lot of potential for off by ones as well so i'm thinking about how to cleanly implement it even though i have a general idea okay i mean let's play around some concepts as we go and then we'll see so yeah let's play with that i think there's gonna be some combination of uh scanning from left to right and also recursion i think it'll be okay i don't think this is that bad but um but let's just have to be really careful so we're gonna start with an empty string and then for x and s so for each character in the string if x is in if x is a number then we have to do the thing and obviously in python this is actually very simple but we are trying to not generate the string because that would be disastrous right so okay um so a string is not going to be enough let me just create a list um and then we'll pass out the list and then we could figure out what the situation is um okay so hmm yeah okay uh i'm just trying to figure out how to name this as well let's just call it current i am terrible with naming right now so yeah so current.append yeah so current.append yeah so current.append of or just x otherwise if it is a string then what i want to write is something like to take the last string and then we add that to x to kind of add to the current string going on but that is not going to be quite correct um if the last string is empty or you know or it's just a number right so okay so if length of current is equal to zero or um the last element is an int then we set this to a new string otherwise we just append it to the last one okay so let's make sure that our thing inputs or outputs what we expect to do so let's give it a quick go uh that is actually what i want so that's good let me also while i'm at it put in the other two test cases what's the number that they want five and then some ridiculous number okay so the length of the num i think then one but same thing yeah and i think so the ongoing uh length of the string is actually not that hard um because okay so current length say is equal to zero if it is number we take current length and then we multiply it by that number otherwise we just increment by one i think this is should be good enough to get so this is the final length of the generated string i believe so we're gonna print it out uh so why do i print so much stuff out is it's just for visualization and this is way too long so let's see it has this big number that is the same as this number so i think so anyway so that should be good um and the segment also let's see what did they say yeah 36 and 8 so that's good because i think i said 36 earlier and this is clearly 8. um so okay so at least we know this recurrence is true so then the question is how do we get the cave element right and this is going to be going backwards i think so hmm how do i want to do it um so the current has the thing i think almost uh we want to terminate early so that we can care about it now so okay so if current length is greater than k it may be greater or equal to we may have to do it off by once but i just want to get the general idea right if this is the case then we only care about and then we can then we don't do the operation that is now right um it's a little bit yucky that's what i'm thinking about the best way to do it cuz this is already that means that this is already too big but that's fine okay so then that means that we only care about uh then current will have the number that we need and then now the answer is in current and then now i have to think about how to construct this right um so basically the idea that i would have is that we have some function f of x say and then we want to convert this um based off the transformation that we're doing here with respect to either times two times something or increment by one and then map it to the new thing right so okay so you know we start with k maybe that's another way of doing it's just we keep track of k right so if we have a if we add so this we should be able to go k minus one because every new character that we see we decrease k by one right um and then here what does this mean right well this means k subtracted or equal to um in sub x um maybe beforehand right because basically like if you go from two times two to four you actually want to get the delta which is two so this is just equal to the current length times this minus one right um that's kind of the idea but we're going to go over because this we're going to check by too late and this is going to be negative right so basically we want to add an if statement which is also okay if k minus 1 is equal to 0 then we return the current string this is so annoying um okay so then here we in theory this is the last actually no this one is easier because then this is the last string we have pen which is x maybe um okay let's just uh return oops if k is less than or because if this is true then that means that the string is within the new thing that we expand so now we want let's just return outward just so that we kind of test this case uh real quick okay so this is this works for these two um of course that's not meant to be exhaustive and all i know that this is not the case intentionally um and yeah we have used the same amount but let's just say two this should give us the wrong answer and if we have to do and then we do three that should maybe give us the right answer um oh decoder string is yeah i mean this is not that interesting to me so that should be okay uh yeah so that so now our behavior is expected and then now we just have to be careful about this right um and that means what does this mean this means that within the current length like whatever we're repeating uh it is within that right and that period is going to be what is that period is just the current length before you get multiplied so then now if this is the case then we want um how do you say this in a good way basically it's just current length mod k i want to say is that true because basically you have something that's repeating and then you want to get the k for amount so it is the k mod the current length would be the new k right okay yeah okay so we do this mod current length because this is the multiplier and again there might be an off by one here i have to double check this for a second um because this is also one index which is always a little bit weird to be honest but um yeah maybe this messes me up so let me make this several index um yeah and let me uh unsolved oops i know i mistyped it but it doesn't matter so let me make sure that this still uh gives me the ex what i expected to give and then now let's get this enter k okay so then now we know that this is within uh the thing so we have to return an answer here at some point and now we could back out exactly uh from the current right so then now let's look for the array um okay and i think to be honest you could probably have i think i did it this way but you can actually just have the current uh the post string at the end and then just go to the back and maybe we'll do some refactoring to that i think maybe i like that better maybe i don't know this case is easier to handle here like this but this case is a little bit uh shaky with respect to that but yeah so now we want to go okay so now this is before right so let's do while current is uh greater than zero and so then now we check the last character if the last string is numeric and maybe this is where uh can calling them is a little bit silly maybe i should just do them one by one instead of uh comparing the string i don't i might it might be easier but i actually don't think yeah i think this doesn't change anything so let's actually uh just always concat or always create a new element and here yeah that's good so then now we can just check whether it is numeric directly if it's numeric then what happens right well with numeric again that's that means that it repeats and it repeats at the frequency that is uh the number that we get here so okay let's just say um last is equal to the end of current minus one so this is the last number and it repeated last number of times so that means that per part will be current length to the last let's just say per uh period and then k we want to mod that by period um okay and then we pop because now we have to go further to get the string right um and then else we just subtract by one because can this be zero i guess so but hmm but we only can solve this here be in the string portion because we don't have to string otherwise i think maybe let's check if k 0 we return a current of negative one else k minus one and also current.pop else k minus one and also current.pop else k minus one and also current.pop okay this is actually really terrible code i think um i mean the logic you saw how i did this progressively logic by logic but it is tricky for sure um okay so there is some weird issue here why do i get uh a mistake here oh i see because we append before we do the multiplication so actually we should the first thing that we should do is uh well we don't have to do anything let's just move this until the end okay then this may turn out a little bit better um okay i mean it's not right but at least it's fun right um and i just don't know if this is off by one as well uh i mean all the other answers are right so it's very possible that this is off by one um yeah if this is zero no it is not that it is off by one it is that i see okay i think actually i made it's not that it's off by one is that i'm counting backwards so if this k is equal to zero i need to get the entire string and not just the last character okay so what i was doing earlier made sense again which is that if length of current zero or um the last one is numeric that's why i was doing it that way but i forgot uh or i don't know this is tough so uh hope you appreciate it um okay so now if this is the case then what do i do this is a string okay let's think about this right that wasn't even right okay so if this is a string so with the number and it since then we do this mod thing which is fine um if not if this is a string what does that mean that means that it could either be part of the string or it cannot be right so i think that's uh so we have to think about it as well for example if you have something like um ha too hard to someone like that say um if your input k is like i don't know six then it's actually um let's just go let's use another one hard to and uh i don't low high low so then this would actually be high and then low and then high low rate so then if you go six this will be in the second part but five would be in the first part four would be the first point so forth and we divide it by 2 so um or we mod it by 6 so this is actually going to give us the 0 that we want but then now this part doesn't tell us anything because it's not going to be in this part right so what does that mean that means okay i have to think about a little bit but i think i got it which is if so the length of the current of my uh the last string that we're looking at um so this is going to be the last characters so this is like the end of the string the suffix of the string right so suffix is equal to this say oh this is the suffix but um suffix length is this length um if so if current length so this is the current length minus suffix length um or let's think about the other way maybe let's see right so basically the suffix length minus that it's going to be so the prefix length okay let's write it that way that's easier to read i think um prefix length is equal to this right because together they create entire string so if k is less than uh again i have to think about the thing then that means that if this is in the prefix then we have to keep going right so current.pop right so current.pop right so current.pop we don't even have to change k because we know that it's going to be inside the prefix so that's fine otherwise k minus equal to prefix length and then we can just return current uh the last string and then the k element okay is that clear i don't even know if that's clear um and again i might have an offer one anyway but oh answer is not defined uh would have answer i forget oh here uh no i don't need it okay well it was worth a shot no i mean i think it's still right but i think there's um some off by one somewhere hmm is this if k is still indexed i think this is right but or like roughly right okay let's check here prefix length suffix length uh and then k right so what do we expect to see from here without well expect to see a little bit more but uh let's just do sk so i could see which test cases this is working for uh okay so how to or two so it's what is s oh s is just the input why is s like this did i overload it by accident oh no s is the first one okay so it's k okay we get the is that right we want to get the fourth character right and that's gonna be h so one zero one two three four i guess that's right okay um prefix length is two suffix length is two is that true current length is four i think i'm off by something here we have four but two we go to three times two i think this is equal to i think that's why uh okay so there's enough by one and we did fix it but i don't i'm not confident about this at all right i am this is a struggle uh so that's so let's test more cases so here 20 30 32 33 34 i don't know just i'm really not confident about this so i am going to put as much as possible and again and there you go i am rewarded for my testing a little bit um but beyond that i am going to take a quick look to see the other answers to see if they're right um because if they're wrong that means they're other things as well no means a couple of things so we'll definitely um figure out what that means why do you even have no or like how is it possible to have no uh on top we only return one place so that makes it easier to debug just first of debug let's print out everything here um bottom say i don't know and here uh top because no is already when i mean no can probably only come up when i have enough by one so that is good in a way so top is i thought i put two now so top returns a cno there's no top at all so what happens i guess it's actually this is just returning impossible maybe um because i thought that maybe it's returning no here somewhere but uh but it may be just that okay all the loops are running out um that is odd though that's also okay i mean this is very odd but that's why we're debugging this is a very long problem but um yeah okay so k is hugely negative so something definitely went wrong somewhere oh um well the there is some assumption about this loop in variant where hmm i mean this cannot make this negative right so it has to be here uh and therefore i mean the only subtraction is maybe here that's i mean and this is not possible to be um negative right because of this statement so that's how i would check about the variance the only thing that is tricky is here so let's add an assertion here and see if that's where it fails uh yep that's where it fails but how does this how is this true okay i guess so let's also add a impossible two so i think it's just doing that as possible too but then it goes through so that means that there's something with this loop invariant that is a little bit off um because my invariant here is that we will go to k is 0 at some point and this would you know be sorted out but apparently not oh i get this fight if this is in the prefix okay that's uh if k is in the prefix so okay let's see let's just add something like a prefix check that we can remove these two for now maybe i'll need them later and i'll regret printing them out but uh but now we know where the bug is and hopefully this debugging is uh valuable for you as well but up okay and in cases of k is less than prefix we pop yeah okay hmm impossible too how does that work that means hmm this is so weird though okay let's actually also add current minus one on the top string um to see i'm having trouble visualizing what's going on so okay so why is there an extra space oh because i okay that's intentional or well not intentional but it is what the code that i wrote okay so first so three quick check the last chunk three k right actually let's add the print impossible so we have a delimited delimiter okay so here it is one the prefix is four did i did this well the prefix length so this is the suffix length right if why i think my signs are just wrong if k is no um because if k is bigger than the prefix length then this happens right so we have this then yeah then we know that this is in the current string otherwise we pop the last string right but we have do we have to oh um we have to minus some k here and i think we haven't done that's probably why we want to so then k no we know we don't because we can ignore it that's my original logic we're going to ignore it because k is already smaller than the prefix length so it's going to be in the prefix which is the rest of the current right so that we can get rid of this one um okay but then why tell me why let's run it real quick okay so this it claims is impossible uh s is less than oh sorry k is less than prefix length so this should pop but it's already on the in the beginning right why is this prefix length eight did i do something weird oh no oh we don't update current length in this because i just forgot i am not a smart person okay so period is this when we pop this actually current length uh shrink by last i don't know how i forgot about doing this i uh and then here when we pop current length minus uh the length of the suffix so yeah okay so wow how did that even pass so many test cases not you know maybe it's just a little bit lucky okay so this looks a lot better i am so yeah just silliness uh let's give it a submit i'm still not that confident but let's uh you know oh uh got my fingers crossed but i did get a lot because test cases right so uh so wait so this seems like an off by one because it's just aab and i returned uh amb which is unfortunate but like i said i got a lot of things right so there's that off by one somewhere here uh that we were worried about for sure um where can it be though is it this one was that was the one that i wasn't sure about because if this is greater than you can remove it right so if they're the same uh okay that's the one that i had doubts on earlier that's why i pinpointed um okay whoo that's actually lucky because i think i should have tested a little bit more so this is a mess of a code um i have a long explanation as you were here for 35 minutes apologies for that but let's have a recap is just being really careful of the problem i think you have you know you just have to keep track of a lot of things there's nothing i don't think it's complex to figure out the formula of okay when you have a number the current length extends by this much and when you have a string or a character the current length extends by this much by one in this case um and it's just about being really careful which i wasn't enough um and yeah i mean i think other than this uh minor thing i think most of my code worked the first time uh and also this thing do i had it right initially but that and then i don't know what happened but um cool so what is the complexity of this well uh for each character in s we push it into the stack this is actually a stack in case you're wondering uh even though we didn't call it that um you push it onto the stack once and you pop it off the stack once so that's going to be linear time in terms of space again because we have a stack and each character can be pushed on the stack once it's going to be linear space uh so that's all i have for this problem it is very tricky but to get right correctly uh well i guess you can be get right incorrectly but it is very tricky so definitely just be careful take your time and let me know what you think about this problem uh and i will see y'all tomorrow bye
Decoded String at Index
rectangle-area-ii
You are given an encoded string `s`. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken: * If the character read is a letter, that letter is written onto the tape. * If the character read is a digit `d`, the entire current tape is repeatedly written `d - 1` more times in total. Given an integer `k`, return _the_ `kth` _letter (**1-indexed)** in the decoded string_. **Example 1:** **Input:** s = "leet2code3 ", k = 10 **Output:** "o " **Explanation:** The decoded string is "leetleetcodeleetleetcodeleetleetcode ". The 10th letter in the string is "o ". **Example 2:** **Input:** s = "ha22 ", k = 5 **Output:** "h " **Explanation:** The decoded string is "hahahaha ". The 5th letter is "h ". **Example 3:** **Input:** s = "a2345678999999999999999 ", k = 1 **Output:** "a " **Explanation:** The decoded string is "a " repeated 8301530446056247680 times. The 1st letter is "a ". **Constraints:** * `2 <= s.length <= 100` * `s` consists of lowercase English letters and digits `2` through `9`. * `s` starts with a letter. * `1 <= k <= 109` * It is guaranteed that `k` is less than or equal to the length of the decoded string. * The decoded string is guaranteed to have less than `263` letters.
null
Array,Segment Tree,Line Sweep,Ordered Set
Hard
null
20
hey everyone welcome to techwired in this video we are going to solve a Lead Core problem called valid parenthesis first we will read the problem statement then we will see the solution using a stack so in this problem we are given three types of brackets we need to check whether the brackets in the input are opened and closed in the correct order and the Open brackets must be closed by the same type of brackets and every close bracket should have a corresponding Open Bracket of the same type of bracket that has been given in the input now we will see the solution and I am going to explain the logic behind it using a stack hey guys so before going into the solution if you guys haven't subscribed to my Channel please like And subscribe it will motivate me to put more videos in future this is one of the examples that has been given to us in the Lead Core website here we have a pointer I'm going to iterate through the string that has been given to us and I'm going to append the Open brackets into the stack and whenever I get a closing bracket in the string I am going to check by popping the element whether I have the open parenthesis of the same type of bracket or not now I'm going to show you the intuition here so here I have the eighth pointer which is pointing to a open parenthesis here I'm going to append that in my stack in the next iteration I'm going to get a closing parenthesis here so whenever I get a closing type of bracket I am going to pop from the stack and keep that in one variable called X okay now so I will check whether I have the corresponding the same type of opening and closing bracket or Not by comparing X and I if they are not equal I am going to return false okay and that is an H case here what if we have only one closing one opening bracket for an example we are going to append that in stack since that is an opening bracket I am going to append that instead and I'm going to terminate from the loop in the end we are going to check whether if there is an bracket present in the stack or not if there is a bracket we are going to return false and if there is no bracket I am going to return true if the stack is empty I'm going to return true now we will see the code for that so first we are creating an empty stack then I'm going to I trade I in my input okay with the variable I okay if I not in my closing brackets okay which is indirectly means that I'm going to whenever I detect an open parenthesis Open Bracket I'm going to append that bracket in my stack okay I'm going if I get a closing bracket then I will check whether there is a stack which means there is some variables some types of inputs already present in the stack or not okay now I'm going to pop the last element which is nothing but we have to get the corresponding opening bracket okay in the X we are going to store the opening bracket that is from the stack the recent opening bracket because we need to close the recent opening bracket okay so I'm going to check if is equal to x equal to opening if I detect an opening bracket okay then I'm going to check if my corresponding the current input string if that is not equal to same type of bracket I'm going to repeat this for all type of brackets okay I'm checking whether the corresp current pointer is pointing to the same type of bracket or not okay so I not equal to or if there is a curly braces and I not equal to I'll call it brace then I'm going to return parts okay now that is another Edge case as well what if there is no opening bracket I just start for example assume if I get a closing bracket assume I get a closing bracket of a curly braces and there is no open parenthesis present okay then I can directly return false here I'm going to return false if that is something present in the stack if there is no values in the stack then I'm going to return true now we can run the code we could see that it's pretty much efficient so we have solved this particular problem in order of n time and Order of n space since we used a stack so that's all for this video please like and share subscribe this will motivate me to upload more videos in future also check out my previous videos and keep supporting happy learning cheers
Valid Parentheses
valid-parentheses
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. 3. Every close bracket has a corresponding open bracket of the same type. **Example 1:** **Input:** s = "() " **Output:** true **Example 2:** **Input:** s = "()\[\]{} " **Output:** true **Example 3:** **Input:** s = "(\] " **Output:** false **Constraints:** * `1 <= s.length <= 104` * `s` consists of parentheses only `'()[]{}'`.
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
String,Stack
Easy
22,32,301,1045,2221
1,646
hi my name is david today we're going to do number one six four six get maximum and generated array this is an easy level problem only code i want to solve it in javascript in this crop we have a function that takes in an integer and with this integer we have these conditions that creates a new array and once you create this new array we want to return the maximum integer in this new array so for example we get this input n equals 7 and then maximum and then we use that seven to create this array and the maximum number in this array is three so we turn three and these are the conditions that we have inside of it so basically these are the first two conditions and then this when you look at it closely is a com very convoluted way they put it but we just skipped the first two one because these were we're doing the two and if we just divide by two this is what we do for the even and then this is what you do for odd so how we're gonna do this is that we're gonna do the edge cage first because it can be it starts at zero and then if it's just the first two we don't do these other different steps so condition if n is less than two we just return and then we so that's the edge cases and next we do we want to create a new array create new a array and with this we want to create an array and then now we want to create the max value that we can see we can keep track of it create max variable and inside of this array we want to set length to n plus one like that said and then fill it to zero at first so we can change it later and then we want to change the a index of one two one for this edge case and once we got that we loop through n and we have a condition to condition if current is even and inside that we just follow the parameters these rules follow rules and then check to see if it's a new maximum that vary that value and that's the even and then we just else follow the rules for odd and then we check for new max and then once we do that we return max so let's put in code so if we do the edge cases first if n is less than two return n and now we create the new array that a equals new array with the length of n plus one and we fill it to zero and then we change the we create the max variable that max equals zero and then change the first index of one a index of one equals one and now we fill out this array up for that and now we can just start at two for this i equals 2 i is less than or equal to n going up to n i plus now we create the conditions if it's even so if i mod 2 has no remainder you just do a index of i equals a math dot 4 i minus 2. so yeah so if there's any remainders but there's no remains because even but we're going to use this format for the other odd ones so it's going to be consistent great and then now we check if this is a max equals if a is the current index is greater than max we want to say if it's true we change it else we keep the max and now else we do the same well we do this plus a you just have to add one right and then we can keep this and then we return max great and then what we need to do is that we create the conditions that complexity time complexity so we know that we're looping through n here so it'll be of n and for the space complexity we're creating a new array here and this new array is however long n is so it's going to be oven so that is how you solve this problem thank you
Get Maximum in Generated Array
kth-missing-positive-number
You are given an integer `n`. A **0-indexed** integer array `nums` of length `n + 1` is generated in the following way: * `nums[0] = 0` * `nums[1] = 1` * `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n` * `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n` Return _the **maximum** integer in the array_ `nums`​​​. **Example 1:** **Input:** n = 7 **Output:** 3 **Explanation:** According to the given rules: nums\[0\] = 0 nums\[1\] = 1 nums\[(1 \* 2) = 2\] = nums\[1\] = 1 nums\[(1 \* 2) + 1 = 3\] = nums\[1\] + nums\[2\] = 1 + 1 = 2 nums\[(2 \* 2) = 4\] = nums\[2\] = 1 nums\[(2 \* 2) + 1 = 5\] = nums\[2\] + nums\[3\] = 1 + 2 = 3 nums\[(3 \* 2) = 6\] = nums\[3\] = 2 nums\[(3 \* 2) + 1 = 7\] = nums\[3\] + nums\[4\] = 2 + 1 = 3 Hence, nums = \[0,1,1,2,1,3,2,3\], and the maximum is max(0,1,1,2,1,3,2,3) = 3. **Example 2:** **Input:** n = 2 **Output:** 1 **Explanation:** According to the given rules, nums = \[0,1,1\]. The maximum is max(0,1,1) = 1. **Example 3:** **Input:** n = 3 **Output:** 2 **Explanation:** According to the given rules, nums = \[0,1,1,2\]. The maximum is max(0,1,1,2) = 2. **Constraints:** * `0 <= n <= 100`
Keep track of how many positive numbers are missing as you scan the array.
Array,Binary Search
Easy
2305
621
hey what's up guys Nick white here I detect Cody stuff on twitch and YouTube check the description for all of my information please like and subscribe this video as it helps me grow my channel doing the hacker rank doing the leak oh got the playlist algorithm explanations and stuff got hundreds this is task scheduler 621 this is given a char array character array and array of characters representing tasks a CPU needs to do it contains capital letters A to Z where different letters represent different cat tasks okay so we have capital letters in an array and each capital letter represents a different task so a is a different task than Z a is a different task than B etc but all A's are the same task okay tasks can be done without original order so there's no ordering the tasks have to be in okay each task could be done in one interval for each interval CPU could finish one task or just be idle okay so for each interval the CPU could do work on a task or it can be idle ok so it's either gonna do something or do nothing however there is a non-negative nothing however there is a non-negative nothing however there is a non-negative cooling interval n that means between two of the same tasks there must be at least n intervals that the CPU are doing different tasks or nothing you need to return the least number of intervals the CPU will take to finish all of the given tasks ok great so basically there's all these tasks alright let's just look at this like AAA BBB so a is a different task than B right these don't have to be done in any particular order now how fast can we finish this task once we do an a there is this cooldown period of two where the CPU cannot do an a again right so a is a task it does one a right now it has to do something else for at least two intervals right so it can do B and then it can sit idle because once you do B you have to also wait to go back to B okay so you do a you wait you know no you do a then you do a B then you remain idle then you do an A then you do a B then you remain idle and you then you do me and you're done so that's eight one two three four five six seven eight right okay great how do we do this so basically what I was thinking off intuition is like okay well it's good to know it's just good to know how many of each task we have to do and it's characters so we're gonna make a little char map showing like the frequency of each task is a character so it's you know just a basic in Turay I do this like you can do call it tasks frequencies you call it char map I like to call it char counts usually but I'll just call it charm map in this case it's a new int its size 26 for the length of the alphabet and it each index like index 0 will be the number of ties we have to do index 1 will be the number of beats because index 0 is a is index 0 in the alphabet you know the first letter in the alphabet right so we're just gonna loop through for char C and tasks is just a char array already so we don't have to do two char array then we just do char map of C minus capital a because these are capital letters this will get us to the index in the array of the current character so we're living through we see a so we do char map of a minus a that gives us 0 and then we increment the frequency because we saw an a we see an again a minus a plus so now it's 2 in index 0 then it's 3 and then next year then when you go to B that gives us index 1 plus now it's a nice one too you know what I mean so we know how this works very easy yeah you know typical thing now what we're gonna do is we're gonna sort we're going to sort the tasks we're gonna sort the char map so the char map is actually gonna look like you know like this is the example 3 and then a bunch of zeros because it's just a B's are the tasks and then everything else is zeros so we're gonna sort so that we have the most frequent task is at the very end of the array so we can get the max value right we can get max value the most frequent task is going to be equal to a char map of 25 which is the last letter of the elf like it was size 26 so when we sort it these don't have to be done in any certain order so we're not access the index for Z and getting frequency of Z anymore because we sorted it with these this is sorted by frequency of tasks so you might want to imagine it like that at this point it went from you know a charm app to frequency of tasks now the most frequent tasks is the last index is 25 now what we want to do is we want to calculate the number of spaces this is explained in the solution although I wouldn't amend the solution explanation its paragraphs and it really doesn't make sense to me but basically we want to imagine how many idle spots there are for you know a current character right and that's going to be based on the cooldown period so we'll just imagine every spot that we have to waste after doing the maxvill task as an idle period right so we'll say you know idle slots will be equal to max Val times n because like for example if well first of all when we get the max value while we're gonna do is we're gonna access that most frequent the frequency of that max value and we're gonna subtract 1 because we don't need to actually wait we don't need to wait on the very last occurrence right we do a be idle but on the last one we don't need to wait anymore it doesn't matter so we're gonna do minus 1 for that reason okay now I know slots is equal to max Val times n because for each character when we do have to wait we have these slots that we have to fill right so we have in n slots right so these two these first two we have to fill the last one doesn't count we don't have to fill those slots because we're not worried about it anymore we just have to do whatever but for these two we have to fill these like two times two is four we have to fill those you know those extra slots up with some tasks or idle you know things so we have idle slots and then what we do is we calculate the arrow slots and now we just loop backwards through the rest of the tasks and we want to fill those we make we think of everything as idle so we just think of oh we'll just fill everything with idle these intervals that we have to fill up so for this a we have to fill two spots to go back to a I will just fill it up with idle this say let's fill it right that's not optimal though so now what we want to do is loop backwards and try and fill it up with actual other tasks like B for example so B does exist and what we'll do is we'll just subtract those from the remaining idle slots right so we don't have to do idle so we'll get rid of some of these idle ones by filling it up with tasks and that will just be math dot min of char map going backwards because going backwards it's sorted by most frequent tasks at this point so going backwards we're gonna get these most frequent tasks right here and the minimum between you know the most frequent tasks and if it was equal to the max value or then we're gonna all we're just gonna pick the minimum between that and the max value because we that one we also you know we want that minus one there because we you know we just fill it up evenly and then the last one doesn't matter you know I'm saying so that's pretty much it and then whatever is left over if you couldn't fill up all those idle slots with these tasks like whatever tasks you also had besides you know maybe a if there was no B or you know there is B but we still have idle slots left over only you know fill it up you know we're gonna do this we're gonna say ok return idle slots if it's greater than 0 that means they're still idle slots left so we have to execute at least those idle slots plus all of the tasks otherwise that's just tasks that length so just to explain this one more time where's the length of this one two three four five six there's two idle slots we could not fill up with other tasks so those are getting added in addition to all up because we have to complete every task so no matter what we're gonna have to complete every task but we want to try and fill up all of those idle slots if we can't we're gonna have to do idle slots plus tasks outlined otherwise we're just gonna you know we filled up all the other slots so we can actually just do it's just going to be we just have to execute all the tasks so that's pretty much it you can walk through this code a little bit if you want to the sorting doesn't ruin the time complexity because you're sorting on an array of size 26 you know if you don't want to sort and you really want to be strict about it you could just make a max variable and then find the max value by doing a for loop and finding it you can do it either way this doesn't ruin the time complexity though because it's size 26 now once again if we look through you get you can look through this yourself so you fill up the charm app write the charm app is three zero then we sort it right so it goes backwards most frequent tasks at the end we get the max value it's three then minus one from it is to idle slots is two times two which is four so we have to fill those up we do idle slots -2 because idle saw it's minus equals -2 because idle saw it's minus equals -2 because idle saw it's minus equals the other test was three and we do the minimum be three at three and if it was equal to the max value we do the max value because we don't care about the last one we fill up two of those slots there's two idle slots left so we return two plus six which is eight and that's what we got for this example I think guys for watching please like it subscribe let me know if you have any other questions about this or if you have another approach this is another equally efficient approach called using priority queue maybe I can go over this in another video but yeah maybe we want to check out this it just looks a little more jumbled up and this seems like a more intuitive and cooler solution so I mean like a look at it's a lot simpler it looks like so maybe check out this priority queue solution as well I do not like for this problem like look at all of this gibberish they I don't know I couldn't read it and it was that I was having a tough time thank you for watching that's it and I'll see you in the next video All Right see ya peace on earth
Task Scheduler
task-scheduler
Given a characters array `tasks`, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer `n` that represents the cooldown period between two **same tasks** (the same letter in the array), that is that there must be at least `n` units of time between any two same tasks. Return _the least number of units of times that the CPU will take to finish all the given tasks_. **Example 1:** **Input:** tasks = \[ "A ", "A ", "A ", "B ", "B ", "B "\], n = 2 **Output:** 8 **Explanation:** A -> B -> idle -> A -> B -> idle -> A -> B There is at least 2 units of time between any two same tasks. **Example 2:** **Input:** tasks = \[ "A ", "A ", "A ", "B ", "B ", "B "\], n = 0 **Output:** 6 **Explanation:** On this case any permutation of size 6 would work since n = 0. \[ "A ", "A ", "A ", "B ", "B ", "B "\] \[ "A ", "B ", "A ", "B ", "A ", "B "\] \[ "B ", "B ", "B ", "A ", "A ", "A "\] ... And so on. **Example 3:** **Input:** tasks = \[ "A ", "A ", "A ", "A ", "A ", "A ", "B ", "C ", "D ", "E ", "F ", "G "\], n = 2 **Output:** 16 **Explanation:** One possible solution is A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A **Constraints:** * `1 <= task.length <= 104` * `tasks[i]` is upper-case English letter. * The integer `n` is in the range `[0, 100]`.
null
Array,Hash Table,Greedy,Sorting,Heap (Priority Queue),Counting
Medium
358,778,2084
958
hello welcome back to my channel i'm here to do my 100 little challenge today we have the code 958 check completeness of a binary tree given a root of the binary determine if it's a complete binary tree in a complete binary every level except possibly the last is completely field and all nodes in the last level are as far left as possible so if can have between one and two h nodes inclusive at the last level h an example in here you see one two three is fielded but only four five six and this level is not fielded fully but they are to the left side as left as possible so it's true but in this case so 7 could is in last level but 7 could be on the left side but it doesn't so it's false this is the idea of this question and to solve this one we can use a q and in the top and have a boolean checking if it's the last node right now and now in here we put one into the queue first and if c if one is no or not it's not then we put two and three in there so we reach the second level and after now we have two and three in the queue and we pop two first and check four and five we put four and five in that place we keep doing that until we see we pop out a no for example in here three have six and no we put six and no inside the queue then in that time at that time the queue will have four five six and no and only when you pop out a no at the last time then the last will become which is the boolean that we have will become true but in this case when we process 1 2 and then the queue we have four five note and seven at that time we have four five get pop out and then now we process no in the queue no will be taken out from that queue but in the same time now we see we meet a node already so that boolean that we set will become true and later on we will see any node later on then that gonna be a false if you see um note after that boolean become true then this is false that's the idea so let's take a look at that code now we have boolean set up as last equal to false so it's not false at the beginning i mean it's not true at the beginning we didn't have the we didn't reach the last note yet and also we have a queue that take in tweet no linked list and first after we have a cube right now we put um root in there because we need to process this root we check while the queue sorry is not empty then we need to do something first we take out the next node as a current that we need to process equal to and then we check if current equal to no or not if it currents no that means we reach to the last node so large will become true at this time so if current node is not no so we check if last we reached the last point already so if we reach to the last point and we still have note coming out coming in that mean return false this note is not complete else um let's see oh sorry shouldn't have this one uh we will do because now we are holding a current note right we want to push that left and right inside that queue so current.lab will be pushed so current.lab will be pushed so current.lab will be pushed will be added to the queue and also current.right and also current.right and also current.right so put 11 right inside that queue we keep track of next level so after this whole while loop then we should return true at the end then let's see so now this case pass and submit it cool uh i think this is a really good practice it took me a while like have some mistake and stuff but overall this is uh should be easy question it be a medium question if you have any questions please comment below and i'll get back to you as soon as possible otherwise i'll see you in the next video bye
Check Completeness of a Binary Tree
sort-array-by-parity-ii
Given the `root` of a binary tree, determine if it is a _complete binary tree_. In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`. **Example 1:** **Input:** root = \[1,2,3,4,5,6\] **Output:** true **Explanation:** Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible. **Example 2:** **Input:** root = \[1,2,3,4,5,null,7\] **Output:** false **Explanation:** The node with value 7 isn't as far left as possible. **Constraints:** * The number of nodes in the tree is in the range `[1, 100]`. * `1 <= Node.val <= 1000`
null
Array,Two Pointers,Sorting
Easy
2271,2283,2327
151
Suggestion or going to solve question number 151 shift setting on list subscribe button subscribe channel that their shoaib start tweet a to whom tweet a 200 Vikramaditya single password have to this accused word supporters and painted storks subscribe warning will start from dengue it boils Creative 1.2515 And Subscribe And In This Page Guys Can Do Subscribe To Our Okay So Let's Quite Clear We Will Take Available And In Which We Can Share And Subscribe Okay Lipstick To-Do List Subscribe Okay Lipstick To-Do List Subscribe Okay Lipstick To-Do List Solve One After Another Will Be The World P And employment provided from attending to shooting this from first to last for this would start with I did you all chief constructive work should also in the court should start from the channel subscribe the channel the effigy of word is not hai and they can See what you can do that this note request 20's discrepancy is work is ok so son of Veer Vikram if you will be constructed subscribe and subscirbe that and if this note caret only that this notification dam water will do it is it world will insult director subscribe 210 Right Is Veer Vikram Award Is Industry 108 Names Of Equity And Reddy Subscribe To This Notice Width Stopping To Solve Vikram Hai Haldi So And What Will Have Value Of P International Federation Of Bus Apart From This Institute In That After All Sandal Or 125 LMB Thank You Doctor Space Android will give will not be question in this case Thursday this side dive with answers in the answer loot space 200 oil my tab space tu dance on that aapke looks good at 9pm to his definition of the word sorry tweet custom export hai ho gya Have so writing Kabir we live raw Which is not at What we can do is rough and tough Look back in its place Which can also you will notice That there will always be extra space in width Have alert Tried to run in this court Sun stayed in shift Juice Print Mistake For Wing Stayed In Stringbuilder It's Getting Exposed Or Status And Different A Simple Please Like This That Singer Babu Now Stayed In Selves Video Clipping Tried To Submit It's N C What Happens Aa Jaa So Add Box A Solution Is Not Very Good As You Can See But It's Rocking Guys How We Can Improve
Reverse Words in a String
reverse-words-in-a-string
Given an input string `s`, reverse the order of the **words**. A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by at least one space. Return _a string of the words in reverse order concatenated by a single space._ **Note** that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. **Example 1:** **Input:** s = "the sky is blue " **Output:** "blue is sky the " **Example 2:** **Input:** s = " hello world " **Output:** "world hello " **Explanation:** Your reversed string should not contain leading or trailing spaces. **Example 3:** **Input:** s = "a good example " **Output:** "example good a " **Explanation:** You need to reduce multiple spaces between two words to a single space in the reversed string. **Constraints:** * `1 <= s.length <= 104` * `s` contains English letters (upper-case and lower-case), digits, and spaces `' '`. * There is **at least one** word in `s`. **Follow-up:** If the string data type is mutable in your language, can you solve it **in-place** with `O(1)` extra space?
null
Two Pointers,String
Medium
186
151
in this problem we have to reverse the words of a string and uh within the word the characters will remain the same so here this is one word world followed by this is exclamation so this remains as it is so the last word will become first word second last word will become second word and similarly first word will become last word and there are some more conditions that input may have some extra spaces in the beginning one or more spaces and even between the words it may have one or more spaces at least there will be one space between different words so space is the only delimiter here so in the result we should not have either leading zeros or trailing zeros we should get rid of all of those and even in between words if we have let's say three space here in the result we should have only one spaces so if there are ten words there should be nine spaces between those one between each pair so let's see how we can solve it so the idea is to uh try to find the words so we start with two indices we keep track of the beginning and end of word so we start traversing from the left in this string let's call it s and we keep a index i equal to zero is the first index in a given string so we start i from zero that is first character this may be space this may be a non space character as well so we keep incrementing i so while i should be less than s dot length let's call it n so while i is less than n and s of i is equal to space so i denote the beginning of word and we will keep another index j that will denote where the word ended so this will denote ending or one more than ending so this way we will start from the beginning so no matter how many spaces are there we will keep incrementing this i so in this condition we have to do nothing but keep incrementing i until we find a non space so if both conditions are satisfied we will keep incrementing here it is a space we will move i here also there is a space so we will move i here now it is not a space so it will come out of this loop so i will remain here at the h letter then we will have another variable j equal to i plus 1 so we will start j immediately next of it so j is initialized here and here what we will do while j is less than n so n minus 1 is the last index if the length is n so that's why n is not a valid index so we stop as soon as we reach n and s of j is not equal to space so j is less than n and this is not a space so keep increment incrementing the j so i was looking for non-space j so i was looking for non-space j so i was looking for non-space and j is looking for space first space that it encounters so again not a space so move j here again it's l move j now as soon as it goes just after o here there is a space so this loop will end so now i is pointing to this j is pointing to this position so we can find this substring so get the substring out of that s dot sub str so whatever is the syntax of substring in the different languages in c plus its first one is the beginning index which is i second is the length of substring so it will be here j minus i in java it's first index and one passed the last index so in java it will be exactly s dot service substring i to j so this is java this is c plus and in python it will be similar we will have a splice s i 2 j so this is in python so this way you find this substring and this will denote a word us call it w so we will not include a space is not included in this only the word and we will keep a result so initially result is empty so there are two conditions either this is the first word in the result or we have already some words so if it's first word simply make result equal to w so this w is hello so it will be hello and no spaces next after this loop this is w we put result equal to or we put it in the beginning so that next word again comes in the beginning so let's call it w so w plus space plus result but you have to add a condition here that if result is empty then don't add this part if result is not empty then add this word add a space and whatever was the earlier result so this is conditional so after this where should we move i so we have taken this word and j was pointing to space so no point in checking for j itself you can keep i here also but let's move i 1 more than j i equal to j plus 1 and again this loop will continue till outer loop is i less than n so while this is true keep repeating this so now i is here it's a space uh and it's less than n so increment i may be there is one more space again increment and when it reaches here i stops here and j will be or where is j is one more than i so j will start from here until it finds a space it will keep moving next when it reaches here it stops so again we take the substring this time it will be world so this time the result is not empty so we will add this part also so result equal to w will be this world exclamation then this space then earlier result which is hello so j is here i will come here and while i less than n and it's a space increment i so i will increment here and now i becomes exactly equal to n so we stop and we return this value so this is how we can solve this problem uh there is a follow up problem here that for c plus procedures try to not use any extra space use open space so we can modify it slightly the logic will be modified since we are inserting in the beginning instead of result we will modify in the input string itself so what we will do uh let us say j is here this is the input string so we will delete everything and we will insert the w in the beginning and then keep track of till what index what was the earlier older j index so it was here and what is the i now next i so i will be this one so you can find out how many spaces were there so you will trim those many spaces and recalculate this n so whatever n we had saved so there will be a new n due to deleting of some space this n will it may or may not decrease so if it decreases by 2 then what we have to do we have to decrease 2 from this i also since we deleted 2 spaces so this w will shift left and then you should shift this i also here or you may keep it at older j so this is how you can modify it and keep updating in the string itself so now let's write the code for this so you are welcome to try this approach uh using the idea that i just said you may have some different idea so this is the empty result i equal to 0 and let's keep the length since we will be using it quite a few times so we can store it while i less than n if result is empty then this is the first word so result is equal to sub this sub is the word that we saw in the explanation substring else if there are already some words in the result then result equal to this new word in the beginning plus one space plus older result and then i equal to j plus one and this again will continue for the next word until it reaches to the end and the solution is accepted so what is the time complexity here we are doing one scan of this word and nothing more than that we are also picking substring from here to here so this will be o of word length again we will scan from here to here again of word length so total it will be o of number of characters in the original string and space we are using a result as extra variable so you can think of it as order in space but we can modify this logic slightly with the idea that we just discussed to update this input string itself and result that updated string now we will write this in java and python and the java solution is also accepted finally we will do it in python 3. so we can do all of this in one line and the python solution is also accepted
Reverse Words in a String
reverse-words-in-a-string
Given an input string `s`, reverse the order of the **words**. A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by at least one space. Return _a string of the words in reverse order concatenated by a single space._ **Note** that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. **Example 1:** **Input:** s = "the sky is blue " **Output:** "blue is sky the " **Example 2:** **Input:** s = " hello world " **Output:** "world hello " **Explanation:** Your reversed string should not contain leading or trailing spaces. **Example 3:** **Input:** s = "a good example " **Output:** "example good a " **Explanation:** You need to reduce multiple spaces between two words to a single space in the reversed string. **Constraints:** * `1 <= s.length <= 104` * `s` contains English letters (upper-case and lower-case), digits, and spaces `' '`. * There is **at least one** word in `s`. **Follow-up:** If the string data type is mutable in your language, can you solve it **in-place** with `O(1)` extra space?
null
Two Pointers,String
Medium
186
242
hi everyone welcome back to the channel and to and solve e code daily challenge problem 242 so we will be looking to the problem statement which we have received then we'll move towards the solution or the approach which we have used and the solution itself so starting with the problem uh the problem says we will given two strings SNT and we have to find out if both these strings are anagram to each other not okay and the definition they have also given the definition of anagram is a word of phrase formed by rearranging the letters of different word of phrase typically using the original letters exactly once so uh the Crux of the whole statement is we have to basically find out if both these statement uh have both these strings have exact number of occurrences of each letter or not okay if yes then we can say that both strings were anagram to each other and we'll return true if not then we'll simply return false okay so coming to the solution like uh this problem can be tackled in multiple ways for example what I can do is I can simply sort these two strings and uh you know compare if both the strings are equal or not okay but when in when you are in an interview setup you know this is not what our interviewer is looking for so we will follow a more technical approach so what we're going to do is I am going to yeah I'm going to use hashmaps or dictionaries uh to solve this question and if you see what we are doing over here is we are just simply uh taking the number of currencies we just simply calculating the number of occurrences of each character for example let's say uh let me use some other yeah what I'm doing I'm just iterating the string s okay sorry uh yeah I'm just iterating the string s and incrementing in the number of occurrences of each character for example I started with a there was no occurrences by that time I'll initi like assume that everything was initi Zero I'll add one in it then next we'll get a again we'll again that one in it and so on so forth for each of the characters okay so this is what I'll do like I'll just go through or iterate through all the elements in s all the elements in T and at the end I'll just simply compare if both my dictionaries were equal or not that's it this will be the approach which we'll be using coming to uh coming to the solution of it as you can see like as discussed what I'm doing over here is yeah there's a base uh condition which I have checked over here in which what I'm doing is I'm just checking if uh both the if the length of both the strings are equal or not because if the length is not equal itself then you know there is no need to check anything else right we can simply say okay uh this these two strings were not anagram because of course like we won't be able to use uh all the characters with each other right if the length is equal what we'll do is we are defining two hash Maps or dictionaries whatever you want to say for S and T and as we know that lenss are same then I'm just simply taking the index into consideration and as I said like what we're doing over here is uh let's say we used anagram okay the first letter was a but at this moment we don't have anything in the dictionary right so this get method makes sure that we don't get a key error while doing so right and what we are doing with the second parameter is we are initializing everything which is not yet in the dictionary with this default value okay so for example we encountered a we saw that a was not there so we initialized it with zero and added plus one next time when we'll encounter a again then uh we'll get one over here because the key was there in the dictionary okay and we'll add one into it so it will become two and we you know just keep following this approach uh for each of the character once we have both the hash Maps what we are doing over here we just simply comparing as we discussed right so let's check out the test cases yeah so the test cases got clear let's submit it for further evaluation and is you can see uh the solution got accepted and I would say we have performed decent uh so yeah this was the solution guys thanks the time for watching the video stay tuned for the uping ones don't forget to subscribe to the channel thank you
Valid Anagram
valid-anagram
Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** s = "anagram", t = "nagaram" **Output:** true **Example 2:** **Input:** s = "rat", t = "car" **Output:** false **Constraints:** * `1 <= s.length, t.length <= 5 * 104` * `s` and `t` consist of lowercase English letters. **Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
null
Hash Table,String,Sorting
Easy
49,266,438
43
oh yes let's do it right a problem at Lee code multiply strings given to non-negative integer N 1 and 2 non-negative integer N 1 and 2 non-negative integer N 1 and 2 represented as strings you turn the product of n number one and then two so how we gonna do this we are going to take this piece st. 1 s new strength buckler's with no one we got averse g string and convert them into trains again so basically we are trying we are reversing the strength because this will make life easier for us case here the problem is our number it starts from your right to left but strings start from left to right sure by exchanging the order reversing the order we can easily you know do operations on string oh yeah thinking of them as number then we're going to have an integer rate and new integer the size is going to be this one length plus is to length once you have this we are going to have a follow I equal to 0 I smile and s double n so X 1 dot length I flat 4 and J equal 0 intraday J equal 0 j s 1 and s 2 length j plus purpose okay we're going to have an I plus K is equal to I plus k plus 1 dot character and I my minus 0 into S 2 n 2 X 2 dot character I hacked J minus 0 so it's happening here is if you think of it this I represent the unit digit of the s 1 number and J is equal to 0 is the unit digit of the extra number and these are the degree of significance that each number has so once we had this ready we are going to have strength result is equal to MU drink and we are going to go to our Eric which we have just created logic is simple digit is equal to M hi mod of M and carry equal to I divided 10 once I have beat there is go check if and uh I plus 1 is smaller than and dot if a test and I'm going to have and I plus 1 equal to and I plus 1 plus K and I'm going through I is equal to I get plus an S or XP in my the reverse order so after this is done we shall return our yes ok one more thing that we have to do while I is dot length is greater than one and I s dot characters at zero is equal to zero and is equally is stop substring one so giving you getting rid of Asia area leading zeros okay this is working somewhat does awesome thank you guys thanks
Multiply Strings
multiply-strings
Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. **Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly. **Example 1:** **Input:** num1 = "2", num2 = "3" **Output:** "6" **Example 2:** **Input:** num1 = "123", num2 = "456" **Output:** "56088" **Constraints:** * `1 <= num1.length, num2.length <= 200` * `num1` and `num2` consist of digits only. * Both `num1` and `num2` do not contain any leading zero, except the number `0` itself.
null
Math,String,Simulation
Medium
2,66,67,415
1,239
all right let's talk about the maximum length of concatenating string with unique characters so you are given the list of string array and then uh you want to concatenate every substring inside the array and then you have to return the maximum possible length of x right so in this version i'm going to use the different search so i'm going to try every single possibility and if there's a duplicate character inside the substring i'm going to skip this substring this string to my answer and now just find out what's the current every what's the current uh length for every single string right and then if this if the starting index is used right i would definitely move forward to the list index and i'll just keep traversing and this is going to be pretty much it right so for every single stream and i need to check if there's a duplicate character right so i will have a function to just keep track so i'm using the content array to keep track of the cubic character so this is going to be pretty much it right and let me start recording i do need to return the value so i'm going to call max which is going to be global variable and i'll just return max right here okay so i'm uh i need to uh use recursion and this is definitely called default so i'm going to start in the regular sub screen and pass the index and pass an empty string all right now i'm going to call the cover function load vfs list option array hinge index string f so i will concatenate in the substring in an array uh into the string x and then i need to create a hover function for what so boolean and i'm going to call unique passing the string s and check every single string so checking every character in the inner string is actually unique right the center 26 go in uh for char sorry for child c to extra tutorial and then i'm gonna just uh adding my counting array first so c x e minus i plus so if let's see minus a and expression could be two you'll become close and at any angle control right so i would definitely make this for cleaner later but i'm going to just focus so if you need s if this is unique of x right so uh you need to so you need profess i need to add update my current max lens right what happens if the default you are definitely going to return and we are using the definitions recursion so in this could be autobahn right so we have to uh send all a set of limit to a rate of sense all right so how do we traverse on fabric i am not traverse one view and coverage from index because i already passed it in this video right here so i understand the radar size i have plus i'm going to just focus search i'm going to pass in one array i'm going to pass it in basic and it's going to be i plus one i'll move on my next index but before i move i need to add the string together so i will have a contact content in the stream together and this is going to be building up pretty much it right so let me submit and then here we go all right so again so let's not talk about my timing span i'm going to make this clean so if you want to just add in uh so this line is actually what uh counting c minus a and then you increment so which means you increment after this line be honest right so i can actually do like this c l c minus a adding and which is greater than zero so you will actually compile this line and then after the compile uh after the compile you will just increment the territory inside the frequency code so this is still going to be doable so if you don't know the logic so just go watch what is the increment after and implement before like there are definitely two different meaning but let's talk about how many space so for every single substring in the range in the list of stream right you either peak or not pick right so you have two options and every single substring has two options you either pick or not pick right and if you're not picked right you are going to skip right so how many subs in the rate it's going to be un uh unsubstituting right so it's going to be two to the n for the time and the first phase is going to be all of them this is because every you can combine every single string together right so this is open and this is going to be pretty much in the solution and i'll see you next time
Maximum Length of a Concatenated String with Unique Characters
largest-1-bordered-square
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. Return _the **maximum** possible length_ of `s`. A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** arr = \[ "un ", "iq ", "ue "\] **Output:** 4 **Explanation:** All the valid concatenations are: - " " - "un " - "iq " - "ue " - "uniq " ( "un " + "iq ") - "ique " ( "iq " + "ue ") Maximum length is 4. **Example 2:** **Input:** arr = \[ "cha ", "r ", "act ", "ers "\] **Output:** 6 **Explanation:** Possible longest valid concatenations are "chaers " ( "cha " + "ers ") and "acters " ( "act " + "ers "). **Example 3:** **Input:** arr = \[ "abcdefghijklmnopqrstuvwxyz "\] **Output:** 26 **Explanation:** The only string in arr has all 26 characters. **Constraints:** * `1 <= arr.length <= 16` * `1 <= arr[i].length <= 26` * `arr[i]` contains only lowercase English letters.
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
Array,Dynamic Programming,Matrix
Medium
null
456
guys welcome to the channel this is vaga we are going to do another leech good question and the question in question is number 132 um no number 456 132 pattern right so we are supposed to get um the 132 pass and in this case the 132 pattern is where one we have um we have a number such that um we have an array right an array of integers and we have um in the array the elements there should be one element which is the minimum one element which is higher than the minimum and then one element which is the midpoint right so in this case one two three four you should and then you return true whether or not it's true right in this case we have one two three four this is not true but three one four two we have one which is the minimum four which is the greatest and then two which is less than that right and ideally they're not supposed to be in any to be in order and we are also supposed to do it in all o and log n or o of n right instead of using you could if you want to use um three loops right the easiest will just be to use three loops right just um check that i that j is greater than i and then k is lesser than j right so basically that but we are not going to do that we're going to use of course we're going to do and try and sort to sort it out in a better time complexity than um using three loops right so um how we could do this is we could come here and um the first thing we do is we create a minimum array right so we could call it something like um min list right we're saying min list and here what we do is we put in the minimum number right so this n is just gotten from the third example if you can look at that examples we have nums there so we're going to work on this and conceptually have a look at it and then possibly um possibly solve it right so um what we're looking for here is the value of i right um because it's i j k so i is the first uh this let's come and say i j and k what you're looking for here is the value of i right so here we push in the minimum at each element for each element it's going to be as long as the nums array in this case our n array right so we could have negative one is um three greater than negative one no so we have negative one and we have negative one okay one two three four basically that right it's supposed to be the same length right and um we then create a stack uh a stack and in our stack where the stack is going to look for the value of k right so we have our stack here and it's going to look for the value of k right and uh we start off by putting in our first element in this case 0 and then um we loop through our array backwards right that's where we're starting with zero right so we look through our array backwards um and at each point we compare the various numbers right we compare uh we move for example we consider k this number to be the first candidate for our k and then we move our rate down to two in this case right so we check um is for k is zero uh a possible contender for k yes so 0 is a possible content of k um is negative 1 i is going to be negative 1 at that position so we have um i in this case is going to be negative 1 right and then we move our pointer down to two right is two the highest of those three yes so we do have um j being two so in this situation we're supposed to return true right um so we have um our ijk being i being negative one j being um j being uh two the highest and uh k being zero right so that's how we would move and um at each point we pop off things on our stack and put them back right the satisfying condition is um whenever we come to our main list and check that our mean listing i is less than the top number in our stack right this is our stack and um and it's less than nums uh the array at i right so the top of our stack and whatever is on the array at i so in such a situation we just return true so basically that is the idea of what you're trying to do and now we have to put it in good the length of um of nums of the set of nums is less than three right if it is we just need to return false the reason for this is we need at least um three elements to have the one three two right we the one three two pattern right so basically in such a situation we return false right after that we need to create a min list and our stack right so we say min list and this is just going to be an empty array like so and after that we have our stack and our stack is just going to be an empty array also like so and um we start off our main list by appending um the very first number and we say min list and what we want to append is we are going to append um the very first number and that is zero like so and um after we append that number we loop through our array right and um we create our minimum array right aside from just appending the first number we can create our minimum array right and for that we just save um for i in re let's just play correctly range and uh we want to go from the second element because you put the first element to the rest of the array and that's land numbers like so and um we append the minimum of everything before the current element being looped right and for that to just say min list and what we want to do is we just want to append and what we are going to append is going to be the minimum in the array at of everything before the current element right so we just say i like so in this situation we have created our main list and we can continue from there back of the array right and um we're going to use the stack to determine the two in the 132 pattern so we check through right and um for that we could just come here and say come down here and say for j in range and the range is going to be um the len of nums minus one like so and um we want to go backwards remember and we want to go all the way to the beginning so we do that so that's it ends before the negative one that is it goes all the way to zero right so that's what the second negative one is for right so for that we are going to remember we're looking for the two in the 132 pattern we check if nums j is greater than the min list at j right um and we move to our stack and uh we remove everything that is less than the current min right so we come here and we say um we say while stack and stack -1 is less than and this is going to be -1 is less than and this is going to be -1 is less than and this is going to be less than or equal to our minimum at that point right we just pop it off the stack right remember we're looking for the two uh the two in this case on the pattern like so um we check then if the number at the at the top of the stack is lesser than um is less than j right so how we do that is we say if stack we have to have a stack and stack is less than j remember it's going to be less than or equal it has to be less than j right because of the 132 button and if that is the case we just return true because we have hit our goal in this case right and at every point we just append numbers j right so we say stack dot append and what we want to append is nums j like so and um after all this what we want to do is we want to return false like so over our code quickly um first we create a minimum array and um we append all the values right then we start iterating from the reverse of the array like over here that's what we do and um uh we're going to use the stack to determine the 2 in the 132 button and at all positions um we push all elements if they're greater than um if they're greater than what is in the minimum array that is because we're looking for the 2 in the 132 pattern and then at any position we remove in this case we pop everything we remove everything in the stack if it is less than or equal to the minimum right because it's in invalid to form the 2 in the 132 right and um the satisfying condition is that the that's the top of the stack is greater than the minimum and uh we come across a number at i which is also um we come across a number at i which is um greater than what is in the stack right because the stack looks for our two right so we get maybe an at numsai we get a number that is greater than um uh than the stack uh the top of our stack and then it's also greater than the minimum that's when we form the 132 button so if we run our code and then we submit it we should get an answer right so we run our code and we submit it and it is accepted and um the time complexity is of course of n and uh the space complexity is also over and we created but we create a bunch of structures and they're going to be as long as our numsery so thank you for watching subscribe to the channel if you're new and i'll see you in the next video
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
39
hi everyone welcome back to lead coding i am your host faraz so in this video we are going to solve another question called combination sum and as you guys have already a good practice of recursion and backtracking if you have been following my playlist so you can just try this problem by your own you can go to the description find the link of the question and try it by your own if you're not able to solve and if you want to know the optimized approach you can just come back to the solution and continue watching the video okay so let us see what the problem statement is we are given an array of distinct integer candidate and a target integer return a list of all unique combinations of candidates where the choosing numbers sum to the target you may return the combination in any order the number may be chosen from the candidate as unlimited number of times okay so we can see the example here this is the candidate list and this is the target is seven now we should choose number from the candidate such that all those numbers this sum up to the target the first example is two and three so two the number two we are picking it two number of times and the number three we are picking one number of times the number six is zero number of times the number seven is again zero number of times so we will attain this configuration two and three and the submission is 7 here now we can see there's another solution that is the only number here is 7 so we are picking 2 3 and 6 0 number of times the frequency is 0 and 7 the frequency is 1. so we have to generate all the possible solutions this way now let us see let us go to an example and see how we can do this using recursion and backtracking so here we are given the candidate as two three and five this is the candidate list and the target is eight so we will be starting from the first element that is two so for two we can either skip it or we can include it into the solution so we have two options the first option is to simply skip two so if we skip two we should move on to the next element so we should just delete it from the candidate list because if you are skipping it we won't need it in future as well so the candidate list will now be three and five and what is the target that we need now the target we need is still 8 we still want to generate it and in the solution space we don't have anything because we didn't include the last element now here if we picked up the first element that is 2 so in that case we are not going to delete it from the candidate list why so because if we are picking 2 we might need it in future as well we might pick it in future as well so 2 3 and 5 will still remain in the candidate list the target will now reduce to 6 because we have already let me just make some space over here so yeah let me just make it here we have 2 3 and 5 into the candidate list the target will now reduce to 6 because we picked up 2 and 2 will now come into the solution okay let us explore the left hand side of the recursion here we have again two possibilities the first one is to skip three so we skip three five will remain to the candidate list so five is still here the target that we need is still eight and the solution is empty if we pick up three then the target that we need is five eight minus three is five and into the candidate list we will have three and five and into the solution we will have three okay so let me just further explore this one so we explored this one and if we skip three so if we skip three the target that we need is still five in the candidate list only five will be remaining and in this solution we will have three now here if we skip five then the target will be five the candidate list will be empty and in the solution we will have three now as we can see here we don't have anything remaining in the candidate list so we cannot reduce five to zero if we are going to explore it further so we are just going to stop here and we won't explore further now exploring the right hand side let's say if we picked up this five so if you picked up this five the target will now reduce to zero in this solution we will have three and five and the candidate will candidate list will still have five now here as the target got reduced to zero this is one of the solution so we are just going to store this three and five into the global answer or the list of solutions okay and we'll just stop here we won't explore further all right so let me just explore this side let me just explore the right hand side here so let's say we picked up this three so the target that we need is five minus three that is two and if we pick up three we will be left with three to pick up in future as well we are not going to delete it from the candidate list and here we will have three and three into the solution now again let us say if we pick up these three and go to the right hand side so we'll be having three to pick up in future as well so this will be the candidate list the target will now reduce to minus one and into the solution we will have three and three now as soon as the target get reduced to a negative number we are sure that we won't be able to make it positive or zero in the future so we'll just stop here and we won't explore further and this is not a solution okay it will just return from here so this is how we are going to do this let us just see the code for this for better understanding we are going to create a function void help in this i will start from i is equal to 0 we are going to start with i is equal to 0 and let us say if i want to skip this 2 so i can just move i to the next element that is i plus 1 and if i pick up 2 then i might need it in future as well i am not going to delete it from the candidate list and i will keep the eyes same that's why i'm using i here then we have the candidate and the target and a vector of int solution to store all the elements that comes into my solution so what is the base condition here the base condition is the target is now equal to zero so this is the base condition when the target is now zero so the target is zero this solution is one of the answers so we are going to add it into the answer.pushback and what is the answer.pushback and what is the answer.pushback and what is the answer here answer is the list of solutions so let me just create answer should be vector of factor of int i'm making it global so answer.pushback this so answer.pushback this so answer.pushback this and then return from here okay and we also saw that if the target get reduced to a negative number we should simply return from here because we have no possibility so even if you explore further we won't be able to generate the answer so return what if i is equal to 0 size if i is equal to c dot size that means we reach till the end of the candidate list we are done with all the elements we are not left with any element to pick now in that case we are sure that the target is not zero okay that's the reason why i am coming to this condition otherwise i would have returned from here so the target is not equal to zero and we are not left with any element to pick so there is no possibility just return from here there's no benefit exploring this further because we won't get the answer otherwise if these three conditions are not met then we can either skip the ith element so just skip the i-th element if we do that the i-th element if we do that the i-th element if we do that just call the helper function to i plus 1 c target will still remain target and solution otherwise we can pick the ith element so if you pick the ith element it might be possible that we will pick it up in the future as well so we are not going to increment i help off is i will remain same then c then target will now reduce t minus c of i because we are picking the ith element and the solution will now have something into it the solution should have this c of i okay all right now as we push back something to the solution we change the solution so while coming back while backtracking from here we should remove this element from the solution so pop back the last element okay so i think this is it let me just call this function from here help of zero comma c comma t must solution and changing the name of variables over here and before passing this sol i should create a vector of int as well and then return the answer let me just try to run this is basically the backtracking part it is giving us correct answer let me just submit it now and it got accepted so this is it for the solution if you like the video make sure to leave your likes and if you want more such content in future make sure to subscribe to the channel and hit the bell icon
Combination Sum
combination-sum
Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**. The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different. The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input. **Example 1:** **Input:** candidates = \[2,3,6,7\], target = 7 **Output:** \[\[2,2,3\],\[7\]\] **Explanation:** 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. **Example 2:** **Input:** candidates = \[2,3,5\], target = 8 **Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\] **Example 3:** **Input:** candidates = \[2\], target = 1 **Output:** \[\] **Constraints:** * `1 <= candidates.length <= 30` * `2 <= candidates[i] <= 40` * All elements of `candidates` are **distinct**. * `1 <= target <= 40`
null
Array,Backtracking
Medium
17,40,77,216,254,377
1,793
hey everybody this is Larry this is me doing the daily prom uh on October 23rd and we have a new weekly prom as well so let's get to it uh yeah hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problem it's a hard problem maximum score of a good Subway 1793 I'm in Hong Kong right now still uh still been a very draining week so we'll see how that goes but I am getting enough sleep so that's always good so yeah that's start um let's take a look the score of a subarray i and J is equal to Min of that um subarray time J minus I + 1 a that um subarray time J minus I + 1 a that um subarray time J minus I + 1 a good subarray is a subarray where I is less than K what's K is less than equal to J what's oh they give you K okay return the maximum possible score of a good subarray okay um maybe this is this like mono Q time or something like this U cuz well I mean this is a little bit of a cheating hint in a way in that's what um um uh and that's what uh you know that's what uh we did yesterday sorry man mind blank on trying to figure out what to say that's what we did yesterday so maybe today similar so that's why I kind of jumped to it not for any particular reasons but we are getting a minute of a supp away and so immediately I am going to try to think whether there is a sliding window right um which is the same idea but I don't know if that's true all let's look at the constraints real quick constraint is n is equal to 10 to the fifth um so it's going to be big enough that we don't we can't do anything more naive just in case that we can right um what is k i is oh actually I met I misread this good Subway part so that means that so in this case a good Subway isn't um or the this constraint part of the subway which is just um meaning that it has to contain that in Index right pretty much yeah okay so what does that mean that means that for example if K isal to three we start at uh seven right I think I don't know if I would call it sliding window but I think the way to think about it maybe some sort of greedy and sorting what I mean by that is that we'll try to go to the left one at a time or right one at a time and maybe in a greedy kind of way like here we have three and a four so we're going to choose the four first right because that changes the minimum the least uh and this one changes in a very monotonically kind of way and then next we five and three we'll choose five because that's three right so we get another score uh from their Index right and then well now that's done we forced to take a three of course given the three we could take the four as well for free um and now we calculate this and then lastly we add the one I think the greedy idea kind of makes sense right but of course as I always say about greedy uh it makes sense until you get a wrong answer you're like well maybe it didn't make that much sense it just made a little bit sense um I think I'm okay with playing around with that because I think the idea is that um and a lot of this is experience and when I say experience it doesn't always mean just like oh I memorize this problem it's about like the feeling of things a little bit um of course some of these or a lot of these feelings are backed by um experience and practice but uh but sometimes it's hard to articulate of course um but what I mean by that is that um this Min function right we basically in a way we forcing in a weird way maybe if you want to phrase it that way in that we basically um basically we're treating the step function as um like okay what is what as um like okay what is the maximum men right and then basically um you can't think of it the other way it's going seven okay and then the next one is going to be four and then the next one is going to be three and then one and then try to calculate what is the score for those uh for every time men changes and we try to uh change men in a very smallest way possible Right like the least change possible every step of the R so that's basically I think the idea that um once you um I think that's a good enough uh idea um yeah I think that's a good idea to kind of uh get started on sorry let's do it um and then here I think I'm trying to maintain a loop in variant right and the loop in variant is that every step of the way um every step of the way uh every time we make a change we what I want to say every time we make a change uh the Min changes the minimally and we have all the um in ag greedy way expand as much as we can okay so wow Loop is wow uh left is I like to write it this way or right is less than n so that means that if they go out bounds or they both out bounc then you know we're good right so okay is this the right way to WR it's a little bit a um also this is like inclusive and not inclusive so that's kind of very awkward uh okay something like this right um okay yeah then current Min or what best is the best score we have a current Min is equal to say infinity to start or actually I guess just nums up uh K and so best is actually also num sub K because yeah okay that makes sense and then now we here first we try to find the next Min and the next Min assuming that we already expand as far as we can it's just going to be if um let's see actually I like it this way I think right uh so left is St and right is yeah okay yeah so then now we can go try to find next Min by going left or right so if num sub left is greater than num sub right then we go left right um so then now here uh conmen oh no yeah is you go to num sub left right uh else num sub is equal to num sub right and then now we're trying to expand left and right as much as possible so that is going to be while num sub left and of course uh while this is true and this uh I'm thinking about how I'm writing this it's so awkward but I think the way that I'm writing it cuz or not awkward we just have to make sure that this is inclusive or exclusive inclusive and inconsistent that's going to be a mess so we just have to uh yeah the way that I'm writing this is I mean this is inclusive in this part so we have to make sure that this is um yeah so this should be inclusive so num sub left is um less than or equal to or greater than or equal to current Min then we uh or left uh the way I want to write it is exclusive so that's why it's a little bit awkward so let's look at ex do I want to okay how do I WR this that into inclusive right so we only need the next item if right but then now this is um going to be this will never terminate right so yeah if this is inclusive how do we terminate it if was inclusive uh if so basically this is inclusive if this is true if both of these are true then we're done and then not of these so minus toen so something like this right yeah so they're both at the end then that's fine and then now we have to go right as well so while right + one is go right as well so while right + one is go right as well so while right + one is less than n Yeahs it's way easy to kind of mess up by one so that's why I'm trying careful and then now the inclusive so the best part about inclusive is that able to do this calculation easier right so it's Yus + 1 time the Min let's give it a spin uh maybe it's infinite Loop uh oh yeah I have to always move at least a little bit so this is a little bit well so then now if yeah this part isn't inclusive so that's why what am I doing it's is a little bit inconsistent um was basically we're trying to see the next minut so this is technically this which is fine but then now we have to deal with uh weird um Left Right statements right I guess if no but left could be zero though right so that's why it's a little bit awkward so try all right go left if it's bigger and a rable right so I guess it's if left is or if white is equal to n minus one or this because if white is already done then we have to go left otherwise we go right but both of these cannot be true so that should be fine yeah maybe yeah there you go um am I going to submit I think I'm just going to submit just for cuz I'm lazy but uh to kind of think of weird cases but let's try at least like a obvious thing okay then doesn't seem to terminate uh and the way that I do it um even though there are two wild Loops this should be linear because left only goes left end times and right only goes right end times um so it may look a little scary shouldn't time out unless I made a mistake I mean it times out if I have like a infinite Loop figh thing but not because and it seems like maybe we do have it whoops uh let's see uh I mean yeah the way that I wrote this is a little bit sketchy because maybe we go right when we shouldn't so yeah let's see what is this test is five so 0 one two three four five right so then now we try to go left and we go and we're already done with left so there's probably something weird here right so left is equal to zero oh yeah so then now here it's a little bit awkward because it's going left still because it's looking at the last element or something weird um just left is equal to zero right okay this is very awkward but I don't know by recommend this yeah I mean it's very hard to get precisely right with these inclusive bounds exclusive bounds uh and apparently it's very hard to get it right um okay so left go zero we always go right is that true yeah but H this is making me sad uh did I think I did it oh I made a lot of mistakes last time too okay I think the idea is right but maybe not maybe I'm really wrong on that one maybe I'm lying uh what is this 34 but the inclusive exclusive bounds is kind of tricky for me anyway um okay so that go Z that means that we want to always go right is that true no I think that's fine but because they're all right let's try the other case where uh we go all right first right so let's we make this 7 92 say that should all go all right uh okay so this oh it doesn't even run because what oh no this ran but I guess maybe I add an extra space okay so that looks good so what is this wrong for that's a little bit annoying so that means a calculation error if this is bigger than um the expected answer right if it's because if it's smaller then you can say maybe I'm doing a suboptimal algorithm but here that means at way leas uh is an implementation error um because we're basically giving an impossible answer oh there that's brighter I could see um if it's the same we keep on expanding yeah this is right it's a little bit awkward it should be right this part seems sketch as well to be honest so uh let's separate them out I don't know maybe I'm just I don't know how to syntax I don't think that should do anything but I just don't get I just want at least separate out the logic okay fine let's print out let's print this out I don't know left right and then this calculated score and then yeah let's see so we have even in from the getg go we uh did I misunderstand the problem I don't think so even from the getg go we kind of um you know got this wrong uh let's see what is so we went left five times this is inclusive so the formula should be right we already went higher there uh what is 34 yeah this is so silly but okay fine um let's print out the array let's print out uh what's it nums also turn on do not disturb Focus uh keep pinging me okay so this so 3011 we go left cuz it's all less than that's six numbers I misunderstand the formula I'm using a manual calculator 6 * I'm using a manual calculator 6 * I'm using a manual calculator 6 * 607 76 yeah I mean h i mean my not this looks okay we have 706 so then that means that we have six numbers where the I'm trying to find the 3011 in the input I guess they just didn't print it or maybe it's behind the real uh oops Yeah I don't get it am I misunderstanding oh I am Mis well I didn't misunderstand it but the Min is okay I am dumb I actually was lazy on this part I thought that when we expand we always me get smaller but that's not true from the first time because I'm silly uh and the silly part is just that I didn't I need to expand before this um so I had to do this part um oops I have to do this part and I'm a little bit uh whatever so uh yeah so I have to do like some oh I can do just do I could just do this I'm too lazy so it doesn't really change anything oh man I am that is such a silly mistake now I fix this why is that K is equal to two01 two so expand oh it's because now this is our bounce in a weird way because the four we expand the four and then now left is equal to zero then variant no longer holds um okay fine I mean I think it should be the same as here right I don't think that changes anything uh okay so zero I set my print statement here by accident but that's good uh so four this should not go to seven because it starts at two wait oh no am I looking at the wrong no uh oh I got it I forgot to uh that's why I kind of put it in there but then I forgot it in both cases which is I forgot to update the best for now okay fine uh yeah that very silly mistakes in general let's going to submit and there you go well what a day to uh do a 1300 day streak linear time linear space uh hopefully the algorithm makes sense uh this was a I guess the last time I did it was about the same but a little bit I mean that was a little bit sloppy but this is a little bit sloppy so what am I to say uh but yeah but the idea is simple the implementation very tricky with the bounds and kind of constraints but yeah um that's all I have for today let me know what you think and yeah stay good stay healthy mental health I'll see yall later and take care byebye
Maximum Score of a Good Subarray
minimum-moves-to-make-array-complementary
You are given an array of integers `nums` **(0-indexed)** and an integer `k`. The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`. Return _the maximum possible **score** of a **good** subarray._ **Example 1:** **Input:** nums = \[1,4,3,7,4,5\], k = 3 **Output:** 15 **Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15. **Example 2:** **Input:** nums = \[5,5,4,5,4,1,1,1\], k = 0 **Output:** 20 **Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 104` * `0 <= k < nums.length`
Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.
Array,Hash Table,Prefix Sum
Medium
null
143
Hello welcome to Delhi, give a Singapore base in five days to very big companies. I will not take a name but it has been asked inside it, so let me tell you the question, what is the question. The question was that when you three four five one in this way Link list de rakhi hai simple lust hai last has null so we have this input and we have to show the output which method of output we have to show van first with last meaning notes should change linking should change right empty values Sapna should be five in van last then second with second last tu with four and then 3 you go it right then these two will be connected 15 then after that 2 4 then after that next and in this manner the linking should also change. Okay so we had to reorder it Okay so this is for example 1 2 3 4 5 Now how can we do this there are different approaches using stack and the most important thing is that you have to do the update in the list without another space. If you want to do it, then how can you do it? So, this is my approach, which I will tell you, which is my thought process, first of all, take out the first mid and find A Gaya, this is my A Gaya, okay, so whatever is there after the mid. reverse it ok reverse de second half of de less ok so reverse off de second half list how did it happen 1 2 3 and this was mine head van ok and I reverse off de second half so what could have happened 54 Okay and this one I have got the head van stored. Okay now what did I do in the last place, I re- Okay now what did I do in the last place, I re- Okay now what did I do in the last place, I re- ordered it, I have the head van already here, the head came here, now I just iterated here on the head van. Here head tu pe trended okay and this here now I have just changed the linking here, after van head tu ka five then next a went tu se four and then came three okay so let's court this one. Yes absolutely court logic is very simple find the middle reverse D second half of D list off then recoding it okay so this is our one list note value is next and we have to reorder so let's do it so first step is I need If you find the mid, it is ok then it is mine, get made note head, so first of all we write its class, less note head, then whatever head comes to me, I have to get its mid and we know the mid, we do it with single pointed double pointer. So I am writing here and here my double hope, you also say slow fast, you say van of double hope, if you say van of double hope, then I am mid nikalna hai double off dot next not equals tu null and double half [ double half [ double half dot net Equals, you tap, so what do I have to do in this case, here the one with van half, I have to increase only once and the one with double hope, I will get this, here this point will come, okay and you will be my head. It will turn out that first I have to reverse my list, so here I have sent a method to reverse the list, okay, so here I have written a method to reverse, the rewards list has no meaning, after that the whole meaning is to reverse it. So here I have list note so mine, for reverse I know 3 pointers are good, previous is null, okay, then after that list note current, which is next, okay, not equals, you become nulne, okay, so my What will happen on this, first I will put the next one on , okay, after that I will put the previous one on the next one of the current one, I am doing reverse right, so the previous one will come on the current one, okay and the previous film will be mine, your current one and the current one. Then it will be mine next, okay and here I will return which previous right here, what I have done to my list here, I have reversed it, okay camera, so this one is next to this, so I can tap here, man, okay. So I have got one list, this one, I have got one list, after this there is null, so what I did here is null just for the simplicity purpose, what brother, we have made two lists from one list, head van head, you are okay. Okay, now let's just write a method here I am doing it, I have advance, now I have to reorder mine there, so while ordering here, I first note down my list, original head is my headphone. Whatever I have to return in the final, I did it from the van guy, now I am looting here, mobile headphone is not equal and head is not equal, you are anyone, if both the taps should not be there, then I will run till then my What to do, I have this 123, after this I have taped and one is 123454 and there is a tap here because I had reversed it, now my head van is here, my head is here, you are here, now I will have time too. What we have to do with this is that what I am doing here is that I have put this six on top of the van and then here I have placed this tamper, both of these I have put a tamper behind the six, okay here and then this will be my tamper. This will happen and this will be mine Head Van Time will be ahead of me and this will happen Head If you are okay then I will continue in this manner The one ahead of the headphones is okay Similarly I have taken one second time, you have increased the tempo Right, now here I am just changing the pointer, right now, what to do on 2K next, tell me which one to do, where is the temperature.
Reorder List
reorder-list
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **Input:** head = \[1,2,3,4\] **Output:** \[1,4,2,3\] **Example 2:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,5,2,4,3\] **Constraints:** * The number of nodes in the list is in the range `[1, 5 * 104]`. * `1 <= Node.val <= 1000`
null
Linked List,Two Pointers,Stack,Recursion
Medium
2216
771
hey everyone welcome to my youtube channel how you all doing so today we'll try to solve lead call problem 771 which is jewels and stones let's solve this if you already tried to solve this problem and you couldn't solve it then hang on to the video we'll try to put some comments first and i'll try to make your life little bit easier and you can again try to solve it if you still don't get it you can come back here again and see my answer so let's see the question first so the problem is jewels and stones which is we are given us strings of gels this one which represent the type of stones that are jewels and stones representing the stones you have each character in stones is the type of stones you have you want to know how many of the stones you have are also jewels okay so also letters are case sensitive okay so this is the input which is uh input the first parameter is joel's which is a string a and capital a and we have second parameter which would be a string of the alphabets which is a capital a b so the output is three so basically what they are saying is they just want to know if this dual a comma a how many times it occurs here like individually so you see a if you just take the a here a and a you see how many times it's coming one two and then this a is coming again here so one two and three you see one two three that's why the output is three so now if you want to see the second one z small z is small z coming here no it's not so the output is zero i hope you got this one what's going on here so just simple thing just try to separate these two this and then you try to see okay how many times small is coming here it's coming one time how many times big a capital a is coming uppercase two times so two plus one three so three times c and you have the output so now how could you this is a really easy problem um if you're still here thank you for watching my video till now and i'll try to solve it so i'll just make some comments so basically what do we want is we have a input we need this output so first things first you'll have to make split the stones string and string oh my god and make it into a array right and second would be use a for loop yeah so once you use a for loop you get hold of all the element and what on what you will use the for loop this divided string stones so the way which i'll do i think it's one of the most easiest way you'll find on whole internet on youtube so because we're not going to worry about js we're just worrying about stones and what we're going to do we're going to separate all of the stones one two all of this that's how we'll be able to see if any of these occurs here we separate them then we run a full loop on it how do you separate them you use a split method right and you'll use single this right so that it separates by each letter and not by a word because then it won't do anything and third step would like to do is make a output array in the beginning and push a plus one to the output array if i can make a make output array this will make it more break it down make outputter and what you'll do if it if this element at you know the stones if the stone set i if it has any of the elemented jewels then add plus one to output and you'll just make this output as zero in the beginning not error sorry and then return it at that nothing else return output is what it's just storing your thing so if you want you can try to solve now and if you don't then just see my solution so see what we're gonna do we're gonna create a variable which is gonna store output in the beginning it's gonna be zero second thing would be what we'll do is we'll create a variable so we already have stone but what do we want new stones which would be array like we want to separate it right so what you're going to do is you're going to use stones dot javascript method which is called split and you want to separate all the letters in this ring so you use this now what you have got access to all of so you know what your stones are it looks like here it looks like a like this a comma capital a comma d so on like this it will go on so now what do you want you already got access to it so now you can run a full loop on it otherwise you won't be able to run a for loop on a string right you only run for loop on array so for variable i equals 0 i is less than new stones dot length and i plus right now what you can do you can put if condition now what do you want to check you just want to check so here's the logic which you're going to use so what you want to check is we just want to check if any of this element we don't care because we are checking here separately for each of the index so we just want to say if any if this thing these two if it comes in this index like if these two if it's equal to this then just do plus one like any of this so like if a and capital a if any of these equal to this one then do plus one then we again go and check if any of this is equal to this then do plus one then any again this includes this plus one let's just run the loop so instead of using again a for loop and make it complicated we're not going to do this we'll use the includes method so what we can do is we can say that if j e w if jails right so if you want to say that if jails dot see so there is a method in javascript called includes if j if jails dot includes what does it includes new stones at i right so what do you want to do is if it includes this then at the output you want to say output equals to output plus one right easy and what have we named output store output so forgive me yeah store output equals to store output plus one else nothing that's it if it equals then you push it otherwise nothing and then you just return the store output yeah and if you try to run the code then it should give a really fast answer yeah it worked and if you try to submit it see we got 60 ms faster than 97 of the javascript solution so see really one of the best solution internet and so easy how easy it was nothing just store create a variable store output create a new variable to split all the array then run a for loop on that array and just see if this includes if this jewels include this and if it this joel's has two it has a string in it so basically if that string includes this then push it otherwise nothing and then return it easy make sure to subscribe my channel like my video and comment on what other video you want me to make on or i'll just continue the series i'm doing it now
Jewels and Stones
encode-n-ary-tree-to-binary-tree
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so `"a "` is considered a different type of stone from `"A "`. **Example 1:** **Input:** jewels = "aA", stones = "aAAbbbb" **Output:** 3 **Example 2:** **Input:** jewels = "z", stones = "ZZ" **Output:** 0 **Constraints:** * `1 <= jewels.length, stones.length <= 50` * `jewels` and `stones` consist of only English letters. * All the characters of `jewels` are **unique**.
null
Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
Hard
765
1,812
Hua Hai Hello Everyone Hindi Select City I'm Going To Explain About It Man Yesterday Office Work Hair Give Vote Subscribe Button Subscribe The Video then subscribe to The Amazing In President Appointed Black Color Shot Dead History Click Hair Two Three Layer Subscribe Button Strongly mintu like share and comment it's coordinator.directory of valuation 55122 daughter coordinator.directory of valuation 55122 daughter Share Subscribe And That We Have Returning Statement Has Written For Which Commitment 1981 This Course Will Agree This Note Is Yes Behind Guy No Will Submit It's A Aap Jakar So Here What Is Notification President Mirwaiz subscribe The Video then subscribe to the Page if you liked The Video then subscribe to subscribe our Videos A
Determine Color of a Chessboard Square
reformat-phone-number
You are given `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return `true` _if the square is white, and_ `false` _if the square is black_. The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second. **Example 1:** **Input:** coordinates = "a1 " **Output:** false **Explanation:** From the chessboard above, the square with coordinates "a1 " is black, so return false. **Example 2:** **Input:** coordinates = "h3 " **Output:** true **Explanation:** From the chessboard above, the square with coordinates "h3 " is white, so return true. **Example 3:** **Input:** coordinates = "c7 " **Output:** false **Constraints:** * `coordinates.length == 2` * `'a' <= coordinates[0] <= 'h'` * `'1' <= coordinates[1] <= '8'`
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
String
Easy
null
475
To Ajay that potatoes are rippling in it, Sachin Gautam himself is going to try skin infection, its name is meters, it is fine till the deposit, day, we try to time it or else you have not got 2 years, one houses characters, keratin, so we are only one. Area, let us tell you on which position it was placed. On the third position, a Hussain has entered the infection. On the second position, there is an intruder Poojan Pack House. On the 11:00 position, intruder Poojan Pack House. On the 11:00 position, intruder Poojan Pack House. On the 11:00 position, it is okay. The first one to show you this is Heater Coffee. Putting it on the question, now your question is Mishri, do you know what to tell, now Kumar, try to understand that all of it is a gas, okay, you have to set a property which is going to be applied on all these heaters, that property. Is it DDS? It's okay, you have to find out the minimum radius. True, all the houses are from here. It's okay that you decide one minute for these three meters of yours, then when all the opportunities can be there, then try to understand the health and safety. Let's see what the question is saying. For a week, he has an option among the teams. He will give you the paper to the nearest one, so for this, the one who is the distance with the nearest heater will go. If you think about the one free one, then his This will happen and if you think about it, then it will stop that this person will be giving a return gift and think about convincing him. If you think about the distance between the time, the house number is 11:00, then it is time, the house number is 11:00, then it is time, the house number is 11:00, then it is on this that this distance between them is so. The minimum radius that we will have to keep for our hips is these three because once you keep the maximum, no matter how much you keep, for all the features, you keep the smoothness radius from the edit plane, there will be no problem, think something, if its difference from the radio is as much as If it is complete advance here and complete enrollment here, then it can spread its illusion, if maximum lettuce is taken out, then there is no problem, you have to decide what minimum radius should I give to my hair, if the decoration can be kept from all the houses then I would say How much is that made this, why should it be there because if you give this heater a radius of three then only it will be able to keep the earth from these houses and then the eleventh house is its bread clear, so I know the additional information of this company, what happened to the houses each. Find out for him that basically how much distance does he feel to keep the bomb from any one meter and if you take the end distances in maths, then scolded him by deciding the minimum radius of the meter. Subscribe to all the houses so that he can live as a player to everyone. So this will be a matter of our society, the question is, okay, a few schools from which to do it, how to do it, let us look at this, if you look carefully, then let's hold on to someone else and see, latest pick, house number, full house number four. Tell me, what is this called, you come after disassembling the heater for Buddha, now the thing is, this is one shot, you are feeling such lines, how will the house number point from one to 11:00 more, we how will the house number point from one to 11:00 more, we how will the house number point from one to 11:00 more, we happened, we say this Who is the closest or lighter actor to you on the left side? Who is the nearest and lighter actor to you on the right side? Well, we celebrated the festival of distance with the one on the left. Who knows? Click on this item, Sanskar flour coated with it will be clear in the office. Now we will see this from this point. If you look at this thing thoughtfully, then you will not know what is happening. Try to remove some things from the question and It is being thought about which heater is lying at the position just a small from f4 of the meters and again which heater is lying at the position just red jab what is the smallest just chill hote what are the scenes and you need to know about one You should know how to extract cilantro, okay, so we are going to do this thing, so ATM, I came to know that if I try to satelliteize all the things like question word problem etc. then this problem is about finding the original, keep it at this length, find, once I tried it, Is this right or not? Let's start. You know, I am not making any points here, just to make you understand because every 1 liter post house, which heater will you pick? 67 means if this white appeals then it will be the same. Like member, what is his distance? Come on, yes, let's talk about that minister. Free will be told that just smile appointment is lying one liter from himself and just Lal Sarpanch is lying one meter from you. With both the pipes on it, the distance to each is like this. Pick any of the two then think about the distance between Udupi to 9, then one position on Noida messenger smaller position and the thing yes that just bigger than no is not a story, okay from 9 to right hand side some leader If it is not there, then you will understand the distance here as if you have not come but understand that - if the not come but understand that - if the not come but understand that - if the brightness of indicating hum is behind you, then the road distance will be on the left side from the answer, it will be plus for the moment, then you will know how much of these three distances have come. Plus celebrated, you understand, think for the Guru, Judge Smaller once lifewise, which better appointment exactly with whom, think for our crow, Jasav Vansh file, OK, so the difference is there, Rathod sitting with the center, also think about 111, just Smaller fell on the reset position. Justin does not formally confirm Okay, so the only heater option for 11:00 and with it its only heater option for 11:00 and with it its only heater option for 11:00 and with it its difference is free, remember, then I will send a chat that you will have to keep my litters to a minimum of dead skin because if this heater and you recognize you He doesn't have that much power in flourishing and inheriting the entire office, but in this sector, cashless, you will have to keep three, otherwise we will have to keep our daddy skin, minimum ladies, our 3062 Bazaar-e-Husn moments, okay, we our 3062 Bazaar-e-Husn moments, okay, we our 3062 Bazaar-e-Husn moments, okay, we should save them from ours. Player will see all these now. How to solve it, you have shown it like this, now how will we welcome it, then just think carefully, do nothing, look at this, hold each house one by one, and this is what we are looking for, the Ninth Jasmal Opposition, on which the phone is at the same level, Etawah. To travel in the layer, remove Noida floor, not just morning, okay, if the problem is similar, not just that, if I find it on the right side, then I will remove their Jasraj, remove the serial, we will see its leaders in the selection or not, they were removed in this way. It can be done when the details ones are sorted, then what will we start with the digital ones, then we will make the ones with this feature soft and our story is looking a little manageable. Okay, so let's do it once, let's try to figure it out. We are looking at it with full voice, which is there, let's go, we are heartbroken that it is okay that all of us keep one thing in mind that we all have to design it in a tasty way, that is, what it needs is only these three, if this pipe Get distributor nights and lets in rural credit, but you will keep this thing. If you want to make all the heaters the same, then if your couplets have been decided, now you will have to keep this also and what will happen in that chapter, what will be the level of alarms. Mom will not be able to stay, capacity is fine, everyone's raid is done like this, only three are kept in it, there is no issue with keeping more reductions here or you have done any obscene foreign thing, but he needed only three so that he can stay from Eleventh House. My minimum balance is Ecuador. Darshan is right Singh so this will be our question ok now I started understanding a little story that your leaders are fighting scene floor in short and are forgiven that position is ok for you what am I to do first of all I will stitch this finance minister and prepare it very easy It is okay to just remove it from the lower one, so it will come in the middle of the three kings, in the middle of 145, there is one, he has one and in the same way, out of the 5, son Edison, with whom will the tune and the caller become distance two for this? I understood but after that the problems came out of nine's cilantro, cracks, then I would say it will not remain, on the right side, if the light of the screen is not lit, then on the right hand side, just red, when the first and second do not appear to hit ok, then just molar eta. With this, he ran away after doing the last rites flat. Think about the distance between class-2. Will come between the forest and Pakistan. Think about the distance between class-2. Will come between the forest and Pakistan. Think about the distance between class-2. Will come between the forest and Pakistan. With this, he is making distance with this. Distance free Raja Tohar wale dipper will do it and think about 140 middle youth. The distance is ready with the teams of 11:00, its distance is ready with the teams of 11:00, its distance is ready with the teams of 11:00, its distance mod is there, so it will be able to be done on the display, but it must be used on the paper. Think about one, the one with 11:00, Think about one, the one with 11:00, Think about one, the one with 11:00, think about it will come on the right side, only the vaporizer is in smaller position. Yes, there is only one, there is nothing on its left but right side. Okay, so we will do it for you. Steam distance via Ujjain. My answer is or all these distances are less. You Tata turned the screen side to side and asked the question medal in the same way. So much complexity has broken down that Hey people of houses, please do it, phone office people loot, it doesn't matter whether you picked up the cat or those of leaders below, this life is useless, Jasmaur Jasraj has gone away, now the one below adjust no dance class chapter can be removed in this way only when the one below is that The picture is posted on the rate thing, its complexity is so bothersome, complexity breakdown is houses ones, are excellent, if end is there, then every time I am extracting the scene from behind each value, then its ones are calendar amazon log m ok directly this. Let's use it because these two factors are fighting and in the bodice, I had initially shot the one with the dress, so we had already put The Thing in it. Whichever factor is bigger among these two, will go to Amazon, the value is from these two. While doing the job, you will make me talk to the doctors on my complexities, after that let's do it one more time because I want him to fold it, the additional side to this will be that you know how to extract cilantro in the dark, that 108 of a life value Yours that let us fold it, if we travel through it will become clear to you how it is going, okay yes, let us go towards the court, we will pass it again and we will see, okay, what is this, he told me first of all. So basically, you should request your hips first, so I did it by putting , my so I did it by putting , my so I did it by putting , my hips first, shot, okay, it's okay, report nothing, house people, replace it and remove the question every time, brought garlic from wise, houses but length. What will I do with the plus seat, will we take out the house portion from him, come to the spot today, now what am I, my friend, laugh at me for this position, no, from this, the junior assistant is found in the judge smaller screens left, he should get his position, and on the right, the junior level is found in his portion. So I want both things to return as father titan, what do I do, I create a fair, then if I want both things to return with se, I create a pair class, public static class foot, address in this tree. What all will be left, nothing but two simple things, this position was in Uddetpur till Angela Chakli, when I returned with my friends, it was just smaller and just red, it is okay, and by grinding these elements. I give both of them separately - Stop it, I give both of them separately - Stop it, I give both of them separately - Stop it, after today whenever I make a new foot, people - I after today whenever I make a new foot, people - I after today whenever I make a new foot, people - I aim at it from my mind and what do you do other than a program, I make you laugh when the empty one keeps looking at you and let it be your wish. Both of you make the empty one as well and Paramilitary Force's Juice Model Jasmine 's Deuce Knowledge Quizzes Moller Desraj 's Deuce Knowledge Quizzes Moller Desraj 's Deuce Knowledge Quizzes Moller Desraj Jassal Research Playlist So I had made it so that I would be able to ask for Uttar Suraj and Jab together, now I am so sure that it is going to be hits, dry ginger is one HP Told about extracting a value 108 times will prove more effective. 10 optimizations and we can apply it on this - What all will I send? can apply it on this - What all will I send? can apply it on this - What all will I send? Volume HP oil is the touch one. In this water value, you just go and take it out from the mold, okay and that If you return me by shaking my leg, then read this my mail, I believe that it will come to me, I will leave - but I believe - but I believe - but I believe that when I give it to him, he will bring me the medal or make it in the same standard form. Now I have the question of best meter to my left and eight to 10 meter question. I will see with whom my distance is less and will shift that person. What should I do to improve my distance? Jhal ji. I will add on run sanskar, left filled meter decided to right with the letter then let's calculate Dr to ok first electronic system left side effects template doing sorry no let's flat this question stay ok so this which is just Maulana if this is yours 9 - just Maulana if this is yours 9 - just Maulana if this is yours 9 - But it is yours - it But it is yours - it But it is yours - it means that the heater on the left does not take a look. Think inside Malwa, basically you have ordered the juice model of your phone and the heater is basically that some important questions are on the page. Hey, it is sorted. If there is something like this, then just call and the molar does not come to you, we are fine, some site questions are coming that you say here, let's keep an indicator that its just model has not come, we come to know that yes on the left side. If there is anything in liter or so for this thing then it is ok then if but there is nothing on the set then brother ex-flame remind him brother ex-flame remind him brother ex-flame remind him maximum instructed of maths person plus imperative there was nothing on the left side and if there is a whisker in which the request If you do so then get the distance calculated with him and get the distance calculated from you, otherwise you will be rallyed first. Details Pendant Jasmaur Activated Distance. If you have to click on any of these two, then one side will come. Now if I calculate the distance with the right one, then the right way will be given to me. You will have to see that when the look is not heavy, if just likes this, then brother, you pick the one with printed max. Okay, and if it adjusts, then consistency with it, Galva, this is just red, when the position on value is big on busy light bill deposit, then first. Just Lal Jain will come and then your position will come. Okay, if you select any of these Edisons, then which heater should you install, then we are the first with whom we will Radhe volume minimum, you don't need, you want to, I have selected the minute now. The difference has not come, all the distances will give this review position, my nature is the maximum of all these, so what do I do for that, I make Sanam's work here, the answer is yes, so the diabetic DJ I have to choose, okay, so what do I do here? If this distance has come till now from the answer then do not forget to update this in Badwai Answer. You will not make any difference with your own terminators so that all the offices should update the phone recipe answer with medicine. And finally return and there is a small thing on the answer base. Whatever is there is complete, now these 22 channels, this is nothing, this is just a shot in the dark to select a lifestyle, so you write it in your style as you want to write, I write it on my side, that's fine. Okay, so the public traffic foot should return me from here because I will stop the fun slaughtering along with you and ask who has got what, who has got a value, okay don't think that I have got it, say one more minute, now understand from here now. If we remove it means that we can put it on it, so as usual, I have taken a new one, you know that in this tree, but now I have cut it, how could it go till ours that inside it, this Google Okay, then there will be a distance war for that, neither will I be here, so let us understand that if there is an exam and the president and you are asked to share the same values in which the judge has gone, then you will love him first and then will we? The same can be sacrificed, the butt is coming out, now there is a case meter, it has been talked about, it means that there is a hit inside it, then just Maula is also the same heater and just war in short distance road 2200 you worry episodes, this area is also in the mall. Give me the middle, ok speed just in Lal Chand, give me the area of ​​the middle, you and fabric day before yesterday give me the area of ​​the middle, you and fabric day before yesterday give me the area of ​​the middle, you and fabric day before yesterday WhatsApp, whose many keys are there and if it is not so, your decision is there in admit day before yesterday, the value is lying, that thing of yours seemed small, the key of these top keys is big. So you go to the right hand side to approach your key. Okay, then pick up the people and put them on mit plus one. To approach your key, go to the right hand side and at the same time see that the value million which is any smaller than yours. So on this movement you have a chance when you will update small, then update small from admit, okay now there will be another small one, that means understand this friend, Baneshwar will keep moving, otherwise as you approach, the speed will keep increasing at 10 monarchs and on the adjusted model. It must be lying there which is much smaller than this, read on it in a very small way, okay this thing and if this situation comes then it means that we have no money left for our ticket, then we will pick it up and keep it to the minimum but we will see its value. Mid your thing increased, you got a chance to do this movement just red address, admits should be purchased that and finally will return display then finally we will return on this ok if we have taken a cup of sugar then all we have to do is cycle and see. Once we take a stand, what thing we have written is fine, so it is correct Rai Bachchan and if there is any mistake then it will pop out, okay ji Pimp Driver will definitely do it, okay, what to do, okay, as always, I made a mistake here, okay Okay, here we will wear the question, okay, it is written in the police inspector of the driver operator, I am very good, Ansari, I am ready, submit master, come immediately with your husband to see it, reduce the password, so what should I do, I respect Tamil Pandey. But I you also have a problem yes it's ok so this is my office leaders hey it's done floor taken which one so it's complete they take all separately so friend at is your pin code and after that this is what I tell you Once we draw it, we will show that this sequence is pure, I will try it once and show that I know the space capsule floor so much and will give me a code number to run. Finally, it is okay for Bigg Boss, as we will see whether it is so or not. So you can make it a little smaller, now at this point the rice is very good, so I have shown this report to the housewives on Raval or Maine Pyar Kiya, I have prepared it first of all, hey, be sorted, it doesn't matter, I got the suit done. Because if there is a shot to be given then I started the minute one and made a video of an alarm in which I am maximizing this rest a distance for that work Infosys, this saliva became our topper, the need came out in it, the pickup to the house came to me for the first time. Free in the house position, what did I say, okay bye research, I made a call, Hey Meena, after taking out the Just No Words rally from the woman below, now I am giving you one time here, for how much, just fun, Jasraj, how will it be taken out, right, initially. Lo, you kept it here, you made a paste for it, for which it is - 52 - boiled - 52 - boiled - 52 - boiled set, it means understand that it was made on it, and there is Jasmaur in the foot, which is now minus one, there is just red in the copper, whatever - This is the first time, is just red in the copper, whatever - This is the first time, is just red in the copper, whatever - This is the first time, I made Jhala, hey, how did it appear open to me? Are you off butt? I want you to teach her three in the mixer. PM this moment, keep it free. On this, yes, she was talking that if I study you, then I will admit. If she looked bigger than me, then I Said that it is ok, first of all, I have to go to the front side to approach the ok, I have to raise the height and keep it at minimum but at the same time it will ask again, I have got a big volume, I have updated the hidden torch light and set the file, now the If this thing had a source in all this, then do n't be afraid, don't know why because Pari was coming for 45 and just in the state for the second time in tension, for gets updated, so I have written this here again and again till it gets worse. This will not happen until you reach the free point, the driving will continue. Okay, so you have taken this thing, now after this, I took out my feet time and came to me, this time it is in the admit card in the front, show me that which is mine. You would have put the value of this note in the products mall and people would have picked it up and put it forward. It's okay, if it was pregnant in the office or home, it would have been like Jasma Lattu because these were the right networks. If you understand, then this is just a coming out story, absolutely so. Here we understood that basically if we have gone ahead of the iron then just is not just logic and the product is that now for the woman we have gone up and created the answers, we have taken out the dimple for life and seen whether just follow request does it for free and where does it do so. Distance has been taken out by you - Man Bieber, how did I take out the house premises - - Man Bieber, how did I take out the house premises - - Man Bieber, how did I take out the house premises - was just model so I have distance made two days to just Lal - Position Bittu has come days to just Lal - Position Bittu has come days to just Lal - Position Bittu has come both of you basically so here both of you race organization is minimum so will you come on that? Till now I noticed that the snow is the biggest one, so the answer was updated and muted. If I write this start, then for this we have raised a distance to. Okay, yes, now we will come like this. Next one is okay for that, so let's go. Then let's move on to that, what would have been read in my key that I read this time, basically Choice for Justice of 1919 will be taken out, once the mixture is prepared, please try it, you may be good for this also, 9 inch shoulder will look good on page 54. See it even in friends parlor - Pandit See it even in friends parlor - Pandit See it even in friends parlor - Pandit Jasraj Lambi - Man Parelu Hi here Jasraj Lambi - Man Parelu Hi here Jasraj Lambi - Man Parelu Hi here we will talk about the currency, okay, so what did I understand, OK ji, take out 20 minutes from the butt, the younger sister said, Web, so what did we do now? While updating the admit card in Just Mall, we went to continue our Sachin on the right hand side, people picked up ABVP Laxman, this time again what you have got, it looks small, it is smaller than the American, so you What to do, just in case Admit ji, while adding Ballu, you also continued Sachin on the right side and like you guys will raise the question, Sachin will go to the group, okay then finally the answer is absolutely correct, see, there is Jasmal interpolation for nine. At but Lalchand, after understanding, now he will come up and calculate day one to two. If we calculate 121 even at the halt, then what will happen now? How will he get the medical calculation done to me? I will see what he used to do while making the voice of just present and minus one. Exit distance taken out, house position - Exit distance taken out, house position - Exit distance taken out, house position - made eight digits, you will have to find a groom, infinity because just like a victim does not do it, okay, when you take out the time of both, how much distance will come, one and you will see whether youth is the biggest focus till now, if it is not, then the answer is not updated. Will it happen in a distance from the set, I hope you are getting clarity as to how to remove the chasma from the uterus, okay then I will give it directly, okay after this I will come to overtime, I have Jasmaur Jasraj for you, we know. That you will come after taking the date off which will be considered as the standard, when I take out Nazar 501, then I will take out that one day two Thorat v5 - 23rd April, there will be minimum from both one take out that one day two Thorat v5 - 23rd April, there will be minimum from both one take out that one day two Thorat v5 - 23rd April, there will be minimum from both one and we, the reservation for this is only with tips, which is the biggest vw till date. No, next time you come, what will happen that I will increase, I will become just a model, Justin, when 521 will become an affair, distance from will become juice originality, distance of three lodges, Rajasthan distance will come, time was given to him for him, make distance manchale which is till now. Realize that if there is no maximum then nothing will happen, there will be no dependent, now finally in the form of cardamom, you must have studied in just mall, what painters in the state - 121 How much is work painters in the state - 121 How much is work painters in the state - 121 How much is work free mode to infinitive, minimum of infinitive has been inserted at your place, Mr. Next ok Okay and this verification has now increased from medium or pillow answer, you updated the answer and made it free, after the station you will say that we will have to keep minimum read SSC, all the options can be proven, okay yes, so I hope you get the solution for this. You will like this from the Basic Education Campaign, this was how you are good with word problems, so whether you are cash tight, should you put it in this? I am ready to do this question in an optimized way, after the complexity, I will do it once again, start my own press one. Tweet to this LMB login if hits plants reference is death and housefull need better length and so we login python tractor here whatever work I do how much is done en login ok so this work of mine is done for these people Out of these two, which one has the biggest value in the body, did you understand that your company will be withdrawn because I am putting it on each one, then I have taken out the enzyme present in the left one, so this thing has iron. If you understand then these The big rally that will happen from both of them will be of its own complexity. So come love, share. If you liked its solution, select Anshul. If you liked it, then please like this video. Okay, I have met in the studio now, Mother Jhaal.
Heaters
heaters
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses. Every house can be warmed, as long as the house is within the heater's warm radius range. Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius standard of heaters so that those heaters could cover all houses._ **Notice** that all the `heaters` follow your radius standard, and the warm radius will the same. **Example 1:** **Input:** houses = \[1,2,3\], heaters = \[2\] **Output:** 1 **Explanation:** The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed. **Example 2:** **Input:** houses = \[1,2,3,4\], heaters = \[1,4\] **Output:** 1 **Explanation:** The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed. **Example 3:** **Input:** houses = \[1,5\], heaters = \[2\] **Output:** 3 **Constraints:** * `1 <= houses.length, heaters.length <= 3 * 104` * `1 <= houses[i], heaters[i] <= 109`
null
Array,Two Pointers,Binary Search,Sorting
Medium
null
48
in this video we will be solving rotate image coding and challenge let's first look at the description you are given an end times and 2d matrix representing an image rotate image by 90 degrees clockwise note you are you have to rotate image in place which means you have to modify the input image directly do not okay we have two examples so the input which is a ray of race becomes this and it's the same for second example okay so look at what we are actually doing so if we have an array of numbers and if we want to rotate the image clockwise 90 with what we're basically doing each it's just this okay so the first row in the input is 1 2 3 4 5 6 and so on and result the first row is seven four one eight five two nine six three so it's basically this cool so whenever we have coding problem that involves matrices we always need to look at the coordinates what's happening to them okay so the number one has coordinates of zero and they become two and the number two has the coordinate of zero one and they become two one two so we're not seeing any pattern here what we can do is just flip or just rotate the rows so the last row becomes first yes so the result will be 7 8 9 the first row and then the first lower all becomes the last one okay now if you look at the numbers we can see that 7 is in the correct position so it's 5 into 3 as well if you look at other numbers like this one here ok they go here and if we look at the coordinates so it becomes so eighties starts from 0 and it becomes 1 0 and number 9 is 0 2 and becomes 2 0 okay cool so we need to just swap the coordinates right to 0 1 becomes 1 0 and so on when you do what we need to be careful here is that whenever we swap we need to do it just once so let's look how we're swapping every number twice let's see what happens right so 7 has coordinates of 0 so when we swap corners it's the same position move on number 8 has coordinates of 0 1 so the numbers positions of 4 cups here let's move on so nine-nine has coordinates of 0-2 so nine-nine has coordinates of 0-2 so nine-nine has coordinates of 0-2 right so we have coordinates 0 22 0 which is 1 and I will swap those it's moved away and now when we come to 8 if we are swapping again so let's see what happens oops basically it becomes 4 &amp; 4 because oops basically it becomes 4 &amp; 4 because oops basically it becomes 4 &amp; 4 because of it and we did nothing so we need to swap it just once okay so let's look at time space complexity for this one so we're doing so it's all and times and for time complexity so and it's number of rows and n represents the number of columns and space is constant so it's off 1 we're not allocating anything new which is doing everything in place now please pause this video and try to come up with a solution yourself remember first rotate or reverse the rows in place and then you need to just swap the rows and columns just once so please do that okay so let's first reverse rows and so JavaScript has reverse method array and it does this in place so we're good here now and now we will be doing two for loops the first all of disappointed for the row and second point will be for the column now it's the tricky part we need to rotate the swab and the rows and gorgeous ones and just swap helper functions and we don't need to return anything because implicit of done for the function is undefined basically we're just saving number two temporary value and just swapping those two moves so it just works it doesn't okay let's run all the test cases and a pass I hope this video helps you understand this coding challenge until next time bye
Rotate Image
rotate-image
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise). You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\] **Example 2:** **Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\] **Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\] **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 20` * `-1000 <= matrix[i][j] <= 1000`
null
Array,Math,Matrix
Medium
2015
1,903
hello everyone today we are going to go through largest old number in string so uh in this prr we receive as input a string with the variable n and then we are supposed to find out what is the biggest o number we can have from this number uh let's say we have this as input 52 you do agree with me that 52 is an even number why because it end with an even number and then the sub string that we can have from 52 are actually five and two and from this the biggest old number that we can have is actually uh five so that is why we return five now let us take this one in this one there's no old number so basically if you looking for the biggest old number you can have from this you are going to have an empty string that is why you have an empty string and for this one you have the entire element because the input is actually already an old number so now giving those example how are we going to solve it so to solve it we are going to take as in consideration a couple of remark and then from those remark we are going to write a straightforward approach that is going to help us solve this so the first thing we need to take in consideration is the fact that uh since we need to have a sub string let me draw it this way so you can see where I'm going since we need to have a sub string which is consist of a let's say x for instance right now so we are looking for the biggest o number that we can have with a substring of the input so one thing you need to have to understand is that it need to end with an old number so you need to find the ending which is an old number right and the second thing you need to consider is that if this is actually a valid substring eventually this will be actually a more valid solution why because if this is a valid sub swing that means we have a pair of element that is old then this will actually be also an a pair which is old why because it end with this and then that said you do agree with me that the longest sub swing will always be the one starting with the first element so that is what we can remark here so it will always start with the first element because any subwing that is going to appear after this will be actually smaller than the one starting with the first element so now given that we can easily Define the Lo where we are going to look from the last element till we find the first o number if we find the first o number we break the loop and we return the string at that position not this yeah the states of the string at that position let's look how it will look like for this let's say here you're starting here it's actually one an old number yes so we return theing nothing to do let the second one we start here it's actually for an old number no we move it actually two an old number no we move yeah it's actually three an old number yes it is an old number so we break here and we return this so This is actually my Approach of coding this so now what will it look like in term of coding so you have a couple of approaches to check if a number is actually old you can actually um get the number convert into swing and um make the module operator or you can just create a let's say a list of old number and that's the option I'm going to use so I'm going to have string I'm going to have old number which is actually which is going to be a list of old number so the list of old number actually uh 1 3 5 7 and 9 um why is this not color and then yeah I just need to return num so what I need to do here I need to have a y l while the N is actually different from an ENT screen so I need to check uh does if the I mean like let me take it this way you're going to see if nums do back num. back is actually the last character if n back that mean the last character is actually found here that means the last element is actually old number so if f is actually different from string and po that means the last element is an old number so we need to break here otherwise we just need to remove the last element so we can continue the shake so we don't make just need to make a pop back okay so that being said uh this is what we have why is this not color am I missing something okay so let us run and see what it gives yeah you have everything green it is passing let us submit yeah we have um performing PR well so this are my Approach of solving this I hope you do enjoy it feel free to leave me any input I'll be really happy to interact with you regarding this see you on the next video chiao
Largest Odd Number in String
design-most-recently-used-queue
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** num = "52 " **Output:** "5 " **Explanation:** The only non-empty substrings are "5 ", "2 ", and "52 ". "5 " is the only odd number. **Example 2:** **Input:** num = "4206 " **Output:** " " **Explanation:** There are no odd numbers in "4206 ". **Example 3:** **Input:** num = "35427 " **Output:** "35427 " **Explanation:** "35427 " is already an odd number. **Constraints:** * `1 <= num.length <= 105` * `num` only consists of digits and does not contain any leading zeros.
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and update it (i.e., O(sqrt(n)) per operation), and move this element to an empty chunk at the end.
Array,Hash Table,Stack,Design,Binary Indexed Tree,Ordered Set
Medium
146