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
160
hi folks welcome to one more linked list problem so in this problem we need to find a intersecting point between two linked lists so we have two linked lists going there and then at one point of time they intersect each other and then they become single linked list so our job is to find that node where both the lists intersect so let's look at the example so we have one list at one three five and then five dot nexus 20 and the other list is even numbers 2 4 8 12 14 16 and then 16 makes this 20 and then onwards they become one lists so like 20 not nexus 30 dot next is 14 and then 14 dot X is null so we need to return 20 because that's the node at which they both intersect so difficulty level on this one is easy however I would say it's on the verge of being medium but it's still easy like so if you look at the problem and if you try to figure it out it looks challenging but once you figure out how to do it and watch the trick behind it will find will realize that oh yeah that makes sense that's easy so let's do that let's go to the whiteboard let's figure out the approach let's figure out the trick behind it and then come back and run the code okay guys so we're going to take these two lists from our problem description and we are going to figure out how we can find out this node 20 where both the lists intersect so I'm sorry for this zigzag list my whiteboard is a little small so I couldn't have straight one so that's why I had like this exact so but as we can see our list 1 is a smaller list right it only has 6 nodes however our list 2 which is like 4 8 and 311 nodes and they both intersect at 20 so no matter what the problem is in linked list like it's typical of like if you have to find a cycle or if you have to find where they intersect you need to have two pointers and then we need to make sure that they reach at that node at the same point of time so that's how we can find out whether it a cycle whether they intersect and whatnot so let's try to do that now we know that if we have one point here and if we have one pointer here if we start moving them to next they'll reach at 20 at different point of time so that doesn't give us anything so what we'll do so there is a neat trick to it and let's see what we can do so what we'll do is as soon as any pointer reaches to the end of the list so let's say this list one pointer we say that this is node one pointer and this is no two pointer right so we say that if node one reaches to null or end of the list we'll say that ok node one start our single is two now so ants likewise if no two reaches the end will say no to strut towers in list one so let's see what happens so let's say this node one it starts traversing right one two three four five so once node one is here this node two would have reached one two three four five and no two would be here so what will say node one start traversing list two so this will be node 1 and node 2 will move to next one right and now what we'll do is node 2 will start traversing right and so 1 2 3 4 so no to reach here after 4 traversal and in meantime no one will be 1 2 3 4 node 1 will be here right so now load 2 has reached to the end of the list and what we'll say no - you go to the start of we'll say no - you go to the start of we'll say no - you go to the start of the list 1 so node 2 will be here and node 1 will be here so now both the nodes are traversing the other list now notice what happened node 1 is 3 node away from that intersecting node 2 is also 3 node away from intersecting this node so 1 2 3 node 1 will be here and 1 2 3 node 2 will be here and that's our node that we want so the moment they both reach to the common node we say that's our intersecting node so what we do we take one node start traversing the list as soon as it hits the end of the list we say start traversing the second list so that's our code we take node 1 node 2 starting from the heads and then we say until they both reach the same place keep looping and till node 1 doesn't hit null or the end of the list keep doing node 1 dot next and as soon as it reaches null go to the second list and likewise for the second node so that's algorithm that's our visualizing but still like if you still have question let's give it one more run ok so what we did so this one our node 1 right so what did node 1 to node 1 traverse the whole list so that's like 6 nodes and then it Travis still here right so 1 2 3 4 8 and 9 so it traversed all in all 15 nodes right now let's count how much did know to traverse I'd 4 8 and 3 11 right and then it came here and it travels 4 nodes so it also travels 15 nodes and they both reach at the same place at the same time so they both traveled 15 nodes and they both reach at the same time so that's the logic so let's try to put a mathematical formula around it like just similar way but different representation so let's say our this is our list 1 right so let's say now this 3 nodes are common to both the list right list to list 1 they both have these 3 nodes so if I want to calculate the length of list 1 I'll say X 1 plus y now this is my X 1 and this is my Y and the length of list 2 I'll say this is my length of so this is my X 2 so I'll say X 2 plus y so that's my list to blend so now what will happen right okay so my node 1 what it does is it travels this X 1 plus y right X 1 plus y complete the list and then it comes here and then start traversing till X 2 right so that it's mine old ones travelpod now what is my node to travel path it starts travelling here it finishes the list so x2 plus y and then it comes here and then it travels x1 now if we notice these both are equal x1 plus y plus X 2 plus y plus x1 and that's the formula that's the logic we just implemented that they both are traveling same number of nodes and they both reach at intersecting node at the same time so that's the algorithm short and sweet code so now that you know the trick you know this formula now you can realize that yes this problem is really easy so there you go guys that's the easy problem to find intersecting two linked lists so let's go to the computer let's run the code and let's make sure that we get this 20 as our output okay folks this is our final code to find the intersecting node between two lists this is similar to what we discussed on the whiteboard so the important part was what we did on the whiteboard if you guys understood that understood the approach then this is just matter of coming and implementing it so still let's run it let's make sure that we get 20 as our intersecting node so there you go we do have c-sharp and Java coder over we do have c-sharp and Java coder over we do have c-sharp and Java coder over there the link to both the code would be there in the description you guys can take it up if you guys want run it against your custom test case make a feel of it get the code your own thing and then try it out so guys if you liked the video if you guys learnt some cool things then give me thumbs up or let me know your feedback and suggestions in the comment and then subscribe to our channel for more videos see you in next one
Intersection of Two Linked Lists
intersection-of-two-linked-lists
Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`. For example, the following two linked lists begin to intersect at node `c1`: The test cases are generated such that there are no cycles anywhere in the entire linked structure. **Note** that the linked lists must **retain their original structure** after the function returns. **Custom Judge:** The inputs to the **judge** are given as follows (your program is **not** given these inputs): * `intersectVal` - The value of the node where the intersection occurs. This is `0` if there is no intersected node. * `listA` - The first linked list. * `listB` - The second linked list. * `skipA` - The number of nodes to skip ahead in `listA` (starting from the head) to get to the intersected node. * `skipB` - The number of nodes to skip ahead in `listB` (starting from the head) to get to the intersected node. The judge will then create the linked structure based on these inputs and pass the two heads, `headA` and `headB` to your program. If you correctly return the intersected node, then your solution will be **accepted**. **Example 1:** **Input:** intersectVal = 8, listA = \[4,1,8,4,5\], listB = \[5,6,1,8,4,5\], skipA = 2, skipB = 3 **Output:** Intersected at '8' **Explanation:** The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as \[4,1,8,4,5\]. From the head of B, it reads as \[5,6,1,8,4,5\]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory. **Example 2:** **Input:** intersectVal = 2, listA = \[1,9,1,2,4\], listB = \[3,2,4\], skipA = 3, skipB = 1 **Output:** Intersected at '2' **Explanation:** The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as \[1,9,1,2,4\]. From the head of B, it reads as \[3,2,4\]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. **Example 3:** **Input:** intersectVal = 0, listA = \[2,6,4\], listB = \[1,5\], skipA = 3, skipB = 2 **Output:** No intersection **Explanation:** From the head of A, it reads as \[2,6,4\]. From the head of B, it reads as \[1,5\]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. **Constraints:** * The number of nodes of `listA` is in the `m`. * The number of nodes of `listB` is in the `n`. * `1 <= m, n <= 3 * 104` * `1 <= Node.val <= 105` * `0 <= skipA < m` * `0 <= skipB < n` * `intersectVal` is `0` if `listA` and `listB` do not intersect. * `intersectVal == listA[skipA] == listB[skipB]` if `listA` and `listB` intersect. **Follow up:** Could you write a solution that runs in `O(m + n)` time and use only `O(1)` memory?
null
Hash Table,Linked List,Two Pointers
Easy
599
419
Have saunf bandh today they want to discuss this list to medium problem people forces after various board this problem has been previously in verse in sea interviews of Microsoft amazon attractive and selected for the gullible like and subscribe the channel for celebration remind me to the place But you discus superintendent have previously been observed in hindi interviews of different companies so without wasting any time during a question for defeat for the video and audio statement and splashed just get to reduce follow part.co.in 1.5 to reduce follow part.co.in 1.5 to reduce follow part.co.in 1.5 single open a rich and modifying dimple yadav Board this is the temperature tree school students should forgive and explain the question the cockroach and demonstration and finally bigg boss code for wishing someone posts tagged under apne sahi to shodesh activated board at odds to like and understand what is equal to cancer cell 186 and One Pinch Dot In This Should Not React Reaction Tax Representatives Beauty Tips Ka Rate And Dogs Different MP Sales Related End Error To Condition Sweater Knitting Partnership The Forest Department Which Can It Be Strictly Vertical And Speech For Joint An L A Torch Light Etc To That is 1999 judgment in pilot previous can't have proper leveling better chief minister vent is then this partnership panthers party by calling similarly a partnership like subscribe and subscribe question subscribe between to subscribe must subscribe and one of the major trishul cutting the number Of components contact in the number of the components in Stockport fold this pre list example a different Of all India point subscribe the amazing and similar for this channel subscribe now to receive new updates on hua hai tujh post jis bhi this approach aur cutting bhi number appoint sapoch but what is the work of this show one seven continents battleship are small dhyeya white Reports in this post No evidence for but I love you can reduce weight reduce Android based on December 19 2010 subscribe to the page if you liked the video then subscribe to see how can we take advantage of this will reach celebs Kim Excellent Ay This Award Winners Of which part of this worship is torch light and it's birthday and you but she's tied weights of which will not experiment on these numbers subscribe to the page if you liked the video then subscribe to subscribe our specially subscribe button hello how little lips kuva arrangement and legendary drivers urdu si ki x and x videos this is the total plus naunihal singh subscribe the channel please subscribe and subscribe the video then subscribe to subscribe our volume Kunodi Karte Code Show Without Wasting Any Time Loot Ki Ek Buddha Ko Deposit Subscribe Sudheesh And This Number Of Russia Which We Can Check This Number Of Columns That A Dish Statement And Statement Online To Difficult Least One Column In One Road No Different From Various Sources Say She Left And Right To Rule Over What Is Loop Ki Subscribe Russia Top O Ka Rate For Village Check Se Lapete To Se Lapete Zindagi Aayi - Mantron Suicide Safed Top Ten Zindagi Aayi - Mantron Suicide Safed Top Ten Zindagi Aayi - Mantron Suicide Safed Top Ten Plus To - Select - Friends Subscribe To This Channel Plus To - Select - Friends Subscribe To This Channel Plus To - Select - Friends Subscribe To This Channel - One Who Did Not Subscribe To - One Who Did Not Subscribe To - One Who Did Not Subscribe To Stop This Channel Subscribe My Channel Subscribe Thank You Statement Piece In Jin-Jin More Statement Piece In Jin-Jin More Statement Piece In Jin-Jin More Topless Scenes Water Dispenser And Solid Se Apps Show You What It Means To Ring Strong Stand Up Board That A Considered Is A facebook twitter top also - 120 left - 110 cc road suite top also - 120 left - 110 cc road suite top also - 120 left - 110 cc road suite presidential only these stars counted for the top 200 points in the forest column left 120 channel subscribe ko end and similarly for any se here force Rohit can be positive always be coming from Should District Sudhir Top District Code and Details Total No of Transmitting Its Lowest Tariff in Trial Court Punish in All It's Something Ko Assigned Pointed Toe Offers Issue-Based Support You Can Again Got This Pointed Toe Offers Issue-Based Support You Can Again Got This Pointed Toe Offers Issue-Based Support You Can Again Got This Video and Middle of 10000 Likes This Video Don't Forget to Like And Share Your Feedback And Don't Forget To Subscribe To This Channel Questions And Keep Learning Coding Thank You For Watching
Battleships in a Board
battleships-in-a-board
Given an `m x n` matrix `board` where each cell is a battleship `'X'` or empty `'.'`, return _the number of the **battleships** on_ `board`. **Battleships** can only be placed horizontally or vertically on `board`. In other words, they can only be made of the shape `1 x k` (`1` row, `k` columns) or `k x 1` (`k` rows, `1` column), where `k` can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships). **Example 1:** **Input:** board = \[\[ "X ", ". ", ". ", "X "\],\[ ". ", ". ", ". ", "X "\],\[ ". ", ". ", ". ", "X "\]\] **Output:** 2 **Example 2:** **Input:** board = \[\[ ". "\]\] **Output:** 0 **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 200` * `board[i][j]` is either `'.'` or `'X'`. **Follow up:** Could you do it in one-pass, using only `O(1)` extra memory and without modifying the values `board`?
null
Array,Depth-First Search,Matrix
Medium
null
462
Hello guys welcome to the video according to the series yes viewers problem school minimum mode to equal are elements of two souls were given a teacher in that size or Twitter minimum number of votes equal to make all elements equal annual increment and decrement elements by Subscribe Now to The Worst Thing You Can Give Charity and Good Health Care Number Off OK Let's See What's Right to Make All Elements S 150 Make Everything in the Race One Won't Give the Minimum Answer Thing About Everything Will Have to Spend a Lot Of Money 210 subscribe to subscribe our Sprint ₹50 OK is Absorbent Not at All Sprint ₹50 OK is Absorbent Not at All Sprint ₹50 OK is Absorbent Not at All Costs Here You Will Notice That One is the Name of the Thing You How to Make the Elements United and Lot of Money with Increasing Amount To Keep Creating More Money To Make Every Situation Is Not Something That Every Thing Is The Volume To Make You Love You Last Point Rupees And They Should 1150 Springs Rupees Your Mind Green The Number Of Video then subscribe to the Page Very Dangerous 123 3000 1000 2000 From A That When For Not Doing This Chapter Strike Shift From Seven To Make Sainik 1238 Short But 800 For Making It One To Three Of Spain ₹5 For Making 11123 Spend It Of Spain ₹5 For Making 11123 Spend It Of Spain ₹5 For Making 11123 Spend It Now You See In The Right Side Love You To Spend A Lot Of Money But You See The Number Center And Numbers Values ​​Are Skewed Normal Distribution Something Numbers Values ​​Are Skewed Normal Distribution Something Numbers Values ​​Are Skewed Normal Distribution Something You Have Centered Around Distribution Will Be Different From The Center Of The Day Other Values ​​Her Husband Night Will come out with Other Values ​​Her Husband Night Will come out with Other Values ​​Her Husband Night Will come out with your earliest subscribe and different from you have large area different from the complete to actually reach the smallest and the largest so subscribe to this video channel it's okay what about that thought that trying to make everything you want to know everything about How Much Money Will Be Spent on OnePlus 5t vs OnePlus 6 to 8 Plus Minus Plus Two You Have a Solid - 250 Subscribes 33351 Complaint Center Chapter Complete Center Will Have to Go One Takes Minimum Number of Factors and Objects Fine Lines Drawn on Left Side Make Everything Is 70's Is One Plus 6 7 Usi Entry Lift Seventh And To Make Se Zameen Dhvani Vaith Sangat You Need To Attract 100% Unit To Front Then Ok Sunna You Can Attract 100% Unit To Front Then Ok Sunna You Can Attract 100% Unit To Front Then Ok Sunna You Can Observe See The You Have Equal Distribution For Distribution Related To Units And Width And Overall Wellness Center List Subscribe Was That Common You Have 0 Messages Interview Minimum Balance 5000 Interviewer Answers In This Particular Case Of Wolves Tried To Central To The Balance Approach Road Distance To Subscribe The Guardian Subscribe Away From The Center And Values ​​From Center Away From The Center And Values ​​From Center Away From The Center And Values ​​From Center Subscribe towards and Delhi's to the center of the best and subscribe to your Radhe-Radhe knowledge 1378 709 I don't thing your Radhe-Radhe knowledge 1378 709 I don't thing your Radhe-Radhe knowledge 1378 709 I don't thing in this particular and what is the missions this left and right the number to make simple and will not want to make everything is Equal To Do The First And Last Love You To Center For Subscribe To Your Now Short Dresses For It's Something Sougian Of The Day Observed In OnePlus X Is Equal To - subscribe to the Page if Is Equal To - subscribe to the Page if Is Equal To - subscribe to the Page if you liked The Video then subscribe to - you liked The Video then subscribe to - you liked The Video then subscribe to - 110 to make it valid and supplied from the valley waste at various levels minus one in this difficult and difficulties and up to Play Again and Again 228 - 3 Will Be Ko * 50 Cases Pending That 228 - 3 Will Be Ko * 50 Cases Pending That 228 - 3 Will Be Ko * 50 Cases Pending That Bigg Boss Back Knowledge for Example Send A Ko Next Possible Hydration I Will Again Increment Start Till Degree Maintain Pet Start Will Prevent End Events Will Come Back to 7 Inch Extra Energy West Assembly in doing so finally Bigg Boss you have made your answers in this question answer and find it very clear number and CEO yo honey bunny distributor left and right hand side butt English chief phone number 0001 number SDO size different size key 125 Valuable Info Service Medium to Make the Number One to Subscribe - Make the Number One to Subscribe - Make the Number One to Subscribe - 28 - Subscribe to 28 - Subscribe to Number Of The Question Plus Minus One Will Dare Attack You When You Are Right Side Do n't Forget To Subscribe And Subscribe This Thinking One And Approach To Your Getting Same Answer And Service Rank Swimming Approach Towards Its Wings Payment Approach True In This Particular Quote On Solid Calling Start Equal to Zero and Intentions Equal to Columns Dot Size - 110 Intentions Equal to Columns Dot Size - 110 Intentions Equal to Columns Dot Size - 110 Just Through This Smile Start Is Loops in Lets Listening That You Whose Screen Settings Stop This Lesson Will Not Doing Any Work Number One of the Most Important Simply Difference is Kids And inside from the right hand side, take the name Safed - Na Dhanteras name Safed - Na Dhanteras name Safed - Na Dhanteras that we all are but actually this is that latent from this note, the noble person said Shri Laxman is always near you can share your views and you are sending you will always have to learn. I Know That All Subscribe Now To The Number Of Subscribe To 210 Risum Exit Polls And Depression Kunody Riddle Hai To If By Mistake And Even Tho The Are Conducted Between Us And Abuse Of Us 108 Turn Side Sports Working On One Text Message Thank you Fardeen Patient and Son
Minimum Moves to Equal Array Elements II
minimum-moves-to-equal-array-elements-ii
Given an integer array `nums` of size `n`, return _the minimum number of moves required to make all array elements equal_. In one move, you can increment or decrement an element of the array by `1`. Test cases are designed so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** 2 **Explanation:** Only two moves are needed (remember each move increments or decrements one element): \[1,2,3\] => \[2,2,3\] => \[2,2,2\] **Example 2:** **Input:** nums = \[1,10,2,9\] **Output:** 16 **Constraints:** * `n == nums.length` * `1 <= nums.length <= 105` * `-109 <= nums[i] <= 109`
null
Array,Math,Sorting
Medium
296,453,2160,2290
49
hello and welcome to another video in this video we're going to be working on group anagrams and in this problem you're given an array of strings and you want to group The anagrams together you can return the answer in any order anagram is a word or phrase rearranged or formed by rearranging letters of a different word of phrase typically using all the original letters exactly once so that's kind of what you need to know is you just need to know um like what defines an anagram and it's roughly this and the other thing for anagrams is all the letter counts are equal for both words right you just have a bunch of letters and you arrange them in a different way so if we have letters like a t well we can rearrange them like this maybe we can write like AE T maybe we can write like T and so on so they kind of show you this example here eight a e and t and there's kind of two ways to figure out what words are anagrams and we can talk about it briefly so one is sort the words so if you just sort by character you would get a for this word and then if you sort T by character you would also get a so you can sort all the words and then they all the anagrams sorted will be the same word so you can use a key of the sorted word and the value will be the anagram and that way like if we go through this example here so we get eat which will sorted be AET so for AET we will write a value of e and then we get T which sorted is once again AE T so we will write a value of T then we will get eight which sorted once again is AET so we will get eight and Nat which sorted is ant so we don't have that yet so we'll put ant over here with Nat in its anagrams and bat we don't have bat either sorted it will be ABT and we don't have that so we'll put it in there and so that's kind of how you do it then you just basically return all of your values in different arrays So like um e a t and 8 will be uh like one Nat will be one and bat and I forgot tan it looks like so yeah so tan sorted will also be Ant um so we will just put in tan so that's one way to do it and that's kind of like the intuitive the other way is for every anagram the count of the letters are the same right so for all of these anagrams you will have 1 a one e and one t and so now the problem is how do we get a key out of this like because the counts are the same how do we get a key out of this we need something to compare and so there is a way to do it um but you want to make sure your keys are the same so there's kind of two ways to do it one you can sort the letters and now notice that if it's only lowercase English letters like here the word is 100 characters so this isn't the best solution but let's say your words are like 10 the fourth um characters then you're going to have big letter counts and sorting the letters is pretty cheap because there's only 26 letters so totally fine to sort the letters so once you sort the letters in alphabetical order now sorting the letters is going to be a lot cheaper than sorting a 10 to the fourth length word right so we get the letter accounts we sort them and then we can just have some kind of key of like maybe character with a number so it would have something like A1 E1 T1 make this a string and now you can this will be like the key for the anagram so every anagram with this letter count will have this key and then this key can be used to figure it out now this is a better time complexity solution because you don't have to sort individual strings but actually in this problem this will be slower because your words are only 100 characters so you have to do a lot here right you have to get the counts you have to sort the keys and then you have to make the strings so this is going to be a lot more worth it if this was a bigger number so like in theory this will be a better time complexity but in practice it will actually be slower but like I said if like imagine if we had 10 to the 6th strings and maybe a string length is like 10 to the 4th or 10 to the 5th or something that's going to make it a lot better because sorting 10 5th is 10 5th * log 10 5th right um but 5th is 10 5th * log 10 5th right um but 5th is 10 5th * log 10 5th right um but sorting a 100 is fine because it's like log 100 which is I don't know like eight or something really small number times 100 so that's totally fine and then you don't have to make these like counters but that's kind of the two ways of doing it either sort the um strings themselves and use that as a key and then every single anagram will have the same key or get a dictionary of all the letters and make a key out of that this is one way to do it there's other ways um you don't have to sort the letters but sorting the letters is cheap because like I said if it's only lowercase English letters the log is basically nothing right like log of 26 cost costs you basically nothing like this is basically linear time so log 26 * 26 is linear time so that is log 26 * 26 is linear time so that is log 26 * 26 is linear time so that is like an easy way to make a key you just store all letters also obviously if your word doesn't even have 26 letters then it's all even less and so those are kind of the two ways um you can make keys in other ways like you can get the dictionary and you can make keys in other ways but the idea is you need some kind of key to represent the letter counts and you need these letter counts the reason you need them to be sorted or have some kind of indexing is because um dictionaries don't maintain index so like for one counter you might get this for another one you might get this and these should be the same that's why like sorting the letters is important because you want these to be the same thing and you can't store a dictionary as a key in a dictionary right so in our dictionary we're going to have for the key we're going to have some kind of thing to tell us like what bucket of anagrams this is in but you can't have a dictionary for that so this is just one way of doing it I'm just going to Cod up the solution I think it's um more intuitive and it's actually going to have better runtime and practice so we can do that so what we need is we need the key to be the sorted string and then the item or the value will be the actual anagram so we can just use a default dict here so we can say like anagrams equals default dict and each key will have a list of anagrams so this will be list then for word and strings so what we want to do is we want to break up the word into characters sort the characters make a word again and use that as a key you can't sort a string because a string is immutable so you have to first break it up into an array so you could just do this so you could say like um sorted word equals so ver we want to break it up so this is just going to you can turn into a list so like this then you want to sort it so you can do this you can make it a sorted list and then you want to join that whole sorted list to make it a string again so we can just join it like this so we break it up into a list we sort it and then we return it so now we have our key and now for our key we will put in this word into its list of anagrams so we can say anagrams sorted word equals word finally um our output so we're going to have a dictionary where we're going to have a key which will be a sort of word and then the values will be all of the anagrams for that um key so basically what we need is we just need to return the array of values we don't really need the key we need just every single array of anagrams so we can return anagrams Dov values so this will be the array of all of the arrays of anagrams that we have I don't know I still have this time it's interesting this is for another problem weird okay and it looks like we have a problem so let's see so it looks like we're not joining uh let's see what we ended up doing here output is at and a um oh yeah so we have the sorted word oh right so we don't want it to equal word we want to pend it right because this anagram sorted word needs to be a list of anagrams so append and the reason you use a default dict which is nice is if this key doesn't exist it will default to an empty list so hopefully that's correct okay there we go and you can see this is uh this is pretty efficient um the other way is actually slower because like I said these words are um only 100 characters so yes it's linear time instead of n logn but n logn for a small number is very it's roughly the same as linear time and making all the strings and all that stuff is actually going to be slower in practice so this is going to be runtime of so we have to sort every single um word so let's just say like the average length of a word is call it like w or something so it'll be like w log W for every single word um and then this is going to be the length of the word so it'll like w log W * n something like it'll like w log W * n something like it'll like w log W * n something like this but since every word is only 100 characters um that's fine um and yeah I think that's mostly it and then for the space so for the space obviously we have to have like the actual result that we're going to be returning like this values we have to have so the exra thing we're storing we are storing all the um all the sorted uh all the sorted words in worst case scenario let's say every word is unique let's say there are no anagrams this is going basically going to be o of n time is the number of words times W which is like number of characters in each word or something like that so it's going to be like n strings and then W is going to be the characters so this will be the total number of characters stored if you want the total number of words stored it'll be like o event or something like that oh yeah I think it's going to be all for this one like I said um not too bad and it is kind of cool to see the other solution and uh yeah like I think for tougher problems you can easily make a problem where sorting will fail and then the other solution will pass making that a string out of the dictionary values if you just change these constraints up a bit you make this value really big and then you make it so you can't sort the words but yeah that's going to be all for this one hopefully you liked it and if you did please like the video and subscribe to your channel and I'll see you in the next one thanks for watching
Group Anagrams
group-anagrams
Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** strs = \["eat","tea","tan","ate","nat","bat"\] **Output:** \[\["bat"\],\["nat","tan"\],\["ate","eat","tea"\]\] **Example 2:** **Input:** strs = \[""\] **Output:** \[\[""\]\] **Example 3:** **Input:** strs = \["a"\] **Output:** \[\["a"\]\] **Constraints:** * `1 <= strs.length <= 104` * `0 <= strs[i].length <= 100` * `strs[i]` consists of lowercase English letters.
null
Hash Table,String,Sorting
Medium
242,249
1,267
Hello Hi Friends Welcome Back To Yaar Go Into Solitude Problem 1267 Contrasts Date Communicate Now Four Wheel Gotras Description Of The Problem And Some Example Is Just Want To Mention Date My Channel Process Of Helping People While Preparing For Coding And Java Interviews And All My Channel Draw More Than 80 Solved Problems Explained In Details With Java Code And Problems Also Taken From Interview Schedule Of Birth Tech Companies Like Amazon App And Facebook Google Microsoft Yahoo Xtra And Others Problems Consist Of Different Varieties Of Which Very Important For Perspective Of Interviews With Sister. In Law of Dynamic Programming Links Listening Related Interview Questions Graph Minor Sisters Points Deficiency and Other Logical Questions Software Preparing Food in Interviews and Job Interviews Please subscribe this Channel that this channel will definitely help you during your preparation for coding and shower interviews so let's go through. To problem na description of the account best communicate you are all the map of service center represented ss mintu and interior matrix creative venture dead in the shell der ise sarovar and romance that is not sarovar to drops of the two communities with are on The same row and the same column within the return number of service tax can communicate with any other server sorry for example in this given first example but as you can see the 305 which is the same column which can communicate with teacher fearing development effects 110 in this row and column there Is on that sarwar suicide note communicate with any other sarwar and for this channel sirhind is row and column btc 2nd sardar ignore adarsh ​​har varsh on aa which 2nd sardar ignore adarsh ​​har varsh on aa which 2nd sardar ignore adarsh ​​har varsh on aa which available only row and column that is the vinod and is 9th february can communicate to answer is shooting this Pimples and Share And They Will Discuss How They Are Going to Solve This Problem Solve 1242 Hair Sau-Sau Asar Work Can Communicate for Example It Sau-Sau Asar Work Can Communicate for Example It Sau-Sau Asar Work Can Communicate for Example It Means Weaver Can Communicate Ideals and Gifts Non-Religious Respect Server on the Same Ideals and Gifts Non-Religious Respect Server on the Same Ideals and Gifts Non-Religious Respect Server on the Same Row and Same Column and Share and Same Column for example year there is another server right in 10m roles adhishwar can communicate with this server basically the soul which means data you know this two drops can communicate with each other parts hui gyankand sarvas can communicate with each other points in early trade fair thinking about this Two Drops Late on the Same Column That They Can Communicate with Each Other Soft Total Late and Forward Can Communicate with Each Other Hits Hui Agency Output Is 430 What the Problem Hui Have to Find Out Within Give One Great How Many Soil Witches Can Communicate With Key Sheet Quite Solid Nazm Free Mode Scholarship White Review It's So What They Are Going To You Will Start Getting Rid From The Beginning To The End Right From This Point To The End In This Point And Wherever Hui Final Android Din Will Keep Like Account Of How Many servers have been available in a metro and in the column basically solve will destroy you have you read to matrix is ​​vansh oriental you read to matrix is ​​vansh oriental you read to matrix is ​​vansh oriental and vertical and for example let's talk about the horizontal metric results for these indices 0 Hello friends this is two and Mrs. Goods Index and Vertical This is Hero Indexes Own Indexes to Indicator Second Indicators Which Mins 3001 Crops to Control Third Floor and So Will Vibrating for the Matrix Great Pride Greed Selva Is Android Wheeler Creator Who Recently and Political Matrix Which Will Tell Us How Many Computers a Available in a metro and in the column also as you can see this is the hero showroom computer morning calculated to here this is the first rollers one computer to give 10.1 hair belt rollers one computer to give 10.1 hair belt rollers one computer to give 10.1 hair belt length is controlled one computer in the second road suite computer scientist Last One Year And Through This One Another Server Side So They Can Create Your Own Favorite Song Similarly You Will Prepare And Matrix Political Best 2051 Sarovar Ki School Top Second Column To Sarvas And You Can Senior Member Two Years For Second Column And Third Floor One Drops Third column is Vansh work so we will first introduced metrics and they will have you read more recently and vertical a great you will update soon you will have this information handy after death at what will you take one variable tender for dates contract with you In the Beginning And Will Again Started Creating A Second Time From This Matrix Again From The Beginning Different From This Point Again Will Start Frequenting Ladies Fight For Stroke Cancer Control The Third And Fourth Rule And They Never Gave You Any Computer For Example Effigy Computer Year Will Give Vinod opposition of research and development will check the true and column the should have more than that available related to best feature for hero nominated as more service available for communication show will increment our ka 121 here right similarly when they riched year again hui mirch one Aware of any other server available right in the same row and column Ashwin Find there is another server available Indra Singh Rhode Island this horizontal to right Vikas tell you have a is equal to shy 2010 0 have to serve will again increment account from one to Three years ago they were enriched near present day again will have more than first available in this form and column directly on another server available in 2009 without taking 123 again will again five will tree to communicate with soil and information from this point to point subscribe to the Page if you liked The Video then subscribe to the detention Nau's Superstar Calculator Number of Runes and Number of Columns and in Her Right Hand and a Creative Vertical Matrix and Horizontal Matrix Vikas Want to Keep Track of How Many Services Available in Hero End Inch Length 100 Created Date Clear Using Special Size After Greed And After Dad I'm Just Going To Straight From All The Road And All The Right Columns To Right Means Will Go Sell Bissell From Strike The Sells In Today E Agree With U Want To fight and wherever you are not zero-valued witch mince pile it is all zero-valued witch mince pile it is all zero-valued witch mince pile it is all available like oriental i plus and vertical z plus side effects of witch can popular how many crosses and there horizontally available in the teacher of and column right for example For your will se horizontal hero plus right for this one and jo plus right to service centers zero plus year also recently hero plus size so let's get brigade 80 position will oo get to hair pack 342 approach and for political will get all vertical Two Plus Vikas For The Second Columns And Two Times Will Get Two Plus By Opposition Two Sarvas Will Get Two Senior Software Co * Get Two Senior Software Co * Get Two Senior Software Co * Copy Late Horizontal And Vertical Hair Were Traveling Through The Matrix So After Garden So Dushman This Time Complexity Shoulder Of Mintu Android Phone Number of Rose * Number Forms Similar for Aa Vijay Screed * Number Forms Similar for Aa Vijay Screed * Number Forms Similar for Aa Vijay Screed One Account Variables and Again Arnav Interesting Second Time Tight Birthday Celebrate Life 108 Total Time Complexity for the Algorithm Is Shoulder of Name * And for the Algorithm Is Shoulder of Name * And for the Algorithm Is Shoulder of Name * And Hearing Will Have to Interest Through Every Sale in the Great From starting to ventilator to depending on self year right shoulder of short time complex quarter of * in here tide came time complex quarter of * in here tide came time complex quarter of * in here tide came in to gain who is the time complexity and space complexity is order of fame plots in which you have created A to Z British vertical and horizontal address Hui Hai Curved Dam Bay Inside Secrets Of This Water Space Complexity You Have To Account Adarsh Simple Variables Will Not Give Any Special Data Structures Or Anything If So Let's Go And Continue With Power Solution For The Second Of All On Twitter And Vijay Space Create Account Variable And Over Again Interesting To Our Degree Dried And Wherever You Find Any Sarvar Din Hui Check Tune Of Vertical Which Is Greater Than One And Horizontal Is Greater Than What Means That Is Source Has More Than Raw And Is Deep Column Have More Than One Drops Gift Is the best friend circle communicable decision of communicable server rates increased our account in that case solve will check for kitchen porn insider to read and will return and account practice how will get for clearance the answer solitaire take medicine example and let's children work order against This example to make chor aur daaku work point is so you can see working for and for is the correct answer ride point is the correct answer know what will give rise to another test cases top complete raw dislocation shahpura answer sheet bcom six in that Case Right Sitem Solid With Latest Modified Unit Test So Here For Your Intuitive Who Here Were Right So Now Detroit They Are Doing So Now These Too Shall Also Set Up To Force Problems So Let's Go Ahead And Run Case Attested Swift Day And Ashish Yadav Answer Software Correct Surya Meeting Fix Communicable Soil And A Good Year Also Lets You And One More Sarwar Daily Discount Vikram7 Flats And One More Sarwar Neer With His Position They Are Adding One More Sarwar Solitude Come Seven In This Case Record Holder Hui One More Communicable Best Option 540 Gold Solution Year Point So Let's Take All The Examples And The Have Given At All These Unit Test Cases Mixture Dost Passes And Will Submit Our Solution Hai 2030 Three Four Wheeler Type Song Aa Were Getting Correct Answer Services Submit Our Solution Now 20000 Almost 99 Per Cent After The Other Submissions And Almost 70% Fast On Main Amar Hu Is And Almost 70% Fast On Main Amar Hu Is And Almost 70% Fast On Main Amar Hu Is Very Good For This Is The Way Can Solve Counters And Communicate Ashwa Tweet Is War Credit The Dream And Will Create And The You Recently And Vertical This To Address Same Created and populated and after that again hui treated through the greed and hui content how many lack cables rudely using the vertical and horizontal exhausted doing so that is the cockroach to solve this problem if you have already check my play list on my channel there is The Playlist Decode and Input Solution Details and Two Harold Problems Door of Change Company Aware Apple Amazon Facebook Google Microsoft Yahoo Least and Tricks Different Spring related Interview Questions in Coding Questions should be explained with examples Sophia Preparing for these Java Coding Questions and Pyaar Preparing for Java Interview Questions on Various Another Place Called a Java Interview of Which Focus on NH8 Different Telephonic Interview Questions were very popular in Java Interview Questions And How To Answer The So This Channel Candidate Will Help You If You Find Yourself If You Like This Solution Please Hit Like And Subscribe The Channel Because That Is The Video Can Reach To More People Like You Are Preparing For Coding And Job Interview Sunday can also watch this video and get help understanding clips and coding questions please subscribe to our channel and thanks for watching the video on
Count Servers that Communicate
remove-zero-sum-consecutive-nodes-from-linked-list
You are given a map of a server center, represented as a `m * n` integer matrix `grid`, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column. Return the number of servers that communicate with any other server. **Example 1:** **Input:** grid = \[\[1,0\],\[0,1\]\] **Output:** 0 **Explanation:** No servers can communicate with others. **Example 2:** **Input:** grid = \[\[1,0\],\[1,1\]\] **Output:** 3 **Explanation:** All three servers can communicate with at least one other server. **Example 3:** **Input:** grid = \[\[1,1,0,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,1\]\] **Output:** 4 **Explanation:** The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m <= 250` * `1 <= n <= 250` * `grid[i][j] == 0 or 1`
Convert the linked list into an array. While you can find a non-empty subarray with sum = 0, erase it. Convert the array into a linked list.
Hash Table,Linked List
Medium
1618
1,704
hello and welcome to today's daily lead code challenge let's solve question 1704 determine if string halves are alike so I've solved this already before but you're given a string s of even length split the string into two halves of equal length let a be the first half B be the second half two strings are alike if they have the same number of vowels a through U both lowercase and uppercase notice that s contains both lowercase and uppercase return true if a and b are alike otherwise return false cool Val Wells this is just going to be a set of a let's do this a e i o u cool uh now let's have a count of a string I'm going to have this return uh filter for Lambda C uh that's going to c lower and the thing that we're filtering down is s let's have the length be the L of S ID two and let's return count vowels of this like Speed code count vowels of s starting from to L is equal to count vowels of s starting from L I'm going onwards count vowels let's see I spelled that correctly l s um yeah this should work see if this is my shortest video nope wrong answer what did I do Len of list count vowels oh V I forgot to say in the wells there we go this is good wrong answer submit fastest video 15-day streak awesome and we're not 15-day streak awesome and we're not 15-day streak awesome and we're not doing too well on time but this is extremely fast and I don't know how to actually make this better yeah let's keep this very short thanks for watching see you tomorrow please like And subscribe bye
Determine if String Halves Are Alike
special-positions-in-a-binary-matrix
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
Array,Matrix
Easy
null
1,722
hey there everyone welcome back to lead coding in this video we will be solving the question number three of lead code weekly contest 223 name of the problem is minimize having distance after swipe operations now in this problem we are given two arrays the source array and the target array and we are given another array swaps now each value of the array allowed swaps it will contain two indices so here we can see that the example contains zero and one so it means that we can swap the values in the source array at the index zero and one now the next value is two and three so it means that we can swap the values at the index two and at the index 3 in the source array so these are the allowed swaps now we have to return the minimum humming distance that means the difference at each index of the source and the target array so we have to minimize this difference by doing as many swaps as we can so here we did the swap at the index zero and one and this is the array that we obtained after this swap operation then the next swipe operation is at the index two and three so doing that we obtained this array now if we compare this array with the target array we can see that there is only one index that is the index number three at which there is a difference other all indices are same as the target except this index so we have to return how many such indices are there we have to minimize those indices here the answer is one in this case the allowed steps there are no allowed swept so we have to compare the source and the target array as it is now when we are comparing them we will find that there are differences at the index one and at the index two yeah so there are two indices on which there's a difference so the answer is two similarly here we can see that the allowed swaps are so many and after the swap we can make the source that is same as the target array that is why the output is zero now let us start solving this problem so i think let me take this example the last one all right the source array the target and the swaps so we can swap the index 0 and the index 4 then we can swap the index 4 and the index 2 then index 1 and 3 then 1 and 4. so these are the swaps that we can do now if an element is there at the index 0 it can go to any index that is 4 2 1 or 3. how so from 0 it can go to index 4 from index 4 it can go to index 2 after doing a swap also from index for it can go to index one and from index one it can go to the index three after the swap so from index zero we can go to any of these indices that is four two one and three similarly from four we can go to index zero doing a swap from 4 we can go to index 2 doing a swap we can go to index 1 and then we can go to index 3 as well from 4 so to go to 3 from 4 we will first go to 1 then we will go from 1 to 3 all right similarly from two we can go to all of these indices so we can swap between all of these indices which are connected how so this is our source array this is our target array now 5 which is at index 0 let me first mark the indices 2 3 and 4 yeah so from 4 we can go to any index so 5 will go to 1 and 1 will have to come to the index 0 so we will obtain 1 5 2 4 and 3. now from the remaining we want 4 to come at the index 2 and we can actually swap two and four so that's why four will come here and two will have to come here after this swap now this is the same array as the target array and that is why we got the answer as zero in this case now what i want to depict by taking this example is uh whichever indices are connected using this swap array we can actually transfer value from any index to any other index for example let me take this so let us say the index 1 2 and 3 are connected and i am taking a 6 size array then the index four and five and zero are connected we can transfer the value which is at the index one to uh any of these indices two or three and we can transfer whatever value is there at the index two to the index one or to the index three similarly we can transfer the value at the index four to the index five or to the index zero and from five to the index four to the index zero and from zero to 5 and 4 so we just have to see that what all indices are connected using this swap array and then we can rotate the values in those indices now how to actually find these groups for that we can use a very useful data structure called dsu disjoint set union so i'm not going to teach dsu in this lecture because i have already covered it in the past there's a dedicated video the link will be provided in the description so you can go to that learn the data structure and then i have also solved few example problems from this data structure in that video itself now when you are comfortable with this data structure you can easily solve this problem so we just have to form these groups we just have to find these unions and after that we will see that inside these unions what all are the differences so let's say i think there is no example uh yeah let me take some example and explain what we have to do once we are done finding these unions let us say this is our first union now this these three values are the first union and these two are in the second union okay these are in the first union these are in the second union i'm talking about the indices now let us denote the head of this union as the index zero and let us denote the head of this union as the index 3 okay now in the union 1 we can rotate all these values so one can come to the position where 5 is there and 5 can come to the position where 1 is there so we can obtain something like this 1 5 and 2 okay so in the target union the values are 1 5 and 4. now there's a difference at this position so in this example the difference is at one position okay in this union the difference is at one position only now talking about the second union which is denoted by three it is uh four and three and the target is two and three now we can take three to this position and four to this position because we saw that we can rotate inside the union we can transfer any value from any place to other place so we can obtain three and four now the difference is at this index so there's only one difference in this union as well so in total there are two differences so that is what we can do so now let us see the code for the same i will just go through the code walkthrough so here's the union and defined these two you will get to know in the lecture which i have provided in the description if you don't know about it already now the other things i am going to code this out so first of all i am initializing this parent and the size array of union find then i'm creating a map so basically this map is of type int comma map of end again so basically what i want is my map of index this should denote the name of the union for example here we were denoting the first union by zero and the second union by three so these are the head of the unions so this first integer will denote that union that which union is this so once we know the union then we have another value that we have to count the number of elements inside that union so we will count the occurrence of 1. actually we are just bothered about what all elements are there inside the union in the source and the target so the union which is marked by zero we will count the occurrence of all the elements so for that uh m of 0 and 5 will be 1 m of 0 and 1 will be 1 we are just counting and m of 2 sorry 0 and 2 will also be 1 so we are storing the count of source and then we will go to the target for the same union so we will see in the target that m of 0 comma 1 so we will just reduce it we were incrementing it in the source and now we will be reducing it in the target so we will do minus so after minus this will become 0 okay then we will go to the next one that is m of 0 comma five now the value for this is also one so we will do minus because we are on the target so we will also reduce here so this will also become zero now for m of four m of zero comma 4 we will do minus for this as well so this will be minus 1 because there is no m of 0 comma 4 so m of 0 comma 4 will be -1 okay -1 okay -1 okay so now in total in the union zero inside the map we will have two values one value is minus one the second value is one it means that there's only one difference we will just sum up these values whatever is there inside the union denoted by 0 we will sum up those values we will sum up the absolute of those values so here the absolute will be minus 1 absolute of minus 1 plus 1 that is equal to 1 plus 1 is equal to 2. so this is the total difference inside this map inside this union denoted by 0 so we can divide it by 2 and we can obtain the number of differences the other thing that we can do is we can keep two maps so we can actually keep two maps the first map will denote the count of the source the second map will denote the count of the target for the same union that is denoted by 0 and then we can take the differences but here we are taking the differences at the same time we are just reducing we are just incrementing it at the time of the source and decrementing it at the time of the target and sometimes it might be possible that there is some negative value so for that we will have to take the absolute and then divided by 2. i hope you understand it will be more clear if we take the if we look at the code so now you got what this map is for then yes then we will initialize an answer with zero now we will go to each of the swept and union them together so this will form the unions then we will go to each of the index one by one for the source and we will increment it as i told you we will increment for now the find i will denote the head of the union find i will give the head of the union so for head of the union we are incrementing this value for the source and then for the target we are decrementing this value now we will go to each of the union so we are going to each of the union and we are obtaining the second map so b is the second map now we are going to each of the values inside the second map and we are taking the absolute as i told you and adding it to the answer and then finally returning answer by 2. so this code is accepted now talking about the space and the time complexity so we are using big o of n extra space here we can see that we are using big of an extra space inside the map also so in the worst case let us say that there these swap array size is zero so in that case there will be total number of n unions so each of the index will be in different unions so there will be total n unions so for that the map will be of size n the first map will be of size n and for each map inside this map will be of size one so in that case this will be big o of n so the space complexity that we are using is big o of n now i want you guys to tell me the time complexity of this solution in the comments so for hint you can see that we are using this swap array and for each of this web we are calling union all right so if you want more such videos in the future do subscribe to the channel and press the bell icon so that you can get notifications to the latest videos thank you
Minimize Hamming Distance After Swap Operations
throne-inheritance
You are given two integer arrays, `source` and `target`, both of length `n`. You are also given an array `allowedSwaps` where each `allowedSwaps[i] = [ai, bi]` indicates that you are allowed to swap the elements at index `ai` and index `bi` **(0-indexed)** of array `source`. Note that you can swap elements at a specific pair of indices **multiple** times and in **any** order. The **Hamming distance** of two arrays of the same length, `source` and `target`, is the number of positions where the elements are different. Formally, it is the number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]` **(0-indexed)**. Return _the **minimum Hamming distance** of_ `source` _and_ `target` _after performing **any** amount of swap operations on array_ `source`_._ **Example 1:** **Input:** source = \[1,2,3,4\], target = \[2,1,4,5\], allowedSwaps = \[\[0,1\],\[2,3\]\] **Output:** 1 **Explanation:** source can be transformed the following way: - Swap indices 0 and 1: source = \[2,1,3,4\] - Swap indices 2 and 3: source = \[2,1,4,3\] The Hamming distance of source and target is 1 as they differ in 1 position: index 3. **Example 2:** **Input:** source = \[1,2,3,4\], target = \[1,3,2,4\], allowedSwaps = \[\] **Output:** 2 **Explanation:** There are no allowed swaps. The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2. **Example 3:** **Input:** source = \[5,1,2,4,3\], target = \[1,5,4,2,3\], allowedSwaps = \[\[0,4\],\[4,2\],\[1,3\],\[1,4\]\] **Output:** 0 **Constraints:** * `n == source.length == target.length` * `1 <= n <= 105` * `1 <= source[i], target[i] <= 105` * `0 <= allowedSwaps.length <= 105` * `allowedSwaps[i].length == 2` * `0 <= ai, bi <= n - 1` * `ai != bi`
Create a tree structure of the family. Without deaths, the order of inheritance is simply a pre-order traversal of the tree. Mark the dead family members tree nodes and don't include them in the final order.
Hash Table,Tree,Depth-First Search,Design
Medium
2104
373
today we're gonna be working on nude code question number 373 find K pairs with smallest sums you are given to integer arrays nums 1 and nums two sorted in ascending order and an integer K Define a pair UV which consists of one element from the first array and one element from the second array return the K appears so we're gonna with the smallest sums so if we have been given nums 1 is equal to 1 7 and 11 and numbers to 4 and 6 and we're going to be returning three smallest pairs so out of all these pairs which can be formed using these uh using these numbers from these two areas we're going to be returning one two one four and one six similarly over here total number is again because 3 multiplied by three we can have up to actually that's not three but so one is going to make a combination with all these then the second is gonna be making a combination with all these and the third element it's gonna be making a combination of all these so we're going to be having a total of uh nine pairs so out of those nine we're going to build a tightening K number of pairs with the smallest values so we're going to be using the priority queue initially if we just have our list of integer with the result equal to new array list the sanity check would be if most of them like if any of it is 0 if the K is 0 if the elements are not available so nums 1 is equal to null similarly nums 2 is equal to null or uh nums to length is equal to zero okay nums one length is equal to zero okay or k is equal to zero in all these cases we're going to be returning um just the result okay after that we can have our periodic EQ of end uh we're gonna have like uh we're gonna be putting in an array with two elements in it and let's call it Q and then it's gonna be a new period EQ okay the way it's gonna calculate is uh basically it's gonna take the nums of one right of a zero and then because we need to calculate the sum of that and the other one is the nums of 2 of a one all right minus nums off to actually I'm so sorry basically nums of this is gonna get added to the number of one of A1 right yes minus nums of one of B zero minus nums of two of B1 so basically we are just sorting them by the sum okay then we're gonna have our Loop because we're going to be filling in only K elements that's going to make the algorithm K log K so we are not going to be filling in all the uh all the combinations we're just going to be filling in up to K termination so our end I is gonna go from zero I is less than there are two conditions here one is that the nums of one dot length it should stay less than that and the I is less than k okay and then for that we're gonna be offering it to uh new end okay the values are gonna be I and then 0. foreign processing the new one and putting uh the right uh a combination back into the queue and current is equal to Q Dot or oh but we need to remember that we need to make sure that it is not empty while the K is greater than zero and the queue is not empty right yeah while it is not empty so we're gonna say that end current is gonna be equal to Q dot for okay result dot add so whatever is gonna be pulled by we're gonna be putting it in there array start and the reason for that is remember we are initially we initialize everything with the uh with the second element as zero so we are we know that the first time the result is gonna be the right result right so the first time we just put it in there so we know that the first one is going to be the right one so we can actually put it directly into the result uh array start as less so basically we're gonna take the first two elements from the two areas and then uh and then convert them to a list right before putting it into the result nums one of current zero and none store of current one okay and the last thing is we're gonna put uh things back to the uh to the queue so for that we want to make sure that the current one is actually less than the nums of 2 dot length minus one so as long as we are within bounds we're gonna be putting the new combination backend for the new combination it's going to be new and then the current of zero and the next one is going to be current of 1 plus 1. and then we're going to decrement the K2 once we are done we can return the result so now we're able to find the symbol because we need to have nums still can't find symbol of and of course okay let's just verify our priority queue formula here one more time that the numbers of one we are actually taking uh nums of one a 0 and we are adding it because numbers with the numbers of 2 no we are not doing that we need to add it to the numbers of 2 right and then subtract nums of one uh B 0 this time yes and then subtract uh numbers of 2b1 that is right one more time yep looking good and it works
Find K Pairs with Smallest Sums
find-k-pairs-with-smallest-sums
You are given two integer arrays `nums1` and `nums2` sorted in **ascending order** and an integer `k`. Define a pair `(u, v)` which consists of one element from the first array and one element from the second array. Return _the_ `k` _pairs_ `(u1, v1), (u2, v2), ..., (uk, vk)` _with the smallest sums_. **Example 1:** **Input:** nums1 = \[1,7,11\], nums2 = \[2,4,6\], k = 3 **Output:** \[\[1,2\],\[1,4\],\[1,6\]\] **Explanation:** The first 3 pairs are returned from the sequence: \[1,2\],\[1,4\],\[1,6\],\[7,2\],\[7,4\],\[11,2\],\[7,6\],\[11,4\],\[11,6\] **Example 2:** **Input:** nums1 = \[1,1,2\], nums2 = \[1,2,3\], k = 2 **Output:** \[\[1,1\],\[1,1\]\] **Explanation:** The first 2 pairs are returned from the sequence: \[1,1\],\[1,1\],\[1,2\],\[2,1\],\[1,2\],\[2,2\],\[1,3\],\[1,3\],\[2,3\] **Example 3:** **Input:** nums1 = \[1,2\], nums2 = \[3\], k = 3 **Output:** \[\[1,3\],\[2,3\]\] **Explanation:** All possible pairs are returned from the sequence: \[1,3\],\[2,3\] **Constraints:** * `1 <= nums1.length, nums2.length <= 105` * `-109 <= nums1[i], nums2[i] <= 109` * `nums1` and `nums2` both are sorted in **ascending order**. * `1 <= k <= 104`
null
Array,Heap (Priority Queue)
Medium
378,719,2150
1,640
Is Then A Today They Are Going To 7 The Fast Follow Benefits Replay Mixture's Deformation True Contact Nation Should Strive To Easily Understand Statement Password Or Singh Hair You Will Be Given Twenty One Is The Schezwan When Scam Id Quantum Mode List Advocate Morning Nickel Unit Fluid Modifying sequence of the small and what means subscribe which hair light batter or person portion occurred this shift daily back and using back record it is easily from its influence of this beneficial and returns through is on pregnancy all the element economic beckley same but hair so beautiful From This Side You Will Not Be Able To Change Sequence Hot Moments Of Life For Dark Skin Hair Per Africa Election 2010 Forces Butter Id Different Dried So You Want To Be Descended From This Piece Minute Modify The Sequence Powder Rights With This Not Permitted To Windows 10 To Return Forms For This Is The Condition Hidden Facts Can Also Helps Elements Of All The President Of 220 The Two Main Conditions That You Need To Keep In Mind Should Chant Radha-Krsna Par Also Right Here Right Now Mind Should Chant Radha-Krsna Par Also Right Here Right Now Mind Should Chant Radha-Krsna Par Also Right Here Right Now You Can Easily From This One Side Sleep Hair Pack Abs Co Cases Hair Is Nominated For Nurses And Index Of A Sacrificer Is Tomato 646 Updates In Our Daily Life Day Box Half Hour 98100 Subscription Form The Amazing Subscribe Elements Of Obscuritism subscribe The Channel Please subscribe and subscribe the Channel 5491 Fennel Can Do Solid Ask Cement Test That 416 Floor End Seek 191 Dry Flour Withdraw Black Puberty Fluid Pick Behind Inhibition 1518 578 Will See OK Hind Is Particular Number Is Sexual 909080 To The Second Remedy 4600 He Took Off For Florida I Subscribed Four 61 Subscribe School was there 61 Subscribe School was there 61 Subscribe School was there but difficulties in different Professional Life Insurance The hardest and 181 Don't push it the hardest 98100 Idli Sandwich Subscribe button and subscribe Video like subscribe and subscribe the Channel Please subscribe and hanging your index is Not matching and element in return for died so acid dissolves should e agri that the court met so they will see the rapist subscribe like this right side 46 and last not died on 18 th that and oil 600 width him in food and allied like That was my starting position ok sir can see this life what information day withdrawal side its pendant for it back support you 1969 subscribe suvvi subscribe my channel ko subscribe The Channel Please subscribe and subscribe me index and rot one matches function physical inside and test Match The Element Officer Of The Peace Sui Dash Looted And Everything Gets Wealth In Western Influences Can Be Done For Research And Subscribe He Can Create It Surya Using Multiple Formats For Lips Us Loud Office Time Comes With Hard Work With This App You Can Create Your Own Soul and Notification Optimize solution right side will now identify them where is the time to subscribe mother can only contact number 90 a the fifth contact number date and time for the properties distic will contain only unique numbers of units unit number 0001 number ok subscribe button to Do 220 After And Important Died So Lets On Lead Acid Containing Time 600 800 Places 94608 A Non Floor Thanks 8 200 Unit Two From This Using This Right In Hundred Vehicles I Can Have Total 20 Numbers 120 Value Of Return To Test Cricket A Bit Vettori and Ryder Shaw Subscribe Our In A Good Source of Vitamin B12 4906 Mind 1948 1992 And You Will Go Through This Will Keep Us That The I Will Map Correspondent Index In The Given Importance For The Particular Numbers And To The Injured I Will Determine What Will be the one who will be subject 210 patti sycamore number that sophia single number 1098 any problem they can easily see ok idnot and share and index is not zero that is number is printer input and they can go ahead with which element 1578 to z30 information The Near Good Hussain Syed Delhi Dare Not Supported It Before And Shyam Temple Elements In The Peace 300 Which All The Admins Are Also Expressed Has Vitamin C Char Din Laut I Will Do I Will Sector Index Of 40 Index Of The Previous One Right For Which you should be sequence flight and porn cd media at least be in a position of chapter for deposit this position rai limited next you can see 15645 change indexes 3483 for which bay to vietnam flight is tree selfish index for the map it is to 16 5353 Pregnancy Request One Dead To Number And Sequence Hair In And In Lantern Switch In This Way Can Consider This Sequence From Supernatural Which Index Logic Difficult Words Used In This Application Will Reduce The Time Complexity So Let's Increase The God Of Small 100's tension back to this is something creative and induction tuesday your call 100 but he knows that for life to get hair oil edison president size 101 requested and contact number 3 want to is next system disturbance white enterprises 101 open now they are going to The Element Offers In Food And Restaurants In This Also A Public 478 Rides And Inductive One Slide Visually Map Right Now But Meeting One Piece Yachting Video 10 Minutes 5000 Kids Run OK Develop Start 120 For The Place Where Mode On Invented The Best Way The Video then subscribe to The Amazing subscribe friends number 90 in return for a ride and subscribe is beneficial hai to incident love * added beneficial hai to incident love * added beneficial hai to incident love * added one is for peace and welcome to this peace time ride so ifin activate them died so let's weekly of the solution check weather its chapter note Subscribe its meeting on hunter feedback on young friends please like this video please do subscribe button and the natives of administration to return in the comment section thanks for watching
Check Array Formation Through Concatenation
design-a-file-sharing-system
You are given an array of **distinct** integers `arr` and an array of integer arrays `pieces`, where the integers in `pieces` are **distinct**. Your goal is to form `arr` by concatenating the arrays in `pieces` **in any order**. However, you are **not** allowed to reorder the integers in each array `pieces[i]`. Return `true` _if it is possible_ _to form the array_ `arr` _from_ `pieces`. Otherwise, return `false`. **Example 1:** **Input:** arr = \[15,88\], pieces = \[\[88\],\[15\]\] **Output:** true **Explanation:** Concatenate \[15\] then \[88\] **Example 2:** **Input:** arr = \[49,18,16\], pieces = \[\[16,18,49\]\] **Output:** false **Explanation:** Even though the numbers match, we cannot reorder pieces\[0\]. **Example 3:** **Input:** arr = \[91,4,64,78\], pieces = \[\[78\],\[4,64\],\[91\]\] **Output:** true **Explanation:** Concatenate \[91\] then \[4,64\] then \[78\] **Constraints:** * `1 <= pieces.length <= arr.length <= 100` * `sum(pieces[i].length) == arr.length` * `1 <= pieces[i].length <= arr.length` * `1 <= arr[i], pieces[i][j] <= 100` * The integers in `arr` are **distinct**. * The integers in `pieces` are **distinct** (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).
Try to solve it by keeping for each file chunk, the users who have this chunk. Try to solve it by keeping all the users in the system with their owned chunks, and when you request a chunk, check all users for it.
Hash Table,Design,Heap (Priority Queue),Data Stream
Medium
355
90
Hello Hi Everyone Welcome To My Channel And We Are Going To Solve A Classical Problem Sabse To Me Already Sold Very Long Back Sabse Problem Seven So Let's Problem Aaye Delhi Suggest First Solve The Problem Because This Problem Can Beat Vishal Net Problem Solve This Problem Solve Basically Giver Numbers And Need To Generate All Subscribe And Answer For Happy Return Duplicate Subscribe To Subscribe Veerwal Sonth Raw Number Like Subscribe * Itself And Subsidies To Time Lag 12138 Tours Sub School And Click Positive Way Number subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to the अब हिस्ब से सिमार्ली अफ्टर विच अब हिस्ब से सिमार्ली अफ्टर विच अब हिस्ब से सिमार्ली अफ्टर विच अलेक्ट्रोनिक्सोफट उच विलिक टो नौ फोर्म विशेष यू क्नोट लिक था टक्लॉन्डस 2513 Video then subscribe to टक्लॉन्डस 2513 Video then subscribe to टक्लॉन्डस 2513 Video then subscribe to the Page if the Video then subscribe to the Page if you liked The Video then subscribe to the Page That All Seervi Blindly Doing And 123 45678910 20138 Subscribe To Solving Subscribe Now To Receive New Updates To-Do For Subscribe subscribe and subscribe the Video then subscribe to The Amazing Indian Wedding Events On A Plane Sea All The Most 400 Training Center Will Remove Duplicates Pilots Huge Body Problems Solution To Update This Will Be First Number One Tanning Remove Duplicate Subscribe Half Fuel Jasvir And subscribe The Amazing 130 Symbols This All Side Division Duplicate Is Totally Flight Fully Copy Paste Edit And Updated With Obscene Method In this problem December subscribe for Live video use this subscribe and subscribe the subscribe what will oo will sperm bhi MD sabse zorse it's ok no we need to front rock ve all in one word for sharing this for you and you will like subscribe now To independent kingdoms subscribe is point Video subscribe to subscribe Video to like this servi in ​​your solid get confused in ​​your solid get confused in ​​your solid get confused like start from the same approach sexual food and supplies from being anti subscribe nowhere in the decide weather to choose not to avoid player and updated with components subscribe Now to receive with that another word no will call another level next level vestige than more than 250 they know they can't have like subscribe and know how to check the current president zero first divine on this is equal to white like subscribe middling from From 2nd subscribe in a reader quid don't abuse from five previous quality of mid select discus will not to withdraw into to exclusions will not you but in to-do will you all subscribe and saunf in to-do will you all subscribe and saunf in to-do will you all subscribe and saunf aur The Video then subscribe to subscribe our YouTube Channel and subscribe the defeat we white mention in that case opponent to select which continued for this is the very important condition which will help you solve math problems like in combination 12345 subscribe this YouTube channel subscribe see this alarm set slav compiling and where great expectations let's give submit The fact that accepts no what is the time complexity of dissolution of fennel but size length and will have to dress power and subsidies for this will go alone in tourist power and times and every time in which govind subscribe and the time complexity of dissolution of tourists power subscribe Like and subscribe 12345
Subsets II
subsets-ii
Given an integer array `nums` that may contain duplicates, return _all possible_ _subsets_ _(the power set)_. The solution set **must not** contain duplicate subsets. Return the solution in **any order**. **Example 1:** **Input:** nums = \[1,2,2\] **Output:** \[\[\],\[1\],\[1,2\],\[1,2,2\],\[2\],\[2,2\]\] **Example 2:** **Input:** nums = \[0\] **Output:** \[\[\],\[0\]\] **Constraints:** * `1 <= nums.length <= 10` * `-10 <= nums[i] <= 10`
null
Array,Backtracking,Bit Manipulation
Medium
78,2109
144
hello everyone welcome back to my channel this is jess so today in this video we're going to go over the implementation of pre-order over the implementation of pre-order over the implementation of pre-order traversal on binary tree if you want a quick recap on how pre-order pre-order pre-order traversal works on a binary tree i've made a quick video on those so feel free to click into that video i'll link it in the top right corner so without further ado let's get started this question statement is very simple you're given the root of a binary tree and you're asked to return the pre-order and you're asked to return the pre-order and you're asked to return the pre-order traversal of its node's value and from the question statement right here we can see that it's asking us to return a list of integers so we're going to return a list of all the values in this tree based on this pre-order traversal based on this pre-order traversal based on this pre-order traversal order so first thing first we need to check whether the given root node is valid so if not root meaning if it's null then we just simply return an empty list and then if it's not null meaning this is a valid binary tree we're going to create our result list so equal to an empty list and then for this implementation i'm going to do it in the recursive way so now let's first implement this recursion recursive method let's call it helper and it takes in itself and then a root node first thing we need to check if the current room node is valid so if it is valid what we need to do is to since we're returning the list of all the node's value so right here we're gonna append the current root nodes value into the result list we get this part from the predefined tree node definition that's given on top of the question so we know that it has this dot value property and it contains the value of the node so after we've append we've appended this value into the result list what we need to do is to recursively call this helper function with its left child and its right child so we call self dot helper ru dot left also getting this property from the definition on top self dot helper root dot right so we know for preorder traversal or for any traversal of dfs we're always going from a left to right so that's why we're calling the left before dot right and then let's go back to the original function the base function so we're going to call this helper function passing in our root and once the helper function have traversed through the whole tree our result list should contain the pre-order traversal should contain the pre-order traversal should contain the pre-order traversal of the values of each node in the tree so we're just going to return self dot result all right so that concludes the implementation for the pre-order implementation for the pre-order implementation for the pre-order traversal on a binary tree and now let's take a look at the runtime and the space complexity for the runtime since we're going through or traversing the whole tree and we're going to visit each node once so the runtime is just going to be big o of n and being the number of nodes in the tree for space complexity in the worst case scenario if we have a binary tree that shapes like a length list meaning that each node will have a left child and just going along say if we have n nodes in this tree then in our recursion function the stack will have at most n levels that case space complexity will be big o of n and being the number of nodes all alright so that is it for today i hope you enjoyed this video please give this a video a thumb up if you found this video helpful and feel free to leave any comments in the comment section i will see you in my next video bye you
Binary Tree Preorder Traversal
binary-tree-preorder-traversal
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
94,255,775
72
hi everyone welcome back to the channel called daily challenge problem number 72 headed distance so it's a really short problem but it's a really interesting problem to solve as well so we will be given two strings Ward one and board two and we have to basically return the minimum number of operations we would require to convert word one to work to and we can perform these three operations insert delete and replace so it's very similar to uh you know a DP problem called longest common subsequence problem right so that's what exactly if you have to do so let me explain that I mean I'll explain it with the example let's say in this figure we have like I have taken the first uh example itself we had horse as a word one and Ros has more tool so we have to basically find out a path you know with the shortest distance in it so how do we do that basically on one axis you will uh write all your characters from Ward one on another excess you will write your characters from War 2 okay and now uh you can see there is an extra row and column right in this column it's basically you know to handle HK cells then these columns are this extra row is for basically handling the HKC and what exactly it uh represents is operations perform like number of operation we will have to perform for this particular element if there is nothing in word one okay so what do we basically take this for example we took these two uh characters right we will check if these two characters are equal or not if they are equal what I'm gonna do I'm gonna pick the diagonal value okay if not what we'll do we will check for the minimum value Within the block right to it diagonal and the block below it and we're gonna add one to the minimum value of it and we'll populate that so I have uh you know started populating this table from using a bottom-up approach that's why you can a bottom-up approach that's why you can a bottom-up approach that's why you can see this path like if I mark this path it's going to be we'll start from here then going this point this okay so this one's explanation Let's uh go to the program okay posting first I want to handle some edge cases so let's say okay your word one is equal to what in this case I want to return 0 right next case is if length or word one is or length of Row 2 is data in that case I want to return the maximum amount of word one or length of voltage okay now comes the complicated and interesting but the main part basically now we need to define a dprx DPI rate to represent the Matrix which we just saw right I want to initialize all the values with Infinity okay we did this and how many columns we wanted to have length of word to plus 1 okay I wanted to have these number of columns into the Matrix and how many rows I wanted to knows to be or length or word of one like word one right and this Plus One will help us getting those extra column and root which we just solves okay once you are done those values like in the extra column were treated right so I'm gonna do that for i n range entho got two plus one sorry plus one and what we have to fill in is so basically we are filling the last column in this case right now right will be equal to what length of what two minus I so we will go back to that Matrix again let's go there okay so if we are over here and if we see what these values are basically so let's say this pivotal index 0 over here right and the length of the string was 3 minus 0 is 3. similarly for 2 1 and so on so forth so that's uh that is exact logic uh behind filling the extra rules we are going to do exactly the same for word like for our columns as well I okay so it'll be one that is it now uh Central dpu function to populate the values I and we wanted to do a bottom upward course right word one minus one till we reached to root zero and similarly for like we'll need another loop basically or for two as well we have to go to this one so we have just two conditions if what was that a word I is equals to word to J then what we wanted to fill the value with the exact same value which we had at diagonal right PP of I in J is DT of I plus 1 J plus 1 we didn't need to perform any operation on it else and what we wanted to do we wanted to fill the value with 1 plus minimum of all the corresponding values like values on the right diagonal and bottom so we can do that let me just copy this minimum of diagonal then for below I'll be using 5 plus 1 J and for the right one we will be using 5 later yeah it seems fine let's uh check out the test cases okay list index of the range why I did so wardrobe at but okay sorry we use word one over here yeah so the test is not clear let's submit for the evaluation and awesome so the solution that accepted and with one detail like we have performed 70 1.6 percent of the have performed 70 1.6 percent of the have performed 70 1.6 percent of the summit solution so yeah thanks again guys for watching video and stay tuned with upcoming ones don't forget to subscribe the channel as well 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
1,658
hey what's up guys this is chung here again so this time let's take a look at one of the weekly contest problem number 1658 minimum operations to reduce x to zero yeah i think this is a pretty good problem media level problem okay so you're given like an integer array nums and an integer x in one operations you can either remove the leftmost or the rightmost element from the array nums and sub subtract its value from x and note that the modifies the this modifies the array for the future operation right and then it asks you to return the minimum number of operations to reduce x to exactly zero if it's possible otherwise return minus 1. all right so one of the few examples here so the first one you know we have you're given like a number of this one so here the optimum solute solution is removed a lot the last two elements to reduce to zero which is this one you remove three first and then you remove two then you got five right so and another one it's like this two here so there's no way you can remove any you can re reduce this x to zero so that's why you have minus one and the first ten here right so you remove three first you move this one and this one that's the that's total 10. that's why you have five right and so here's some important constraints here as you guys can see the numbers about x is 10 to the power of 9 and the number of lengths is 10 to the power of 5. okay i mean without this without the constraints i mean i think many people most of us will start thinking about okay of course so this is like all right we do return the minimum number of operations oh cool so we at each of the state we have two options we can either remove the ones on the left or we can remove the ones on the right and then we can simply use the bfs right let's just use bf as search and every time we have a we can have a left and right pointer right i mean anytime when we see the current if the current one is not greater than x we can remove it we need to remove the left one or the right one right and then by the time we had the card number is equal to x right and then where the current number becomes to zero and then we have our mean our final minimum numbers of operations i mean true that's that will give you the correct answer but it will tle right it's because the uh you know the bfs right so the bfs the complexity for the bfs is the number of the states and for this problem if you want to use the bfs search you know we first we will have like current number the current number right and then we have what we have a left pointer and then we have a right pointer so this three thing will become our the state of the bfs search and this current number itself is 10 to the power of nine right and also the left and the right this combination is also like a n i think 10 to the power of 5 right the length of numbers so i mean this times this one of course it will tle so with the given constraints we cannot use the bfs so then we have to find a better way to do that right um so what's the uh what's the other options what are the options we have other options i mean we can try with minimum numbers right there's a dp or there's what or there is like this maximum number of length or the uh or the sliding window right a sliding window can also give us some minimum word maximum result and you know actually so for you guys in the next time when you guys see this the descriptions you can either remove from the left or from the right most numbers it's it will definitely become a sliding window problem so why is that because you know because after removing the some left most numbers and the right most numbers what's left is it's definitely a what a subs a sub array right we have x here and then we have some x removed from uh on the left side and we have some x removed from the right side so by the time we finish removing those numbers and what's left is definitely a sub array right that's why you know anything that relates to removing from the left most or the rightmost elements is actually a sliding window problem and for all those problems it can always be transformed to a what you know since we are for this problem it's asking us to get the minimum number of numbers operations means the minimum numbers we can remove on both left side and right side actually it i it's identical to what it's identical to get the longest remaining sub array right who's what whose sum is equal to the total minus x which is this one right because as long as we have like as long as we find the max the longest sub array who's like what who's the sum is that it's the is the total minus x then in the end we simply use n minus that length right will give us the answer we're looking for here right i mean so since we have find that like up we find that observations right we can start our coding here so let's get our target first the length is what the length is the let's get our target so we have total the total is the sum of the numbers right and then what's going to be our target so the target is what is the total minus x right and then we'll have like the this uh this sliding window right to get the maximum the longest sub array whose sum is the uh is that this target so the way we're doing it is we're using like sliding window where we have a left equals to zero right and the right equals to i'm sorry right will be we need to end here so length is like the num the length of numbers and now we have a long longest we have let's say max length equals to minus one okay because we will use this minus one to check if we ever find a valid candidate or not so now we have a left pointer and then we have a right pointer right in range of n here so with the sliding window logic you know i've usually we have like a it depends right it depends on some for some problem that's the size of a slight sliding window is fixed and for some problem it's not it means especially for us for this kind of problem you know we're looking for we're using a sliding window to help us find the uh the longest right the longest slide uh sub array so which means that i mean the sliding window it could be starting from zero right that's why you know we have to starting the right from the zero and then for this kind of run uh sum problems we always need to use like the random sum right so and every time when we add the new when we reach the uh a new element we increase the running sum is the this is right element and then what so and then we are updating our sliding window right we're making sure the sliding window is it's not greater than x it's not greater than the target right basically this is what i mean right basically while the target well the running sum right is greater than the target right and the left is not greater than the right okay then we do a running sum minors the nums of left right and then we move the sliding window the left pointer by one so by the time we're finishing this while loop here now all right we're up shrink sliding window to make sure running sum is not greater than target right so now we have a valid sliding window right with this track we check if the running sum is equal to the target because we uh we need to we need this track right because you know it could be the running sum is smaller than the target right and we only need the uh we only need the running sum when it's equal to the target and then we can update our answer which is the maximum length right equals to the maximum right and the maximum length of right minus left plus one right yeah so that i mean and after this sliding window for loop here this max length was towards the uh the maximum length whose target whose sum is the target right and since it's possible it could it's possible that the answer is minus one which means that there is no such sub array whose sum is the target right and then we just said what we just return we only so we only return the n minus the longest the right the max so if it's max sum is not equals to minus one right else minus one yeah i think yeah let's try to run the code here right accept it cool all right so it's accepted all right i mean just to re to recap the logic real quick here you know so first you know whenever you see the leftmost and right most element right remove the leftmost or rightmost element and then this problem can always be converted to find the what the answer for the remaining part which is the uh a sub array and for this problem the uh the sub array we're looking for is the longest sub array whose sum is equal to the target which is the total minus x right and the way we're finding that longitude sub arrays using the is to use uh the two sliding window approach and every time when we add like a at the new location right we uh we update we increase the running sum and then we check if the running sum is greater than x if it is we shrink it okay we shrink it and then we check if the if after shrinking if the uh the running sum is the same it's the same as target right if it is then we update our the maximum length if it's not we simply skip that and in the end we simply we just use this max lens to get our final result yeah and so the time and space complexity right i mean as you guys can see we have a sliding window and for the sliding window the time com complexity is always often right and space complexity is do we have a space complexity no so the space complexity so one cool i think that's it for this problem yeah i believe if you want to solve it directly without tr result without uh transforming it to uh to the longest sub array i think there's also a way to do it but i just find this is the most intuitive way to solve this problem you know cool i hope you guys enjoy watching this video thank you so much guys and stay tuned see you guys soon bye
Minimum Operations to Reduce X to Zero
minimum-swaps-to-arrange-a-binary-grid
You are given an integer array `nums` and an integer `x`. In one operation, you can either remove the leftmost or the rightmost element from the array `nums` and subtract its value from `x`. Note that this **modifies** the array for future operations. Return _the **minimum number** of operations to reduce_ `x` _to **exactly**_ `0` _if it is possible__, otherwise, return_ `-1`. **Example 1:** **Input:** nums = \[1,1,4,2,3\], x = 5 **Output:** 2 **Explanation:** The optimal solution is to remove the last two elements to reduce x to zero. **Example 2:** **Input:** nums = \[5,6,7,8,9\], x = 4 **Output:** -1 **Example 3:** **Input:** nums = \[3,2,20,1,1,3\], x = 10 **Output:** 5 **Explanation:** The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 104` * `1 <= x <= 109`
For each row of the grid calculate the most right 1 in the grid in the array maxRight. To check if there exist answer, sort maxRight and check if maxRight[i] ≤ i for all possible i's. If there exist an answer, simulate the swaps.
Array,Greedy,Matrix
Medium
null
136
hello everyone welcome back and today we are looking at question 136 which is single number so we are given a non empty array of integers it's called nums and every element in this array appears twice except for one and we want to return that single number in other words our array contains one unique value and all other values are duplicated and they want us to implement a solution with linear runtime in other words the time complexity would be a big o of n and we want to use constant space so the space complexity big o of one so looking at example one we see the array nums contains two to one we said the array will contain one unique value in this case it's one and we can see that two is duplicated now in example two we see that nums contains four one two in this case four is the unique value and one is duplicated and two is also duplicated now three contains one number which is one and in this case it's the only number so it's unique so we return one example one we return one it's the unique value in example two four is the unique value in example three one is unique value now usually when i see a question that asks for unique values or that say we have duplicates i immediately think of two things one it's a hash set since the hash set does not allow any duplicate values and number two i think of exclusive or now in this case they want to use constant space so we cannot use a hash set in this case i will use an exclusive or so why is that let me show you and let me give you a quick review of an exclusive or operation here we are in the blackboard and as you can see i have written exclusive or and if you want to know we denote it like this is this means exclusive or so now i have drawn a table with number a and number b and since we are talking about exclusive or it's a bit wise operation means that we will use it with binary numbers what is binary it means we only have 0 and 1 as numbers it's binary okay so now we have two numbers a and b and i have draw a table to find the combinations between them so a can be zero one and b can zero one and this table shows the combinations between these two numbers so i want you to notice that in exclusive or the only way to get the number one in binary is if the two numbers that we apply exclusive r2 are different in other words we can see that one and zero are different so a exclusive or with b will give us a one here and now zero exclusive or with one will give us a one they are different but now look if we say zero exclusive or zero this will be zero and one exclusive or one this will also be a zero as you can see the only way to get a one is if the number a and number b are different so this is the first thing we need to know okay but what if i tell you what is two exclusive or with three it's not binary anymore well it's the same idea you will take this two and convert it to binary and now three in binary is one now we apply the exclusive r to them and now we have binary zero and one are different so the answer would be one xorn with one and one the same so the answer is zero in other words two xored with three will give us zero one but zero one in binary corresponds to one so two x or three equals one now why i am saying this well let me show you something we said that if the two numbers are the same the answer would be zero so what is two x on with two what is 3 x orbital 3 well they should give us 0 because we said if the two numbers are the same the answer would be 0. so let's check 2x or 2. we said 2 in boiner is 1 0. what is the other two it's also 1 0. let's take the xor zero and zero the same the answer is zero one and one the same the answer is also zero as you can see zero okay let's check three is one the other three is one take the exclusive or one and one the same so the answer would be zero one and one the same so the answer is zero as we can see if the two numbers are the same and we take the exclusive or the result would be zero so this is rule number one that i want you to keep in your mind a exclusive or with a will always be zero this is rule number one okay now going into rule number two if i said hey what is three exclusive or with zero or what is two xor with zero what is the answer well let's check if we said three it's one zero it's zero deck exclusive or what is one xord with zero it's one what is one x or zero it's also one it's right here and what is one in binary well it's three focus on this it's three okay what is two xor with zero well two is one zero is zero take the xor zero with zero are the same the answer is zero one and zero are different so the answer is one but what is one and zero in binary well it's two okay so basically rule number two tells you if you x or any number with zero the result would be that number so rule number two says that if a xor was zero the result would be a okay these are extremely important for any bit a manipulation question also note that exclusive or is both commutative and associative okay it's so important so three we have a xor b equals b xord a and now for a xor b xor c equals a x or b x or c these are so important we will use them in the solution this was the review for the xor so now let's look at the question okay so i have wrote an array that has one two one 4 and we can see that 4 is the unique value 1 is duplicated 2 is also duplicated so now how can we find 4 using xor and knowing these 4 properties now we said if we xor the number with itself it will give us zero and if we xor this number with zero we will get the same number now we can use that in the array since they told us that we only have one unique value which is four and all other numbers are duplicated or each number appears twice we know that 1 will appear twice and we know that 2 will appear twice so now looking at this rule a xor a equals 0 we know that 1 xor with 1 will be 0 we know 2 x or with 2 will be 0 and we said anything x or with 0 will be the same so 0 xor with 4 will be 4. so the idea is we want to xor all the numbers in the array so one xor with two xor with one xord with four this will result something but now you might say we have the one here but the other one there but remember this and this xor is both commutative and associative so we can rearrange these numbers to look like this one xor with two x or with four basically you can place the numbers in different places and it will hold true since it's both associative and commutative so now what is one xor with one it's zero and now what is 2 x or with 2 it's 0 what is 0 x or 0 it's 0 and finally what is 0 x or 4 and 0x or 4 is 4. so this is the idea we want to xor all the numbers in the array let's go to lead code and cut the solution out we said we will loop through all the numbers and take the xor so 4 int num inside of nums we will take the xor between all the numbers but we need to start somewhere how can we do that well i will make a variable x so in x equals zero and i will say x equals x xorn with num now why i said x equals zero well zero xor with anything will give us that number so initially when we start here we will say okay x is zero we will say x equals x xorn with num what is zero xor with two it's two so now x equals two and now the process continues oh what is 2x or with two 2x or two is zero now what is zero xor with one is one so at the end just return x so let's run the code let's submit okay so looking at the time and space complexity start with the space complexity we did not use anything um so the space is constant we go of one now time complexity we use the for loop to loop through all the numbers in the array and we xor them together assuming we have n numbers in the array the time complexity would be bing o of n i hope you guys enjoyed the video best of luck to you and see you in the next one
Single Number
single-number
Given a **non-empty** array of integers `nums`, every element appears _twice_ except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space. **Example 1:** **Input:** nums = \[2,2,1\] **Output:** 1 **Example 2:** **Input:** nums = \[4,1,2,1,2\] **Output:** 4 **Example 3:** **Input:** nums = \[1\] **Output:** 1 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-3 * 104 <= nums[i] <= 3 * 104` * Each element in the array appears twice except for one element which appears only once.
null
Array,Bit Manipulation
Easy
137,260,268,287,389
363
hi everyone my name is coaching and today i'm trying to solve the uh august challenge problem the problem is maximum sum of uh rectangle no larger than k so the basically the problem is that given an m cross n matrix uh an integer is k and written the maximum sum of uh rectangle in this matrix such that its sum is no longer than k so it is guaranteed that there will be a rectangle with some no longer than k so directly i am going to the dry iron and then after that i am trying to implement my logic of the coding interpretation so 1 0 minus 2 3 0 minus 2 and 3 what i'll do that uh basically i will take that there is an m plus 1 and the n plus 1 size matrix that means that is one extra uh grid for there that means zero so what will do that uh basically the value has been present there first i will do that one zero one there and then after that will be the from previous one that is 0 and 1 that is the i'm taking there as a prefix sum basically so what will do that what is the prefix sum basically that is also sorry 1 0 1 that is one and two so what is happening that here it is contributing the previous one and there it is contributing the previous one so after that one will do that so that will be the uh adding that will be adding and that will be detecting from there that will be so 1 plus 1 minus 1 then plus of minus 2 that is 1 minus 2 that is minus 1 and then 2 minus 1 and then plus the 3 basically so what is do that minus 2 then there is 3 that is the total uh matrix perfection that is one two three zero one two one minus one and three that is the uh basic total prefix and then after that i am trying to do that first of all i my position up there that will be starting from there and ah and parallely another condition that will be that another uh matrix there and after that will goes to there that goes to there and every time i will checking there uh if from the next matrix and from the uh fast matrix that is the suppose from first case that will be the same and from the second case that will be the uh that one and for the third case that one for the three guess so all the x one x y one i mean that uh x two y two minus when that is same basically there is the x 1 that is x 2 minus 1 and the y 1 so if the value which is the value has been present is it the value is lesser than k or equals to k that will be the maximum value will be taking the result value of the value and the previous one the suppose uh previous one is answer is equals to the then answer and after that i will return the answer basically so basically what happened that first of all i am taking the previous sum basically the order of n cross m and then after that i am taking that one more time so basically order up in uh if i've been taking n cross m into n constant so basically order of n square m square that is the time complexity for it so right now i am trying to implement my logic as a coding interpretation also i am taking the extra space of order n cross m so the space complexity is order of n crossing basically right now i'm trying to implement my logic so what is happening that first of all integer um the sum of k integer n is equals to matrix dot size integer m is equals to matrix zero dot size then integer n plus one m plus one then name set of p sum of zero and size of p sum that will be done there after that i will taking the prefix sum so what will happen that uh hold on for integer i is equals to 1 i is equals to n i plus and for integer j is equals to 1 j less than or equals to m j plus and for there uh what is happening there basically p sum is equals to hold on that is not required to do that first of all fast i'll do that p sum up i up 0 i f 0 okay hold on i have been taking that part i've been taking that part so one of one basically so basically what will do that here is basically uh prefix of i1 basically there is a one basically then after that what will do that uh p sum of i minus one there is the previous one of 1 and plus the basically the matrix value so matrix of i minus of 0 that means that one i minus 1 that is 0 i minus 1 that is 1 minus 1 that is 0 and 0 so that will be adding there i minus 1 and that is 0 so it is for the uh for the every first case basically and then after that i'm trying to implement my logic as the column format for integer j is equals to 1 and j less than or equals to m j plus and for there what is happening that p sum of first of all what is that will be the value so that is basically that is one and one so columns there is down through there that is the round true there so that is p sum of 1 of i that means j basically is equals to p sum of 1 of j minus 1 plus matrix of 0 of j minus 1 basically i am trying to do that uh the mat first row and the first column then after that i am trying to implement my normal p sum so there is the starting uh for the basically there is the row and there is the column so after that what will do that for integer here basically uh why i am taking this one because i have been taking i plus that is r plus one and the j plus one i mean that r plus one that means uh which is the n uh then plus one and the which is the column that is the plus one so that is why i am starting from one basically so i is here two i less than or equals to in i plus and for integer j is equals to 2 j less than or equals to m j plus and from there basically p sum of i of j is equals to p sum of i minus 1 of j from the previous one i have been adding there and i've been adding also the upper one ah there is the upper one that is goes there that is i'm taking the i of j minus 1 and then i will deduct the p sum of the i minus 1 and j minus 1 and then i will adding the matrix value matrix of i minus 1 and j minus 1. then there is everything there now my pre-computing procedure has been now my pre-computing procedure has been now my pre-computing procedure has been completed right now i have been computing through the matrix deduction value basically the integer answer answers will be integer max sorry integer mean well i didn't know that why it is going there so from integer pointer one is equals to starting from there basically from one and pointer one is goes to n and p1 plus and then after that i don't know why it is happening there or it's close to there i didn't know what is happening and for integer of p 2 is equals to i mean that i have been changing the point basically uh q1 basically if i've been taking there q1 of 1 to q1 is equals to i mean that m and q one plus and for their for the second case i've been taking the ending uh pointer uh matrix uh coordinate so that is why for integer p2 is equals to 1 p2 less than or equals to the n p2 plus and for there for integer u2 is equals to not equals to 1 basically there is a starting point up there is a p1 and q2 is basically the q1 and q2 is less than or equal to the m and q2 plus and then after that what is happening that the first i will check that the sum is basically the calculated sum is equals to basically the prefix sum of which is already have been pre-computed there been pre-computed there been pre-computed there so p sum of the uh ending value that is uh p2 and q2 and minus p sum of p 1 minus 1 because that is the uh starting point there so if i've been taking the minus 1 then i will adding that value so p 1 minus 1 and the q 2 because q 2 is the location there q2 and here i've been taking the minus 1 minus and then taking the bracket basically so what is happening that so p sum up so same there that is the p sum of the p2 of the q2 minus 1 and the minus of p sum of same level that is the p1 minus 1 and the q2 minus 1 sorry not q2 there is a p1 minus 1 there is a q1 minus 1 so if calculated sum is lesser than or equals to k in that case i will take the maximum value of there so answer is equals to max of answer and calculated sorry calculated sum there calculated sum and after that i will return the answer so let me check that my logic is correct or not basically taking the lot of time here why is it happening there okay why is it okay allows consecutive bracket and there you want it okay minus there clicking that one p sum up there what why is it happening please sum up minus 1 line number 26 okay i got it forgot it i minus 1 minus j it's given me okay three what it is wrong there hold on it is okay that is because uh i am taking that upper one there is the left one and then after the detecting the diagonal and then adding calculating some there that is the p2 q2 the pointer then the same level pointer minus 1 that is the x coordinate and minus p 2 okay q 1 basically that is the pointer of 1 starting from there and the last one p1 minus one okay let me check there maybe right there in same case i thought here art is accepting for the custom disk so right now i'm trying to submit my code yeah it's got accepted thank you so much you
Max Sum of Rectangle No Larger Than K
max-sum-of-rectangle-no-larger-than-k
Given an `m x n` matrix `matrix` and an integer `k`, return _the max sum of a rectangle in the matrix such that its sum is no larger than_ `k`. It is **guaranteed** that there will be a rectangle with a sum no larger than `k`. **Example 1:** **Input:** matrix = \[\[1,0,1\],\[0,-2,3\]\], k = 2 **Output:** 2 **Explanation:** Because the sum of the blue rectangle \[\[0, 1\], \[-2, 3\]\] is 2, and 2 is the max number no larger than k (k = 2). **Example 2:** **Input:** matrix = \[\[2,2,-1\]\], k = 3 **Output:** 3 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 100` * `-100 <= matrix[i][j] <= 100` * `-105 <= k <= 105` **Follow up:** What if the number of rows is much larger than the number of columns?
null
Array,Binary Search,Dynamic Programming,Matrix,Ordered Set
Hard
null
888
okay so welcome guys so let's solve this uh fair candy swap so alice and bob have candy spare uh different sizes no added size eyes the size of ice bears uh candy but i been can at his house and bear above side stage the size of jay's parliament so basically uh alice have some candies and bubbles on candies since they are friends they would like to exchange one candy bar uh each so they after exchange they both have less than total amount total amounts okay so return an individual array where answer zero is the size of candies bars the alice must exchange and answer y is the size of candy bar the bar must exchange if there are multiple answers they return any order so for example if added side one then bob sides two then they should return one two right so one two means that as return one at least return uh at least exchange one to bob exchange two so it becomes uh so at least become one two bubbles or also one two right so there's totally some three and also at least uh edit size is one two bobsled two three so uh alice can answer one two right so one means that x is change one to about two so uh every sides become one three both sides become two their sum is uh both four okay so uh the simple mathematical question right so let's assume the total sum of about x and the total sum of bob sum is y okay so let's say alice exchange u1 and the bob exchange u2 okay so the total uh will become x minus u1 plus u2 this is for alice and the total above is my one minus u2 plus u1 right so uh simple mass tells you that u1 minus u2 is basically x minus y divided by 2. okay so the problem becomes that find u1 find the u1 in alice and find u2 in bob such that their difference is x minus y divided by two right simple mathematical equation okay so now it's very easy let's divide target to be x minus y divided by two so x is the sum of at is uh sum of bob and therefore u1 in the edits right and therefore u1 minus if i know we check that whether u1 minus the target it's the same as u2 so if you want my targets in the box you know in y then return u1 and u1 minus target okay so yeah so indeed in my code this is called target right so finally you need to return you want u2 so basically you return u1 and the u1 minus target right that's it yeah simple solution okay see you guys in the next video be sure to subscribe to my channel thanks
Fair Candy Swap
mirror-reflection
Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the `ith` box of candy that Alice has and `bobSizes[j]` is the number of candies of the `jth` box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return a_n integer array_ `answer` _where_ `answer[0]` _is the number of candies in the box that Alice must exchange, and_ `answer[1]` _is the number of candies in the box that Bob must exchange_. If there are multiple answers, you may **return any** one of them. It is guaranteed that at least one answer exists. **Example 1:** **Input:** aliceSizes = \[1,1\], bobSizes = \[2,2\] **Output:** \[1,2\] **Example 2:** **Input:** aliceSizes = \[1,2\], bobSizes = \[2,3\] **Output:** \[1,2\] **Example 3:** **Input:** aliceSizes = \[2\], bobSizes = \[1,3\] **Output:** \[2,3\] **Constraints:** * `1 <= aliceSizes.length, bobSizes.length <= 104` * `1 <= aliceSizes[i], bobSizes[j] <= 105` * Alice and Bob have a different total number of candies. * There will be at least one valid answer for the given input.
null
Math,Geometry
Medium
null
377
Hello friends to Jhal Ajay, once again welcome all of you to my YouTube channel Tier-3. There are two more all of you to my YouTube channel Tier-3. There are two more interesting questions to be asked in today's video whose name is Combination Suff and these questions must have been already asked by those people who Martyrdom, Targets, we submit or any change, combination, politics, who's motivation, did all this, that question seems to be exactly zoology, is n't it the same thing in the combination, inside which is the question and also on the point, just subscribe now like in my place. But there are some numbers that are telling me that something is ok, that they have given me some of my targets, some of the targets have been achieved, otherwise this is let's support for many, so they told me how many terminations you can do, how many ways are there that you can achieve it by using these numbers. Achieve the target and adopt these flats. Look, I have completely reframed the question to make it exactly the same, which is a question and reducer named coin change in inches combination points information. This is the one with motivation, that combination is saver. If you turn off the mode, then the infinite supply also increases and every member has one member in this line, you can also use it in these flat bars, it seems that there is no limited supply that if it is used once, it will be used twice. Let's see how to do it basically means we will see the same approach to do it which one is Top Twenty Cricket Shiv Approach So what do I say, initially I came to the market, I am fine, I went to the market, so I have 384 my Courage, there were coins of this type, a door pack of ₹ 1, Courage, there were coins of this type, a door pack of ₹ 1, Courage, there were coins of this type, a door pack of ₹ 1, cooked them and a body of four rupees. So, I have some denomination sequenced members which were already lying in my pocket. Now what did I say, I will have a choice, right, I am the shop keeper first. I will go after this, I have a target, why do I have to do it, if I know that I have seen all the items taken, then what choice do I have? For the first time only three depend on the diet initial stage. Either I go with one, that is, I will give it for ₹ 1. First give me a coin or should I will give it for ₹ 1. First give me a coin or should I will give it for ₹ 1. First give me a coin or should I cheat him. I should give him four rupees. It was 334. I said I will give one rupee. He went ahead and hit George in the pocket. He accepted that the pocket is still not empty because I gave my ₹1. And there are because I gave my ₹1. And there are because I gave my ₹1. And there are many calamities supplied from Norway, there is no problem, again I said only one thing, I will still do one, friend, I will push it, I will lick it, I went again, one would be good, small one rupee coins would be fine. There are also, it will happen soon, I again, now how many rupees did I give him for - now how many rupees did I give him for - now how many rupees did I give him for - two which is ₹ 2, went to him positive, two which is ₹ 2, went to him positive, two which is ₹ 2, went to him positive, then I next again put my hand in the pocket, now again I saw half, I have ever received ₹ 384 on the mail. One two or you, ever received ₹ 384 on the mail. One two or you, ever received ₹ 384 on the mail. One two or you, I gave him vande again then I moved ahead again one two or break the width and till now what time are the denominations here I again closed it like so now need to go ahead from here Is there anyone clear, I think look, I have given him one and a half, one, two, three and 40 on all four bodies. What does this show that Aamir Rat has found a way to give me points? One 0 Easy. This is a way to do this by giving it further, now I need because this is done so now let's do one thing which I did in the last I thought of this but was going to give that I had given one two three but I had to give you So I will say, ' say, ' say, ' Money, four, such things, by any means, these people are finished, now we have taken this ₹ 1 now we have taken this ₹ 1 now we have taken this ₹ 1 coin back from him and now we have asked him to give us how many more rupees at the end of the Abhishad end. We have to pay because look, we have already given ₹ 1, we have already given We have to pay because look, we have already given ₹ 1, we have already given We have to pay because look, we have already given ₹ 1, we have already given two out of four, so now we have given emphasis on the rate, so till now I have stored the method here by tying it to the stage, now after doing the last day, I will see two. As if I gave you two, then you message two, what is zero? Now there was no question of giving any further choice, putting my hands in the pocket again. I have finished my work, so have I found one more way? And Nandoi, this is another way. That money can also be given to the shopkeeper in this way, after that I said, this method is also obscene and OK, now let's explain one more thing, try to give it by cutting it into pieces, but there was talk of giving it for two rupees. If I could not give the remaining rice, then let's give a third, let's finish the work. After coming back down, what did I say, will you still give him the same amount or try? So now when I had given one, then ₹ 3 children were there in my husband. If you when I had given one, then ₹ 3 children were there in my husband. If you when I had given one, then ₹ 3 children were there in my husband. If you give left two, then one rupee is left. Now I will move ahead from this place. After putting it in my pocket, again in three ways, it is 1234 diya like storm, like one diya, 1780 target is reached. If all the money is completed, then one way. And what did I get? 1281 I got it and returned it to the forest for freshener. I took it and gave it two. But if I had given two, it would have done a negative thing, that is, if more money would have been lost, I could not have given even two. I will return the key. Went to come back today, I took it back from here again for 2 coins, as if I took 2 coins back, we had to give him 36 because till now I only asked, he gave only ₹ 1, now he I only asked, he gave only ₹ 1, now he I only asked, he gave only ₹ 1, now he tried by giving 4, now how much was to be given ₹ 3 But tried by giving 4, now how much was to be given ₹ 3 But tried by giving 4, now how much was to be given ₹ 3 But that Jahangir could not cover all four of you, the work was finished, then after doing 101 methods, I returned to the place, now from here, even when I started with this, I had found three methods, these three are similar in work, the second one is the second one. I will do it similarly, if I do it from the phone, then go ahead and then come back, then go forward, then come back again. What is this? It is nothing but the recognition with backtracking. From here, it will break for you. It will come back again, then it will go back, then it will go again, then the option will come. If it comes then this is the tour of the method and such questions can be solved with rich weight. Why is dynamic programming coming because now here if I say time will be mixed it will be more then put DP for that because they have same problem. I don't have a worker but the problem is because from where you look like Vansh and 21 121 this and this both look different but have the total value of each other which is the most disgusting thing we do and fold it so first of all We type in a function that what will it take are the numbers, it will take that target and that's it, now let's do one thing, after coming down here, I asked what is my device and said my wish is that I have collected all the Congress tickets. In some cases and explain, I can use all of them. Level at every level means every time in my pocket, I will give their width to self-reliant teams. in my pocket, I will give their width to self-reliant teams. Point is equal to zero to give oil mid length plus. Now I have to extract what let's find the interior is 1320 i.e. find the interior is 1320 i.e. find the interior is 1320 i.e. How many points i.e. how many ways have we How many points i.e. how many ways have we How many points i.e. how many ways have we experienced in this market - If I market - If I market - If I tried Namaskar in the target and got zero then it means there is no need to go further, answer is straight plus NFC off that such target - not come if garlic It is that such target - not come if garlic It is that such target - not come if garlic It is done, now you will tell me if you are a user and if there is any possibility of giving it. If it is possible then what should I add in the answer? Add zero. Even if Noor Mahal does n't do it, this app will still work. I have written this line for the player only around degrees Celsius - Does it this line for the player only around degrees Celsius - Does it this line for the player only around degrees Celsius - Does it pass? You say Celsius, if that, what would be the methods in this, that is, if the target was not mentioned now, then now that means some more money will be left to be paid and Saif, then what to do in that case, answer plus request in that case. I have kept it in such a way that the dad function will bring me the rest of my work and I have full faith in him that he will give it to me, I don't care about how to give, but now what was my target while giving, what will happen - the name will be set, why - the name will be set, why - the name will be set, why because. Now what did I say, I gave him a coin of ₹ 1, the remaining gave him a coin of ₹ 1, the remaining gave him a coin of ₹ 1, the remaining money, if he tells me in how many ways it can be made, then I will return it to me complete and in the last leela within a fixed period of time. No optimization has been done, now while doing your meditation, tell me that the state has changed and you yourself are going constant only in name, Namaskar, this is a stunt, only one state is changing, which is the target, the state in which the complete change is taking place, then this state. If there is only one status change, then ODI pitch can also work, so what can we do here, we can write if the dentist is changing, target tips can also be done here in the answer and return that This DP that a particular target ignore devotional in that case returns bp.ed a particular case returns bp.ed a particular case returns bp.ed a particular market that it will be passed to me and here I also pass the DP in this function VPN and in its product also in the signature I write I am interior type BP, now let's come to the main function, let's make DJ type the drops to new A B C D. By targeting this picture, what is the length of the update? How much is this target maximum going to 2030, then the address of 101 is created as stitch. Let's take BF Reply to see you in tomorrow's next video thank you guys
Combination Sum IV
combination-sum-iv
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`. The test cases are generated so that the answer can fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[1,2,3\], target = 4 **Output:** 7 **Explanation:** The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. **Example 2:** **Input:** nums = \[9\], target = 3 **Output:** 0 **Constraints:** * `1 <= nums.length <= 200` * `1 <= nums[i] <= 1000` * All the elements of `nums` are **unique**. * `1 <= target <= 1000` **Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
null
Array,Dynamic Programming
Medium
39
1,694
all right welcome to my second um Leo video where I choose a random problem and you join me as I encounter it for the first time and watch me do my best to solve it and then afterwards we look at the um optimal solution and if I had didn't reach that we'll explore the optimal solution and how we could have reached that and what we can learn for next time all right well since this is my second actual leak code um we'll do an easy one again um and we'll pick another random one all right reformat phone number you are given a phone number as a string called number it consists of digits spaces and or dashes you'll like to reformat the phone number in a certain manner firstly remove all spaces and dashes then group the digits from left to right into box of length three Till There are four or fewer digits the final digits are then grouped as follows a single block of two digits a single block of three digits and two blocks of length to each um all right the blocks are then joined by dashes and notice that the reformatting process should never produce any blocks of length one and produce at most two blocks of length two and return the phone number after formatting here we have a number uh you can see first you get rid of the dashes and then you group the first group of digits into three and then since there's three left there a single Button as they also so explain it the second example you start with those get rid of the spaces and the dashes you start with three and then and I start with three and then you notice that there's four digits left so we have to turn them into two blocks of length to all right and similar there the constraints of the numbers at least two digits long and at most 100 y we know that and we know that all right so let's just comment the key information move all spaces and dashes group the digits from left to right into blocks of blength three into uh four or fewer digits if there are two left say s of two left single B of three and if oops if that four left two BLS of two all righty um and joined my dashes all right well now let's just think of a brot force oops Force approach fast um well so first we can just iterate through removing spaces and digits um I can't think of the top of my head if there's a simple way to do that with the string I might just have to make it copy and copy the uh I'm sure that's not the best way but um this is my second we carde so we will improve this proof Force approach after we have a working um a working solution just have to just copy the yeah I feel like that's definitely not the best way to do it um I just write this down for now uh besides the spaces all right and then excuse me um iterate left to right um I every four digits um let me think um not sure how to check but we'll just add checking if it leaves us with four or less of each one each um grouping leads us with four or less it does I'm sure there's a mathematical way to check how many that will be left um we might do that all right um the time complexity of that would be bigger of n to remove the spaces and digits um and then big of in to add the dashes that's just big of n so I mean a Brute Force approach might be all righty um space complexity um then if we're copying strings probably um one I'm not super familiar with the operations you can do on like strings if you can just add one in the middle I'm pretty sure that's still big of in I would do yes because if you have to add a dash um yeah there and a big long you know 96 more digits and you have to move all of them over one you know what I mean so I think that's pretty um now can we improve this SLE or should we just get into coding um what could you improve I'm not sure if you can improve very much except for that little mat part and the yeah well I think we'll just get straight into cting shall we all right so first we just want to remove spes I'm sure there's actually a better way to optimize the time but maybe not removing all the dashes maybe you could keep a dash which groups you the which is part of the dash the group dashing you know what I mean um to set my timer um I'm not sure what the timer is here oh that's starting um well it's been about 10 minutes I can see my recording I just have to go off that anyway remove all spaces and dashes so um ++ um ++ um ++ um if number the dash I mean the parentheses equals a space or I a dash oops want to move it um I don't know I'm not very good with the operations maybe you could do number oh I don't really know but we actually yeah we can't we'll do that oh we'll go to work version First without looking anything up but um I'll just copy it to a new stream um so definitely not the best way to do this but I want to get a working solution without looking anything up because it's only really a small thing it's not going to change the change it too much excuse me for yawning I know it's pretty boring um yeah run the same thing that I had before pretty much is it push does it matter if it's push back that's fine yeah that's fine okay so then that should end up with number copy having no I really need to know that operation though we add dashes in I have to know how to do it B better um I don't think it HS let look looking up it's not the best uh that I need to do this but oh well um where would it be don't know be string no idea um appen is that just at the end I think that does mean an insert there we go and maybe Erase here uh yes this is what we want one of that's inside erase first all right um oh dear me all right sure I'm just Ying 108 why is it oh no I get it so the first par is um 10 wait what um ah that's the one we're looking at that also means that I obviously should be using T here as eraing over the number oops we don't need that it's getting hot in my room but I think it's CU I'm just being dumb um so we got the position so we got race don't know if that's correct if that is um let me that one I think it could be we test it out I just return just to keep it happy so if we run that hopefully it should work oh yes it does well done me having to Google a simple string uh operation not very good but you know just learn something we just learned something together maybe you don't know that I for some reason didn't did not remember that but anyway we've got that so remove all spaces and dashes and then group the digits from left to right into blocks of like three but let's work out how many um elements there should be left in the end so to do this I think that means um you get the remainder after dividing it into groups of four excuse me um so it just modulous good wait hold up oh no oh that's box of three so if you just do in um trailing nums inals number L don't really remember what if I'm doing modulus going to work let's just test make sure test what that gives us return that again hopefully it gives us three for the first EX I think it look like no gives us zero should give us three gives us one or should give us four that gives us two oh that should us to oh no that means I know what I'm doing okay so we get the remainder what if you just divide it I'm just doing random testing now because I don't want to have to resort to Googling anything straight up that gives us two and it shouldn't that gives us two and it shouldn't I'm just try absolutely anything I can't just Google something when it's been 20 minutes that's good oh is something promising we got three no that's wrong and that's wrong let's just do that because might as well try all of these uh H let's just take a second to think how can we get the remainder remaining things maybe we'll come back to that and just do it differently first but we should just do it now what is the remainder is when you divide a big number by a small number so how many times can you split into this number Remain the thing but if you wa it's going to mess up when the r is one there I think no R of one just means it's full I haven't been looking at that I haven't been checking that oops sorry buddy how long do I have to wait let me take some have some water yeah that should be Randa one not three that should be two this must be horrible to watch oh I had it right that with that I had it right the first thing I put just cuz I saw this was one where I assumed it would be like four but that makes no sense it must be one so that's right if none train num sorry about the last two minutes so that must have been very painful to watch but if it's zero um digits final digits it's one there are two digits whoops if it's two there are two fin digits we got there in the end let go there looking for the wrong answer at this whoops all right so now I should also figure out how many blocks we should have oops why am I do that num uh we should work except for when there's four remainder four and then be one to many which I guess we can just change so we've got this is definitely not what you can't really do this sorry in an interview but it's better than nothing when I'm stupid why is it not outputting anything does have to be oh no I'm I was looking at that two yeah that's right there to technically not right but um mess um one it's just add one or is it minus one add one I'm trying to work out this logic so we can use it oops so we can use it later on in our act so two yeah two three yeah three I don't like that I should do num three bucks how many I don't know I don't like it should be three as well if I was going after ouch very sorry everyone has to watch this but you know not good okay two three bcks yes one three book yes 23 bucks oh man I need a way to know what's to do the end all right well anyway Z eyes less than numbers i+ um see I'm a mess today I don't know why I can't already do this try that number be T always forget 14 what are you on about space four I reckon re that's what I meant um not helpful we have a dash every fourth what the heck I'm so confused oh goodness I'm not even sure what mulus freaking does I'm not very good at this there un completely last all right and that's also I'm looking at the thing it's the index it's not the phone number it's the index so one which is two excuse me four Z one two that's not full that's full two Z one two three four five six oh it's minus one so we can start there already rights oh no it's not the index that's coming up oh what am I talking about oh this must be a great video to watch three so after the three Ander it no that's the 0 1 2 3 so cor six0 1 2 three four five that's not three anymore though oh yeah we keep calculating it do all right I'm going to pull my hair out right now I'm struggling with this so much Z one two three and0 one two three Z one two three four why is it like that whatever I'm trying to be too fancy with the mats just none zero if this is really done but hopefully it'll let if it's three then we'll do number inser how to use insert position oh this will be within one which is you know good enough this is probably the worst way anyone's ever tried doing this righty okay I've used it wrong how do I use it does it have to be a Str it why is it done like that what didn't want to add a dash anywhere there why I done that so hung right now so in the first three I don't know why we didn't have it incorrectly even well why didn't why that is a bloody weird I'm just curious what happens if you um well that does work like I was expecting it to work but obviously not maybe that's CL the correct OD oh dare me I'm so not good at this so that splits it into three just yawning and no I'm trying I'm be why can't I freaking do this it's only been 30 minutes I jump up a bridge know what I'm doing maybe something like this who knows who nice um at the would it be four times I obviously not like that silly me outut why does it skip maybe I'm just try anything doesn't seem do one at all I should do one I should there an extra one the Run what the is man let make sure I got the right n three block as well one which is correct that here two oh yeah there me add that many dashes it doesn't have any two that's one so maybe stupid brains not braining whatsoever does that for whatever reason it does that which is correct why is that got ex stream oops you can tell I'm not a very experienced Elite coder oh that's progress as that works and that works for the first part and that seems to work for that part so we split it into the correct number of three blocks now that to oh man it's just no this isn't going to work but I'm just going to try this is going to work H Mary hello Mary nope exence one still why is it that there it done that then was I just forgotten that one let's just do that just so we can see what we're dealing withs oh I'm thinking of wrong thing then be3 should be four I'm not sure why I working if I hav got working I thought this one worked for the first one I changed am I done oh man just copy that so bring it back and just back oh is that it was that it yes that was it right I think I'm thinking of like the maybe it's that maybe no not do not even close but you could do I was trying to do before I'm haing more memories right now oh there's no way this works for all cases absolutely not that's the worst freaking solution I've ever seen again it works but should it work all right let's just go through test case uh a good test we can do the original dashes don't really matter um a long number there if you go that it should end up like that should with three just remember and if we do that it should end up with two Ls of t and that should be oops that should be one l two so I missed that should be two Ls of two that should be one L of two that should be one out of three need to be all I'm not happy with this solution it's the messiest thing I've never seen but it seems to work I hate this I absolutely do not like it how could you improve it or actually we can submit this let see if it's actually right on it oh it's not even closed oh dear me I was hoping it would be right how's that happening why has that happened let just for that so what is that one why is that not light oh did I do the wrong thing did I do the wrong one name didn't look if it was all right so what messes it up is it just that there's two dashes at the is there just a problem with my erase maybe so if we get rid of one of them this start it works right and if we say copy this one and add two at the start what could the problem be seems to only erase the first one oh I understand why this whole bloody thing is it one a double maybe it's one there two on a row freaks out I don't even think that's where the ARs would be two spaces there that's going to mess up judge quicker man yeah it keeps the second space in it why is that because do a your eyes W um well wait copy and paste that well I mean I zero it's not a space or a dash so we leave it B second one same thing leave it b i is one here now I is three I see the three delete it now um I is actually Four so we actually skip five which we don't want so IUS minus is that going to be a little nicer let's freaking go let's go I'm the Champion I'm ging I'm the Champion the champ submit come on let's go beats everyone whoa what the heck look at the dog me you about me let's clean that up there when did we get that we got that oops about 48 407 38 actually you don't think there a better way to do this actually no there's definitely a better way but asically more efficient way and not to be sure okay let's just have some comments to explain what is going on um number of De if there are two two I'm curious to see the proper solutions for this CU this is horrible yeah we don't need that either oh that n wait why can I just have I got I guess besides the final one all right I could have had that in there as well this is a hard horrible set of if stat here um yeah as well put that in there just have that there and this that and that there and this is the worst C I've ever seen um and we insert a dash two digits from the end sure now insert a dash for um one I don't know if that's even bloody correct make sure mess anything up oh I have great so I have to go back and freaking find out what I messed up not good believe this button should be unchanged all right so what did I change my old one I forgot to do that run better run R run all righty that should work as well that's my final freaking solution not very good why was that one better why did that do so well no idea that's weird and I don't actually really get how any let's look at the editorial they don't have one great let's look at the solutions then C++ and most oops C++ and most oops C++ and most oops most lengthy oh that's a bit much um I don't like the solution too confusing oh I see what kind of done not sure if that's the best way to do it oh got F pictures wow pleas kind of confusing me all right so y to start yeah what is mine um big of end space complexity um just the inserting stuff but it's and divided by like three so it's still technically n but that's a beat I think or the size of the numbers in the original stream and yeah I think you can beat that cuz you have to stuff anyway time complexity is it big on N still um y there it's constant that insert is biger of n as well that's big of almost n well big of yes still depends Bigg of n so that's still bigger of n as the guy his so what do this F do digits from the number Final Answer size of the number for each character in the number of it's a digit add it to the temp number and the length is the size of the temp zero I guess that just kind of finds the remainder sort of um if there's more than four left then the answer at the first three eras I think this is super efficient says faster doesn't seem super efficient bit silly could be wrong but doesn't look great efficiency I like mine like M you need to have a genius you can tell from the last hour what you just has been watching that I'm an absolute freaking genius one line shut up y disgusting yeah um oh place that spaces in ENT no I like my solution all right well I think that's it for this video absolutely disgusting you know but I solved it in what almost 50 minutes not much better than the first episode but you know check that out if you want to see me solve my pretty much first of Le C live um you know stay tuned for more if you enjoyed this video uh leave a like and all that comment what your thought any feedback uh subscribe for more you know all the good stuff um yeah leave some feedback if you've got any I'm sure you do probably Dum I am but you know I'm learning might be learning along with me we see yeah leave me feedback about this freaking solution because it's horrible all right thanks for watching see you
Reformat Phone Number
make-sum-divisible-by-p
You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`. You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or fewer digits. The final digits are then grouped as follows: * 2 digits: A single block of length 2. * 3 digits: A single block of length 3. * 4 digits: Two blocks of length 2 each. The blocks are then joined by dashes. Notice that the reformatting process should **never** produce any blocks of length 1 and produce **at most** two blocks of length 2. Return _the phone number after formatting._ **Example 1:** **Input:** number = "1-23-45 6 " **Output:** "123-456 " **Explanation:** The digits are "123456 ". Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123 ". Step 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is "456 ". Joining the blocks gives "123-456 ". **Example 2:** **Input:** number = "123 4-567 " **Output:** "123-45-67 " **Explanation:** The digits are "1234567 ". Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123 ". Step 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are "45 " and "67 ". Joining the blocks gives "123-45-67 ". **Example 3:** **Input:** number = "123 4-5678 " **Output:** "123-456-78 " **Explanation:** The digits are "12345678 ". Step 1: The 1st block is "123 ". Step 2: The 2nd block is "456 ". Step 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is "78 ". Joining the blocks gives "123-456-78 ". **Constraints:** * `2 <= number.length <= 100` * `number` consists of digits and the characters `'-'` and `' '`. * There are at least **two** digits in `number`.
Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost index for every prefix sum % p.
Array,Hash Table,Prefix Sum
Medium
1016
1,822
hello guys welcome back to my channel and today we will be solving a new lead code question that is sign of the product of an array before starting this question guys please do subscribe to the channel hit the like button press the Bell icon button so that you can get the recent updates from the channel so let's read out the question and the question says there is a function sign function X that returns minus 1 if x is positive minus 1 if x is negative 0 if x is equal to 0 you are given integer a random so let protect the product of all the values in Array nums okay return size the sine function product so let's understand this question with the help of example so if you multiply this value we will get a positive number okay so if it is a positive number we have to return one if it is a negative number we have to return minus 1 and if it is if the product is equals to 0 then we have to return 0. so it's quite straightforward uh we will be solving this question with the help of python so let's start solving this question so I will be using if math Dot rod nums is greater than zero then return one alif method dot Broad nums is less than zero then return minus 1. return zero so let's run this code and check out whether we are getting our answer or not okay so we have got our answer here let me understand let me explain it to you that we have created a false condition it was quite simple and straightforward we have created a Final Phase condition where we have viewed use a meth.plot where we have viewed use a meth.plot where we have viewed use a meth.plot function and it says that if a number is greater than 0 written minus 1 if it is less than 1 less than 0 then it minus 1 then returns 0 if it is if both conditions are false let me solve the solve this question with another method as well where I will be saying that a product Rod is equals to 1 and I will be using a loop here so for I in the range nums sorry land nums and I will be multiplying prod because Broad into nums I now I will be saying if prod is greater than one sorry greater zero then return one and if Rod is less than 0 return minus 1 else return 0. so let's run this code now so see both are working here uh let me solve this with multiple test cases here so use multiple use example test cases and try for multiple test cases so that we are assured that we are the our code is working properly so it is working properly we are getting the answer correctly so we have solved this question with two methods first we have used them function and then we have do it we have done it manually so you can do either ways if you have if you do not want to use this function you can use this method or if you do not want to uh if you do not want to use this method both are fine so that's why this is all in the question guys thank you guys for watching the video hope you have liked the video please guys do comment in the comment section if you have any doubt related to the video thank you guys for watching the video see you next time
Sign of the Product of an Array
longest-palindromic-subsequence-ii
There is a function `signFunc(x)` that returns: * `1` if `x` is positive. * `-1` if `x` is negative. * `0` if `x` is equal to `0`. You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`. Return `signFunc(product)`. **Example 1:** **Input:** nums = \[-1,-2,-3,-4,3,2,1\] **Output:** 1 **Explanation:** The product of all values in the array is 144, and signFunc(144) = 1 **Example 2:** **Input:** nums = \[1,5,0,2,-3\] **Output:** 0 **Explanation:** The product of all values in the array is 0, and signFunc(0) = 0 **Example 3:** **Input:** nums = \[-1,1,-1,1,-1\] **Output:** -1 **Explanation:** The product of all values in the array is -1, and signFunc(-1) = -1 **Constraints:** * `1 <= nums.length <= 1000` * `-100 <= nums[i] <= 100`
As with any good dp problem that uses palindromes, try building the palindrome from the edges The prime point is to check that no two adjacent characters are equal, so save the past character while building the palindrome.
String,Dynamic Programming
Medium
516
332
hello everyone welcome back here it's Vanessa and today we have a really exciting problem uh called find a itinerary so this is a political daily challenge and this is a classic graph problem that can be solved using that first search or DFS so if you are a fan of graph Theory or you want to learn more about DFS this is the right place so uh the problem is like this given a list of flight ticket represented a spur of departure and arrival ports from to reconstruct the itinerary in order so all of the tickets belong to a man who is departure from JFK and that's the itinerary must begin with JFK so sounds fun so let's dive into some examples to understand the problem better so if we have some tickets so here is input our ticket list so for example ER uh yeah so uh those five tickets are represented in graph so when we draw the graph so here is a one then uh the second is JFK uh mooc so here uh sf4 s j c and plus Al har s f oh so uh you can see the graph and our output should be uh yeah traversal from the JFK so this is why JFK then mooc then sf4 and S J C so when it's represented as a graph it's quite a trivial to understand so uh now let's switch to coding so I will start coding and then explain so graph will be default digged list and step one so create the graph so first we need to create a graph so for SRC destination sorted tickets reverse true graph Source append destination and itinerary will be list and step two depth first search so we will Implement helper Dev DFS Airport and while graph Airport DFS of graph Airport and itinerary append Airport and step 3 kick start the DFS so DFS from JFK and finally step 4 reverse the itinerary so we need to reverse it and to return itinerary reversed as simple as this so it's really straightforward DFS graph implementation yeah we can run it to verify that it's working so yeah all good and so uh what is the approach so the python code uses a DFS approach and we start by constructing a graph with default addict from python collection model and then we sort the ticket in reverse order to use the building list as a stack and after that we start our DFS from JFK and keep going until there are no more destination to visit from the current air force so finally we return this reversed itinerary and there we have it so the graph represent airports and their possible next stop so DFS function here above the last destination from the current airport list and call itself recursively until there are no more at destination so this ensure we visit each destination in the correct order as well so yeah we can submit it for and since cases to verify all works well yeah so all working perfectly and we beat yeah 86 percent with respect to runtime and also 66 and with respect to memory so now if you're wondering how to solve this problem in other languages like uh go rest C plus and network check out the description below so I added implementation in those languages as well so all right that's it for today I hope you enjoy solving uh this uh problem with miso is classic DFS task quite common on coding interview as well so if you did I give this video a thumbs up and don't forget to subscribe for more coding challenges tutorial machine learning and much more and remember don't just aim to fight the quickest route and aim to expand your coding toolkit so stay motivated keep practicing happy coding and see you next time
Reconstruct Itinerary
reconstruct-itinerary
You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from `"JFK "`, thus, the itinerary must begin with `"JFK "`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. * For example, the itinerary `[ "JFK ", "LGA "]` has a smaller lexical order than `[ "JFK ", "LGB "]`. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. **Example 1:** **Input:** tickets = \[\[ "MUC ", "LHR "\],\[ "JFK ", "MUC "\],\[ "SFO ", "SJC "\],\[ "LHR ", "SFO "\]\] **Output:** \[ "JFK ", "MUC ", "LHR ", "SFO ", "SJC "\] **Example 2:** **Input:** tickets = \[\[ "JFK ", "SFO "\],\[ "JFK ", "ATL "\],\[ "SFO ", "ATL "\],\[ "ATL ", "JFK "\],\[ "ATL ", "SFO "\]\] **Output:** \[ "JFK ", "ATL ", "JFK ", "SFO ", "ATL ", "SFO "\] **Explanation:** Another possible reconstruction is \[ "JFK ", "SFO ", "ATL ", "JFK ", "ATL ", "SFO "\] but it is larger in lexical order. **Constraints:** * `1 <= tickets.length <= 300` * `tickets[i].length == 2` * `fromi.length == 3` * `toi.length == 3` * `fromi` and `toi` consist of uppercase English letters. * `fromi != toi`
null
Depth-First Search,Graph,Eulerian Circuit
Hard
2051,2201
1,762
hello today we'll be doing leeco number 1762 buildings with an ocean view now for this problem we are being given an array of integers which represents heights of buildings in a line and to the right of all these buildings there is an ocean and what we want to do is find all the buildings that have an ocean view which means that all the buildings to its right have to be shorter and what we want to return is an array with all the index of the buildings that do have an ocean view and we want that to be sorted in an increasing order so for the first example i've drew it to the right and so we can see that a one will have an ocean view because there well there is no buildings in front of it and three will have a building this building which with a height of three will have an ocean view because the only building front of it is one which is shorter and now this building has a height of two but it won't have an ocean view because it is being blocked by this building with a taller height and this building over here with a height of four will have an ocean view because all the buildings in front of it are shorter so as we can see here we return the list of index and it is sorted in ascending order and now here for the example we have just a array of heights that are just in decreasing order and we know that this would all have an ocean view because this means that all the buildings in front of it are going to be shorter now this last one the only building with an ocean view is this last building with the height of four and this is because all the buildings that come after it are shorter than this building so only this building will have an ocean view now how can we solve this problem one way would be to start at each building and we would just check if all the buildings ahead of it are shorter so say we start at four we would check all the buildings in front and we can see that they're all short uh and we start at two and then we would see that okay there's the three which is larger so we would not include this in the final array now uh this would be a nested for loop implementation so that would end up giving us o of n square time complexity but there is a way that we can do this with linear time now how do we do this linear time well what we can do is have a maximum height variable to track what our maximum height is at any given point of the array so we do is start at the end and we would see if uh the building height is greater than the max height or not and we know that if it's greater than and then there are no buildings in front of it that could block its uh ocean view so we would then add that to our resulting array of indices so starting at 1 we would see that this is greater than the max height and so we would both update our max height variable and we would add that index to a resulting array and then we would move on to the next building and we would see that uh this height which is the three is larger than our current max height so we would update it and add it to our resulting array now we move on to two is not greater than our current max height and so we would not do anything for this building we would not update our variable and we would not uh add the added to our resulting array and now we move on to this building which has a height of 4 and this is greater than our current height so we would both again update that variable and add the index to our resulting array and what we would do in the end is just reverse this array so that it would be in increasing order now uh this uh algorithm has an o of n runtime because we're only traversing through the array once and it would also give us o of one space excluding that uh return array all right so on to the coding solution as i mentioned before we will have a variable to keep track of the max height and also of course that array of the resulting indices and now all we want to do is iterate backwards in the array and uh we do want to start um one before the length or else we'll be out of bounds and because uh this next element is exclusive in python we would put it at negative one because we want to go all the way to the end and we will be going backwards so all we want to do is compare if our current height is greater than the current max height and if it is we will both append this index to the resulting array and update our max height and in the end we will just return that array of indices but reversed since we do want it in the ascending order and this is the end of the algorithm so we will go ahead and run this so i realize i forgot to add the s for the heights in these but i will run this now and as you can see this solution gives us pretty good runtime and memory usage so if you like this video please like and subscribe to this channel and if you have any questions please let me know in the comments below bye
Buildings With an Ocean View
furthest-building-you-can-reach
There are `n` buildings in a line. You are given an integer array `heights` of size `n` that represents the heights of the buildings in the line. The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a **smaller** height. Return a list of indices **(0-indexed)** of buildings that have an ocean view, sorted in increasing order. **Example 1:** **Input:** heights = \[4,2,3,1\] **Output:** \[0,2,3\] **Explanation:** Building 1 (0-indexed) does not have an ocean view because building 2 is taller. **Example 2:** **Input:** heights = \[4,3,2,1\] **Output:** \[0,1,2,3\] **Explanation:** All the buildings have an ocean view. **Example 3:** **Input:** heights = \[1,3,2,4\] **Output:** \[3\] **Explanation:** Only building 3 has an ocean view. **Constraints:** * `1 <= heights.length <= 105` * `1 <= heights[i] <= 109`
Assume the problem is to check whether you can reach the last building or not. You'll have to do a set of jumps, and choose for each one whether to do it using a ladder or bricks. It's always optimal to use ladders in the largest jumps. Iterate on the buildings, maintaining the largest r jumps and the sum of the remaining ones so far, and stop whenever this sum exceeds b.
Array,Greedy,Heap (Priority Queue)
Medium
null
1,796
let's solve problem 1796 second largest digit in a string so given an alpha numeric string is return the second largest numerical digit that appears in s or minus1 if it does not exist an alpha numeric string is a string consisting of lowercase English letters and digits so they are saying they're giving a string of letters and numbers in it and you need to return the second largest number simple what am I going to do is I'm going to go from left to right each character I'm going to check if the character is a number if it is a number I'll store it in I'll compare it to the greatest number I have so far and if it is bigger than the biggest number then I'll update it else I'll check if it is bigger than the second largest number that I have if it is greater than second largest number I'll update it else I'll just move on so let's see how to do that in code so I'll first of all create a set of s okay it will basically remove all the duplicates and give me an array or a list of uh all the unique characters and S then I'll maintain second and first I'll maintain these variables to store the second largest number and the first largest number and the largest number okay this is where I'll compare I'm setting it to minus one because as in when I get a bigger number I'll update it okay if I do not find any I this will return minus one as it is so let's go through for CNS I'm going character by character from left to right if the character is numeric which is it's a number then it will go into the F block and convert that string it's still a string it's a number but it's still in string uh data type so I'll convert that into an integer data type so that I can do greater than or less than operations on it then I'll check if it is greater than my greatest number that I have so far if it is greater than that I'll update it I'll update first with C I'll update my greatest with c and the second greatest with the first I'll move first to second position and the C would become the new first else if C is less than first but is greater than second in that case I'll update just the second one so I found character Which is less than the first one but is still greater than the second one so I'll update the second one with the current character and then I'll finally after this for Loop is complete I'll return that character let's run in this it worked for both the test cases let's submit and see and that worked in 8 milliseconds beats 100% of users with python so beats 100% of users with python so beats 100% of users with python so that's the best solution we have got
Second Largest Digit in a String
correct-a-binary-tree
Given an alphanumeric string `s`, return _the **second largest** numerical digit that appears in_ `s`_, or_ `-1` _if it does not exist_. An **alphanumeric** string is a string consisting of lowercase English letters and digits. **Example 1:** **Input:** s = "dfa12321afd " **Output:** 2 **Explanation:** The digits that appear in s are \[1, 2, 3\]. The second largest digit is 2. **Example 2:** **Input:** s = "abc1111 " **Output:** -1 **Explanation:** The digits that appear in s are \[1\]. There is no second largest digit. **Constraints:** * `1 <= s.length <= 500` * `s` consists of only lowercase English letters and/or digits.
If you traverse the tree from right to left, the invalid node will point to a node that has already been visited.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
114,766
1,091
Everyone welcome back to my YouTube channel, so today we are going to do the shortest lesson in a boundary matrix, it is a very medium level question but the meaning is something very special. No, if you know how to do fast first search concept then no in the question. Not going to tell anything quickly, it is a very easy question, you will have to do one more cross and key binary metric Clear text meaning what is the meaning between them, tell the text from zero to the index of n - 1 and -1, meaning between them, tell the text from zero to the index of n - 1 and -1, meaning between them, tell the text from zero to the index of n - 1 and -1, okay zero we People can walk on this cell in which if there is zero or one then they cannot walk in the cell. Okay and the adjacent cells of D path are A directional connect one directional so what does it mean that the one path is A can move in its RTO direction. It means that if we come here, then tell me, if we are here, then we can go here also means there is freedom to move in the direction, okay something There are questions but here there is an option of direction. Okay, so what D length of D number of social length has to be told actually, so see here we are at zero. Okay, if there was one here, then what would happen. One would mean that we We cannot move from here because we need zero to move and to reach there should also be zero, so this is our condition that there should be zero while walking and also zero should be the starting and ending point. But it should be zero, now the rest is simple for us, we are zero here, if we reach here then how much is the length, if we visited here then how much is the length, you and I do not walk here. Because there is a forest here, we cannot walk on the forest because which will be the widgetized text in which zero will come, okay, so its length is done, now let's see here, now this is ours, we are here, okay but zero, so From zero, where can we go? Here, here too, it is okay, but now we have gone in eight of these directions, then we will check, but which is the valid direction, what will be the validation here? So all this is out of grid, we cannot go there even in the out upgrade and here if we go down, it will go to one A, so there is no use of life here because of this one should not come near us. Even one should not come near us, so what happened here we will make a move, this side is fine, here there was only option, so we are moving here, okay now when we have made a move here, then we have options. When we move, we will make it like this, now we do n't want to visit it again. Okay, brother, this part of ours has already been visited, so band it so that we don't want to visit it again. What will we do now? People will check from here, okay, so what will happen now, we are already visiting so this account will not be there, this is one here, this also will not be counted, there is a band here, this is also not there, we can walk here If yes, we can walk here, then what will happen to us now, we will have two options, either walk here or walk here, okay, so there was distance from you till here, so where did we reach on three, we reached here and we reached here, okay here. But there will be two options at three distances, two options, there will be two options at three distances, now there will be options at two distances, now on this one, if we go with this, it is okay, then we did not go here because the visit has been done, here everything is out of grid, here we are. We can reach here, okay, we can go here from here, okay, so at four distance, we reached here, okay, but now we came from here, so now we will check with this, so what will happen here, this here this is already visited, this also Biscuits are done here, we are out of bread, so only the one below and below will reach here, so we reached last, then our answer came, how did the fourth lesson happen, went here, now let's see the last one, then I will also explain the above to you through the diagram so now here we have this grate and this is our starting point so its mines one is A and the other one is how can we be in the corner if we want to finish quickly. If there is a forest here, then when we cannot reach any other place, then the answer here will be -1, answer here will be -1, answer here will be -1, then you can write what are these two corners, okay, so let us understand this question from the diagram. So, let 's first have what happened at this point, 's first have what happened at this point, 's first have what happened at this point, okay, at this point, what is its index, I have become its index, I am late, zero is fine and I have also become late, from zero 12 to eight directions, either brother, go this way. Jo yato bhai idhaar chale jo yato idhaar chale jo yahi idhaar chale jo tumara index kya ho gaya Okay, so this is our answer will not be calculated, so we made it closed, now we went to the upper one, what will be the index of the upper one, then minus one, so this is also ours, because this is also out of grid here. We went to the one above, this is also our off grid. We went to the one here, this is also our out of grid. Okay, now we have the next one, what's the next one? Next, we got here. Okay, so here is zero one. So here is this zero. The value is okay, so this can be our one valid. From here we can reach the text. Okay, so we will keep it for further. Okay, now what happened next, this one is one value in one, so this is also left. It is done because here one A became great, one in our lesson can never be A, they have said this, so we will count this one too and if the next one also became this great then this one will also not be counted. Okay, so these two will count. And then we reach the next 1 - 1 This one here, the And then we reach the next 1 - 1 This one here, the And then we reach the next 1 - 1 This one here, the value that comes here is minus one, this one is also out of grid, so this is how they all collected, now we only have one option, baby, exactly one option, what baby is this? Zero one is ok so what will be our distance at this time current distance here you are ok you are our distance till here ok now what was the next option we had ok And now who are we? Okay on this one, so when we reach this one, what will we do now? We will replace each one that we visit with one so that we do n't have to count it again. Okay, now we have reached this Odia. Now from here too we will Pass aath ho direction hai yeh Okay, there are eight directions, okay, so what will we do now, brother, all this will be neglected, this has already been stated, all this has gone out of grid, the bottom two are already If these accounts are created, we cannot use them, so what children do we have? We have two options from this position, sir, one is 02, this one is gone, okay, so now we have visited, okay, so this is what we have done. Visited, okay, we reached here, okay, so we reached here, now one more thing, first we will band this, okay, we will band that first, now we reached here, now here, reached here, now we went to this first okay. Leave aside that previous point for a minute, we have this option first, let me do this so that you can understand what happened to the distance, it is okay here because there will be tax here, this one too has been divided into three parts, okay now. Let's move on this, okay, up and down, it has only one option, okay, this option of moving down in one direction is okay, so we went to one, okay, now this is complete. Okay and now we will look at it could have gone up but it could have gone down, so what happened to it when it came down and what was the distance when we reached here What is the distance on this one 24 The answer to this is A Okay, so this is our over which will take some effort in making the diagram. If you like it, please like the video and share it. Whatever you like, okay, I will do 01 raid with it in a minute. What is the distance here? Hui one here, what was the distance? You were at this position, what was the distance? So this is our method, so why am I taking it now, why what type will it be? Why should I put cells in it? Okay, if we have to put cells in wait, then there is one in it. Second gender, what will depend on the second one, the pen is okay, so why do we make this Before the corner, I have to tell you, brother, first the distance, what is its name, the first element is this, start from here. Okay, so this is why we will give this first, okay why will I give this first, we are starting from 00, so in K, we will give that index first, okay, what will be the element, zero pen, okay? Now what will happen, now we will run a loop until all the elements are finished, like this 000, so if we add that value in One is ok then zero sorry zero minus one will be here one minus one 10 ok so now like support that if we go right on one in this direction then we will reach here so now if we add this value on any index then I will know about its auto direction, so we have put this in the possible directions. The dot size is fine. Now how many times do we have to move as long as there are elements in K. I have to move that many times, so as long as the size is This note is equal to zero till then it has to run, I am fine, what is the size now, what is one, okay, so how many times will this look of ours run once, okay, now it has this value, now its i and the index which we get. Okay, so what do we call it, current i equal, why do you take it by the name of current index and why do we remove that element, whatever we travel, even if we remove it will remove it. Will give us the integer inside it, why I, what is G type, I, why I, what is G type, first in, first out, so what have we put before, it will remove the zero one, okay now it has removed the zero one, now we will see. Is this valid or not? Is this current index valid or not? So now we will see the private bullion is this valid cell which is taking what is the interior taking the index of the index is telling and great take. And when will be our invalid sale, then we will put zero in its value, I am writing this index so that it can be easier to understand, okay, if you understand this, then here we have told that brother, there is a valid sale here. But right now we are here, which means it will check this cell only, so it is not a valid index and it is also being valid for us because there are zeros from above inside the grid. Now what will we do? Let me wait here for a minute and tell you. I am Rohit, tomorrow you are current index zero the element will play eight times. Okay, whatever element we are visiting in the great, we are bandaging its value also, otherwise then it will move ahead. It is okay if it is not repeated again, so what was it for us, the pen is equal, now what is this for us, the size will have to change, it is okay to visit every time and return it to us in the last, here I will do one more thing, now we have done that. Direction to take, how much distance have I become, am I late, then it means when I have filled the first element, right distance. Now when we will check the valid cell, we will also check that the story has not reached the ending exactly. Our row is N - 1 and our pen is also N - 1. If it is - 1 and our pen is also N - 1. If it is - 1 and our pen is also N - 1. If it is so then brother, just return the distance as far as you have walked to reach there. Return the distance. I would have tried it once and then you will see it again. I will explain the diagram to him OK Here you will have to add the return statement. If from there it does not return here it will never reach here and on -1 then add it. I never reach here and on -1 then add it. I submit the last one return and then I see that it has been passed. So let me explain to you a little according to the diagram. Yes, here why I will be those elements, what possible distances will be our cells, why I will be that distance. Okay, so what did we do initially, why this one is the only cell lying, zero, okay, possible directions. You know, we have given directions, meaning if we are on this cell, then to know its RTO directions, we have given possible directions. It has been done, okay, every cell, some random cell will appear and this value will be added to it, then you will know the index of the cells of the direction. Okay, and the current index has been taken as zero, then we will first check why this note. It is not empty, okay, and what will be the size of K, it is done here, okay, what will we do now, why what is the size of K, it is one, so one size will do once, okay, so from K, we will get the value which we have given as zero. Zero has been entered, we will take out this value, okay and then we will check that this is a valid cell, yes, it is valid because it is here and it is zero and it is out of the grid, otherwise this is a valid cell, okay. We will check whether this is our last sale or not and is not equal to -1 then this is our not equal to -1 then this is our not equal to -1 then this is our last sale otherwise this distance is not going to return to us also what should we do now because now we have counted it sir Okay, what we did is we looked at the auto directions of this cell. Okay, now why do we have 00? Okay, now why do we have what will be the data of auto directions of this cell, meaning that this is the whole of this. So full of his auto directions, why did I come, how many values ​​were there, 1234 78 value, ok so how many values ​​were there, 1234 78 value, ok so how many values ​​were there, 1234 78 value, ok so these guys, what was our size, what was his time, zero, so now these conditions are satisfied, then he took us out from here that brother, if he is KMT, then he has time. Why I was one, he took it out but then later we also gave eight pulses, why tell me the size, okay, so now what is this, we have reached the distance, you are okay, distance, you are the first element, this one is this mill. Brother, is it a valid sale, did he ask when is it a valid sale? I am not out of the grid, I am the one who has reached this sale again. Asked brother, is it a valid sale? Brother, is it not a valid sale? Then he added one more size. Asked him, brother, where is the valid sale? Brother, I am not a valid sale. I have removed it. Asked him, brother, I am not the brother of valid se lo, I am not a valid sale. First, I am late to remove it. Okay, ask him brother, what happened to the one from valid se lo. Asked this, there is no loan from valid, I am out of great, so this is also there, so now our size is decreasing, how many children, one child is this, why now we have only one element and here the size is one is not equal to you. Zero, take out its index, then take out its rock and asked him, brother, take it from the valid one, then he said brother, I am a valid cell, then this is what happened here, okay, then he said brother, we are there, so I am a valid cell, sorry, I am saying this, I am So he asked, brother, you are not the last element, at all, I am not the last element, so he said, brother, write yourself wasted, why put it in me, okay, then what did he do here, he banded it and Rest of the elements are included in the why of auto direction. Okay, here I have shown only two but here 8 elements must have been included in the why. Okay, why are the eight directional elements included in the why? Okay, so the 8x ones. Okay, now why now here the size has reduced by one more, now zero child, so here this condition has been satisfied, the condition has to be done, brother, I have eight elements, so he said, okay, now whatever elements you have. When you visit, there will be elements reached at a distance of three, only then people have increased the distance here, the correct size is eight, so first we take the mother that when we went to the invite element, then it bypassed 6, six from here, so you are fine. Now you have gone here, zero, you are zero, you have come to that one, okay which one, but this one, okay? He asked, then he asked, brother, am I valid, he said, brother, I am valid, and okay, he said okay brother, so he asked plainly. That brother, can you grid the last elements, she said, I am not the last element, then she said, okay, brother, if you are not the last element, then you make yourself widgetized, okay, you make yourself widgetized, she said, ok. Hey brother, I have visited myself and brother, you put the elements around you in my why, then he has put these elements of auto direction in his why, how many elements will work in the why, eight, okay, now what is the size here? Size now there were two elements children, first now what will be the size one element child exactly one element went to which child is this one then asked him what are you brother he said brother I am valid then asked him brother you are the last element and the grid. He said, no brother, I am not the last element. We are talking about this element. He said, I am not the last element. It is great. So he said, brother, take yourself as a guest, these are the elements of right direction, those are the elements of your auto directions. Put it in my why, she said, okay, why do you take my direction, now 16 elements have gone into why, okay, 16 elements, now why will I do, and along with that, we have given the size, what was the first size, there was one child, then the last one is this one. When the last elementary visit is done, then the size should become zero. Okay, now how many elements have come in K? Why did I come? Brother, why don't you know? What is the size of his? Now what is his? Brother, 16 is okay, so brother, the distance is now as many as 16. If the elements are also valid then they will represent the tax distance. Okay, so our distance tax is done, so he almost ignored all the meanings, okay, but when this one came to the sale, he asked, brother, are the elements valid? He said no, yes, I am valid, then he said, brother, are you N - the last am valid, then he said, brother, are you N - the last am valid, then he said, brother, are you N - the last element, he said, brother, I am the last element, so he made the return distance, okay, so then our answer here is that brother, if we made it a valid element, then our answer is complete. Once it's done, it was complete in this way. If you liked it, please like the video. The video is a bit long but I will try to make it shorter in the future, but for now, I can do this much. Okay, so thank you. Subscribe. Okay. And I will give the link of this submission in the description and you can also see it from get up with the diagram so thank you so match please like share and subscribe
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
119
hey guys welcome back to another video and today we're going to be solving the lead code question pascal's triangle 2. so in this question we're going to be given a non-negative we're going to be given a non-negative we're going to be given a non-negative index so let's say we're given the index 0. so we need to return whatever is at the zeroth row of a pascal's triangle so in this case would return the number one let's say we're given the number three so we'd return the third row so zero one two three so it'd return one three one so you can look at this example here input three output one three one so this question is very math based and in order to get the most optimal solution we need to understand the formula behind it so let's take a look at what that actually is all right so let's just take a quick look at what a pascal's triangle actually is so this is what it looks like and in the beginning so this is going to be our zeroth row and this is going to be our first row and if you notice the first elements of each row no matter what are always going to be one and the last elements are also always going to be one okay so now once you go to our second row we have one two and one so how do we get that so the first one is always going to be one the last is also going to be one and for the one over here we add this element here and this element here so we add one plus one and we get the number two so let's look at our third row real quick so the first is one last one is one and how do we get the number three and that's nothing else but adding this over here and this over here so 1 plus 2 equals 3 and for this 3 we add this 2 and we add this 1. so again we get 1 plus 2 3. so that's how a pascal's triangle looks like and what is the purpose of a pascal's triangle and the answer is you use a pascal's triangle in order to perform binary expansion these are going to be the coefficients and if you know how binary expansion works this can also be represented using the ncr format so you might have seen it been written like this or some people write it like this or sometimes usually it's written like this so you have n over here and you have r over here so let's just look at what does this actually mean and how can and how does this correspond to our pascal's triangle so let's just look at how do people represent the ncr format so on top you have the n value and over here you write the r value okay and the formula for this is so we're going to first find n factorial so all n factorial is we're going to do n multiplied by n minus 1 multiplied by n minus 2 and so on and so forth and we're going to divide that by r factorial right multiplied by n minus r factorial so this over here is the formula for calculating ncr so let's just take a quick look at it so let's say you have this value over here 2c 0. so i'm just going to write this over here so we have 2 c 0 and let's just plug it into our formula so you have 2 factorial divided by zero factorial multiplied by two minus zero factorial so how does this look like so two factorial is two multiplied by one zero factorial has a value of one and we're going to multiply that by 2 factorial which is again 2 multiplied by 1. and in other words this is just 2 divided by 2. so 2 by 2 which equals to 1. so over here you can notice that everything on the left so ncr where r has a value of zero is always going to equal to the value of one so that also makes sense if you look at this everything on the left is one over here as well everything is one now similarly on the right hand side when you have ncr and the n value is equal to the r value in that case you also get a value of one so similarly all of these values are one so now that you understand the concept i'm sure you might be thinking that we're going to be using that to solve our question and we could so we could first do n of 4 c 0 4 c 1 4 c 2 and so on and so forth but the problem is that we need to do so a lot of computations at the same time and that's actually going to be oh it's going to take up a lot of time so a lot easier and better solution is we're going to use the ncr minus once value use that value in order to find the value of ncr so what i mean by that in other words is to find let's say 4c1 we're going to be using the value of 4c0 and this is actually a better solution because we know that in the beginning our value is always going to be one so we can use that in order to find the next element so what we need to do in order to be able to do that we need to find some sort of relationship between ncr and ncr minus one so the current element and the previous element and in order to find the relationship what we're going to do is we're going to take ncr and divide that by ncr minus one so i'm just going to show you the proof of this real quickly so uh over here i'm going to have ncr and i'll just write it so n factorial divided by r factorial multiplied by n minus r factorial simple and then we have ncr minus 1. and to write that we're going to have n factorial divided by r minus 1 factorial and multiplied by n minus r minus 1. so make sure look how i'm writing it in brackets is because when you simplify this it's going to actually end up being n minus r plus 1 factorial i was making this mistake earlier so yeah make sure of that okay so now we have this and now we're going to divide them so when you're dividing them it's just the same as taking ncr and multiplying it with the inverse of this if you don't know what inverse is always you take the numerator and put it in the denominator take the denominator and put it in the numerator pretty simple so i'm just going to write this real quick and show you how it looks like okay so we have this over here so this is going to be our division so let's try to simplify it as much as possible the first thing right off the bat we have n factorial over here and we have n factorial here so we can cross that off now we can actually simplify it further more let's just go uh element by element so over here we have r factorial i'm just going to cross it off for now it can also be written as r multiplied by r minus 1 factorial pretty simple and if you notice over here let's just go to this equation we already have r minus 1 factorial so we're going to cross this off and we're also going to cross out the r minus 1 factorial here so far we're left out with r and similarly now what we're going to do is we're going to try to break this part down further more so because of lack of space i'm going to be writing this over here i know it's a little bit confusing but yeah sorry so this is the same as writing n minus r plus 1 multiplied by n minus r plus 1 minus 1 right so n minus r plus 1 minus 1 is the same as n minus r so n minus r factorial again this is the numerator i'm not writing it because of lack of space so now let's just cross it out further more so over here we have n minus r factorial we can cross that out and over here in the numerator we also have n minus r factorial so this over here is our simplified version let me just write it so that it looks a lot easier to understand so after doing our formula or proof this is what we end up with ncr divided by ncr minus 1 is equal to n minus r plus 1 divided by r so now what we're going to do is we're just going to rearrange our equation a bit so in other words we're going to have ncr is equal to ncr minus 1 so this is the value of the previous element multiplied by n minus r plus 1 by r so this is the formula that we're going to be using and if you want to see how it works just put it into one of these numbers over here and you can test it out for yourself and it should work so this is the formula we're going to be using so just take a quick look at it and now we're going to implement it in code so again uh if you don't understand anything ask me down in the comments because i truly believe that once you understand the theory part of this the code itself is the easy part so what we're going to do is we're going to start off by calling a variable called row and this is what is going to hold all of the items of our row and we're going to start off by giving it our very first value and we know that no matter what row we are at the first value is going to be 1. so we're going to start off with giving it the value 1. so now we're going to iterate through the values and we're going to start off with the value one and we're going to go all the way up to the ending so row index plus one and the reason we're doing plus one here is because by just doing row index we're going to go up to row index but when we do row index plus one we're going to include that row index okay so now what we need to do is we need to find out the value of element x so in this case we already have the zeroth element so let's find what the value of the first element is going to be so i'll try to put up the function over here somewhere and we're just going to follow that function so first we want to give it the value of ncr minus 1 right so we want to give it the value of ncr minus 1. so the previous element and that's always going to be so that value is going to be rho x minus one so in the beginning for the first index we're going to go to one minus one which is the zeroth index so this is going to be the value of ncr minus one and now we're going to multiply it with the value that we had before which is our we're going to multiply with the value of n minus the current index we're on plus 1. so in this case the n is going to be row index right minus x which we get from over here and plus one since such as part of the function and after we do that we're going to divide it with the value of x so we're going to do integer division divided by x and now what we're going to do is we're going to add this to our row so we're going to append this to our row and that should be it so we're going to go through this function and at the ending of it we're going to return our row and let's see if this works so submit and as you can see our solution did get accepted and finally do let me know if you have any questions and i think this is the most optimum solution but let me know if you have a better solution and thanks a lot for watching guys and do let me know what you thought about the video thank you
Pascal's Triangle II
pascals-triangle-ii
Given an integer `rowIndex`, return the `rowIndexth` (**0-indexed**) row of the **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** rowIndex = 3 **Output:** \[1,3,3,1\] **Example 2:** **Input:** rowIndex = 0 **Output:** \[1\] **Example 3:** **Input:** rowIndex = 1 **Output:** \[1,1\] **Constraints:** * `0 <= rowIndex <= 33` **Follow up:** Could you optimize your algorithm to use only `O(rowIndex)` extra space?
null
Array,Dynamic Programming
Easy
118,2324
905
hey guys welcome back to another video and today we're going to be solving the lika question sort array by parity all right so we're given an area a of non-negative integers and we area a of non-negative integers and we area a of non-negative integers and we return an area consisting of all the even elements of a followed by all the odd elements of a you may return any answer array that satisfies this condition all right so for example we have this area over three one two four and our first task is to identify which one of these numbers are odd and which ones are even well three is odd one is odd two is even and four is also even and what we do is we need to rearrange it in such a way that all the even numbers come first and then the odd numbers so we can have 2 4 1 3 or we can have 4 2 1 3 or we can have uh there's other combinations like 2 4 1 3 or we could yeah so there's three different combinations that we have and all that these combinations need to follow is the fact that the even numbers come first followed by the odd numbers so those are the only conditions that we need to follow and let's see how we can do this so there's several ways that we could solve this question and what we want to do is we want to try to find the best solution and the best solution would be one where we do everything in constant space so we're doing all the operations in place and as for time we want to iterate through everything a minimum or a maximum of one time so we don't want to iterate through a thing through a number more than one time so in order to do that the best thing that we could do is use a two pointer method and how this is gonna work is we're gonna have a pointer starting from the zeroth index and we're also going to have a pointer starting at the ending so the last the very last element and what we're going to do is if whatever is on the left right so in the beginning if that is odd and whatever is on the right is even and in that case we're going to swap those two if that is not the case we're going to keep moving our left pointer until we find something which is odd and we're going to keep moving our right pointer until we find something which is even and when that happens we're going to make a swap and by doing that what's going to happen is everything to the left is going to stay even and everything to the right is going to be odd so real quickly let's see how that looks like in code all right so we're going to start off by defining our two pointers so i'll call these pointers left and right and left is going to be to the pointer on the left which is well it's going to start at the zero with index so 0 and the right pointer is going to start at the right most index and to get that all we can do is we can find the length of our array and we can subtract it by one so that's going to give us uh the last index so now we're going to go inside of a while loop and we're going to stay inside of this while loop until the left value is less than our right value and when that's not the case we're going to get out of our while loop and we're just going to return whatever we have okay so now over here we're going to go into two more while loops well the first while loop is to check whether the leftmost element is odd so if the leftmost element is even right then in that case we're going to keep iterating through it until we find an odd value so let's first do that for our left so while and we need to go to our area and we need to go to whatever is at the left index okay so if that value mod 2 is equal to 0 then in that case it means that it's even and we also need to check whether left is left and right so in that case we're going to keep adding so we're going to keep moving our left pointer to the right by one so left plus equals one okay so we're going to keep moving our pointer until we reach a point where we found an odd number and we're going to do the same for the right pointer but instead for our right pointer we're going to move it to the left until we find an even number so again we're going to do while a go to the right index mod 2 is equal to 1 since odd and then and left less than right same conditions and over here if that's the case we're going to decrease right by one and we're going to get out of this while loop once we find an even number so if we go out of these two while loops we're going to be at a point where the leftmost number and the rightmost number need to be swapped so that's what we're going to do over here we're going to take our array at the left and we're going to swap that with the area on the right so it's equal to area right and similarly when you do for array on the right swap that with that of the left so area right is equal to whatever is at the left index okay so this is basically swapping the two elements and we're going to keep going inside of this while loop until this condition becomes false and once that happens we're just going to return our array as it is since we did everything in place so let's submit this and let's see what happens and as you can see our submission did get accepted all right so that should be it for the video and thanks a lot for watching guys do let me know what you thought about the video and don't forget to like and subscribe if this video helped you thank you
Sort Array By Parity
length-of-longest-fibonacci-subsequence
Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers. Return _**any array** that satisfies this condition_. **Example 1:** **Input:** nums = \[3,1,2,4\] **Output:** \[2,4,3,1\] **Explanation:** The outputs \[4,2,3,1\], \[2,4,1,3\], and \[4,2,1,3\] would also be accepted. **Example 2:** **Input:** nums = \[0\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 5000` * `0 <= nums[i] <= 5000`
null
Array,Hash Table,Dynamic Programming
Medium
1013
198
what's up everyone today we're going to go over house rubber first we'll go over the input and the output then we'll look at the approach and finally we'll go over the code and complexity oh the input is going to be an integer array and the output is going to be an integer what we have to do is pick numbers such that we maximize our score but the condition is that we can't pick consecutive numbers so we can't pick one and two and we can't pick two and three but we can pick the subsequences which are different like one and three so one and three gives four two and one gives three and one going from here to here gives two so we can of course also pick one number but why would we do that we need to maximize our score oftentimes when we go for maximizing or minimizing or counting the number of ways we go for dynamic programming so what we have to do is we have to trust that a solution to this problem does exist and that we can find it using some version of these sub problems we take the same question make it a little bit smaller in a way that makes sense and that we're allowed to and use some combination of them to build up the answer to our original question let's look at that now here are some sub problems the original question is asking us the maximum score if we have an array of length n now to make the sub problems what we have to do is take the original question and make it smaller somehow in this case it makes sense to ask the question again using a smaller array by let's say ignoring one element or two element or three element let's see what makes sense and what we can do to make it maximal if we ignore the last one that's okay if we ignore n then we could probably just take n minus 1. if we ignore n and n minus 1 and take n minus 2 it wouldn't make sense to ignore n so we add n if we ignore n minus 1 and n minus 2 that really doesn't make sense because our condition is only two consecutive numbers so we don't need to use this sub problem we can solve our problem using this one and this one now let's look at how we come up with the dag now that we've decided on our sub problems let's see what they mean dp of i minus 1 means we're going to ignore the element at i dp of i minus 2 plus a r of i means we're going to take i and we're going to recursively ask for the sub problem i minus 2 dp of i is going to be the maximum of either this or this for our input of 4 which is the length of the array dpf4 is going to ask dp of 3 and dp of 2 you can ignore the plus ar for now we're just looking at the dag recurrence relationship here's a more generalized tag dp of n is going to ask for dp of n minus 2 and dp of n minus 1. each of them is going to ask for their own thing so dp of n minus 4 n minus 3 and minus 2. now you see these sub problems are what we call overlapping pretty much they're repeating so we're going to cache them when we do the top-down cache them when we do the top-down cache them when we do the top-down memoized approach each call of dp is calling two one and two different dp calls keep that in mind when we look at the time complexity late before we look at the code let's briefly talk about base cases eventually we're going to run out of numbers when we keep making the array we're looking at smaller so what happens when we go negative if we only have one integer that's fine the index is going to be 0 and we just return what's in that number but if we go negative we're going to return zero and that's going to be our return condition for our recursive call so i've initialized the map which is used for caching so k is going to be the dp like of i and the i is actually going to be the key and the value is going to be dp of i and here's a global variable for the array and recursively call it so here's our base case first we check our cache have i already calculated this if so just return it otherwise recursively call dp of i minus 1 dp of i minus 2 or i just wrote n here but it's the same thing and then get the value if we decide to take the current value at n we calculate the max we put it in our map and we return for the bottom up tabular approach first we're just going to do some basic checks like the length of the array if it's zero we return zero if it's one we just return whatever elements in it if it's two we just return the maximum of the first or second number otherwise we initialize a dp table initialize the first two so if we have only one element we're just going to put it in there if we have the second element we're going to just take the maximum of the first two then we can begin our tag so we initialize our loop and at each stage all we do is we ask for r minus 1 or i minus 2 plus the number that we're currently visiting ultimately this is going to fill up the table and we just return dp of n minus 1. the bottom up tabular approach the space and time complexity are going to be of n because we initialized an array of length n and we iterated through the original array once the space complexity of memoization approach our cache could grow to a size of n and we could have for the time complexity in the worst case 2 power n if for some reason we have a bunch of cache misses we won't but that's a theoretical because each dp call is making two more dp calls so that's how you solve house robber if you like the video please thumbs up and if you want to see more don't forget to subscribe
House Robber
house-robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**. Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_. **Example 1:** **Input:** nums = \[1,2,3,1\] **Output:** 4 **Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. **Example 2:** **Input:** nums = \[2,7,9,3,1\] **Output:** 12 **Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 400`
null
Array,Dynamic Programming
Medium
152,213,256,276,337,600,656,740,2262
413
hi guys welcome to algorithms made easy in this video we will see the question arithmetic slices a sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive element is the same so here the examples given in these are arithmetic sequences because we can see that the first one has a difference of two for all the conjugative elements in the second one we have a difference of zero for all the consecutive elements and in this one we have a difference of minus four and if you see this sequence it is not an arithmetic sequence because there are no three elements in this sequence that would have a common difference a zero indexed array a consists of n numbers is given and a slice of that array is any pair of integers such that 0 is less than p less than q n which is less than n a slice of an array is called arithmetic if its subsequence is arithmetic in particular this means that p plus 1 is less than q this condition should always satisfy so that the sequence can be called an arithmetic sequence and now your function should return the number of such arithmetic slices in the array we'll understand it better when we see an example so let's see an example in a graphical manner so let's take a bigger example like this and here we can see that we can have two arithmetic slices which are 1 to 6 and then 6 to 14 which has a difference of 2 here the differences of one so how many number of possible arithmetic slices can be created over here these can be given by 10 for this particular sequence and six for this particular sequence and so in total we can have 16 arithmetic slices how do we get this 10 and the 6 is the part we need to focus on so let's take this example a smaller version from the one we have seen in the earlier slide and here we are taking this three numbers at once and finding the difference between the consecutive pairs so this gives us a plus one difference and since this is equal we can say that this is a slice and so we add 1 in this particular array so this is nothing but a dp array that we have taken and we'll keep on adding the arithmetic slice that we have found or else we can conclude the number of slices that could be possible by using the previous answer that we have got so let's see how we can use the previous answer in this if we go one step ahead this also forms a arithmetic slice and so we can say that one slice is possible with this but now there was one slice that was possible with the previous one too and so we can say that there can be a slice possible by taking into consideration all the elements present in the previous and current that's the reason we do one from here and this one from the previous i minus one position i hope that this is clear why we are taking and how we are taking the i minus one position into consideration now let's move ahead in this example and here we can see that this gives us a 1 as a difference and this gives us 4 as a difference so this is not an arithmetic slice and so this remains 0. moving forward again here we can see that the difference from 4 and 8 is 4 but 8 and 10 is 2 and so this is not an arithmetic slice so we do nothing but 0 is our answer for this particular position also now we move ahead here we can see that the difference is same and so we do i minus 1 plus 1 from this particular position which gives us 1. again as we move ahead this is also giving me an arithmetic slice with difference of 2 and so we can do 1 plus the 1 from i minus 1 position which gives me a 2. now that we have come to the end we can find the total from the dp array which would give me the total number of arithmetic slices that are possible which is 6 in this particular case so now that we know this dp approach let's go ahead and code it out then we'll see how we can optimize it or can we have a formula for this particular example so as we have talked we would need a dp array and this would be of the same length as a after we have this we also need a result variable which would be 0 and we loop starting from i equal to 2 so that we can take into consideration three numbers at a time in here we are checking whether the difference between these two consecutive pairs is same or not if this is the case we say that dp of i equal to 1 plus dp of i minus 1 as we discussed in our example and with this we can also add it in our result and finally we return the result let's run this code and it's giving a perfect result let's submit this and it got submitted and so the time complexity over here is o of n and the space complexity is also of n as we are using a dp array so now you can see that we only need the i minus 1 position in the dp so can i change this dp array to just an integer variable so over here this line would change from dp of i to dp and dp of i minus 1 to dp this will also change to result plus dp and now we also need to keep in mind that whenever we see a sequence that was not arithmetic my dp was 0. so i need to set that in my else part so 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 remains the same but the space complexity is reduced from o of n to o of 1. now let's see if we can have a formula for this so if you see this example closely over here for this particular sequence the answer is summation from 1 to 4 and for this particular sequence the answer is summation of 1 to 3 so how do i get this 4 and 3 can be found out by saying that okay i have a pair of 3 and how many pairs of 3 can i have so that would be given by the sequence that is there minus 2 or you can play with the count variable in such a way that it just gives you 4. we would see that in our example or in our code when we are doing it so that's the whole logic behind the formula if you know this you do not have to add a particular number for every iteration but you can just find how many different arithmetic sequences you have and what is the length of that arithmetic sequence or what is the count of the arithmetic slices of size equal to 3 and then from that you can find the formula that is summation of n equal to 1 to n and f of n that is given by n into n plus 1 by 2 so here if you see n into n plus 1 by 2 if you substitute here then it would be 4 into 5 by 2 which gives us 20 divided by 2 that is 10 or even here if you see it would be 3 into 4 by 2 which is 12 by 2 which gives us 6. so now let's go ahead and code this problem so that you can understand it how we are deriving the count so for that i'll need a count variable that would be 0 i'll also need a result variable the for loop over here would remain the same and in here instead of this i'll have count plus whenever i am getting the sequence that is continuing and if that is not the case my count gets reset to zero after you reach a place wherein you are setting the count to 0 you also need to find out the value for the number of arithmetic slices you could have generated from the previous sequence and so my result would become result plus the formula that is count multiplied by count plus 1 and this is divided by 2. so let's take in the brackets carefully this is all about the for loop but now you can also have a count that would be there if your arithmetic sequence was continuing till the end so that part or that sequence would not have been counted earlier so we would do that while returning this so that would give us this and let's run this code and it is giving a perfect result let's submit this and it got submitted so the time and space complexity remains same as in the better version of dp that we saw that is time remains of n and space is o of one so that's it for this video guys i hope you like the video and i'll see you in another great video so till then keep learning and keep coding
Arithmetic Slices
arithmetic-slices
An integer array is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same. * For example, `[1,3,5,7,9]`, `[7,7,7,7]`, and `[3,-1,-5,-9]` are arithmetic sequences. Given an integer array `nums`, return _the number of arithmetic **subarrays** of_ `nums`. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 3 **Explanation:** We have 3 arithmetic slices in nums: \[1, 2, 3\], \[2, 3, 4\] and \[1,2,3,4\] itself. **Example 2:** **Input:** nums = \[1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 5000` * `-1000 <= nums[i] <= 1000`
null
Array,Dynamic Programming
Medium
446,1752
153
hey guys Greg here let's solve 153 which is find minimum in rotated sorted array so suppose an array of length n is sorted in ascending order so the numbers are going up but then it's been rotated between one and N times so for example the array of originally nums as just the numbers 0 to 7 if you rotated it four times that would become 4 to 7 and then 0 to two why is that well if you track the four for example all the numbers are going to follow suit so tracking the four here it's going to move forward and if it goes to the end it's going to wrap around to the beginning it's going to go forward four times so the four starts here it moves forward once twice three times four times and all the other numbers will follow Zoot so it starts at four it's going to go up until 7 there's going to be this critical point here where you go from increasing just to decreasing in one step there's only going to be one spot where that's true because it's increasing in general but because we've now rotated it there's this pivot point where right here it goes from increasing order just to decreasing One Step here and your minimum will be on the right side of that and then it goes to increasing again and here this is the only circumstance where it is just increasing up okay so you have the chance of this pivot point but also it could be the case where it's just original sorted order as well so we're given the sorted rotated array nums of unique elements okay let's unpack that cuz that's actually a lot we are given the sorted rotated version so this has already been rotated we're not given like the amount of times that it's been rotated or whatever we've just been given this rotated array and we need to return the minimum element of the array and also they are all unique elements so there is no duplicates given that thing we have to return the minimum element of the array so that's going to be either that first value there if it's fully sorted or it'll be that one just after that pivot point now furthermore we actually need to run an algorithm that runs in O of log n time and if you've done a binary search problem or two then this should be screaming binary search to you as something to try Okay so let's just look at one of these examples here this should be enough so 34512 is our input the output is one because that is the value not the index but the actual value of the minimum element and the explanation is that the original aray 1 2 3 4 5 was rotated three times that's kind of a misleading explanation it's correct and that's not invalid it's just that we actually don't even really care like that the fact that this is true isn't even important to us for solving the problem now if you haven't heard of binary search before I would check out my video on that we actually have a couple of them on here already so we're going to start off with just pretending we can do a binary search here I know that's kind of problematic because we have this version in the middle here where it's not sorted but let's just give this a try and try to tweak it so we start L at the first index and R at the last index now for a binary search you would calculate your middle index which is going to end up being here you can do that through the formula l+ R over 2 that means formula l+ R over 2 that means formula l+ R over 2 that means integer division okay so that'll get you your middle index but just drawing it's going to be right here and of course we can access this value here so we have three values of Interest 4 7 and 2 now in normal binary search you'd expect this value to be higher than this value we'd actually just kind of guarantee that's true but we can't in this case we want to try and discover this Pivot Point okay if we can find this over here then this actually gets really simple the problem is that this value may or may not be bigger than this let's actually just forget about the left for now it turns out to not matter as much so we have the middle value of seven and we need to actually compare that to what's on the right now if it is bigger if this value is bigger what does that mean let's actually just pretend it was over here for a second so if the middle was here and the right was here well we discover that the middle is greater than the right and I mean the values not the indices so the middle value is bigger than what's on the right well it means that m is in this situation over here where if the middle is bigger than the right it means that the Pivot Point must be somewhere over here okay the Pivot Point must be in this range why is that true well if the middle value is bigger than what's on the right well that means there must be some point where we actually went up and then we hit the bottom if the middle value is bigger than what's on the right well that means that over here somewhere strictly to the right side of M that pivot point which we know is here that must be to the right of M okay so say if we found that's true let's actually write this down as a rule and again I mean the values of M and R not the indices themselves so if m is greater than R the rule is that the pivot point is somewhere to the right what does that mean well we need to update our bounds it means we want to set L to equal m + 1 so we set L to be m set L to equal m + 1 so we set L to be m set L to equal m + 1 so we set L to be m + 1 because now what do we see we're + 1 because now what do we see we're + 1 because now what do we see we're looking in a better range here we know we don't care about the pivot point over here it must be now somewhere in this range so we're just going to keep asking this question what if the case that this is not true as in m is less than or equal to R let me just make this a little bit smaller because that seems to be taking up all the space here so let's get our new middle value we'll get M and let's write the math out this time so this is index 0 1 2 so M we know is equal to l + r / 2 integer division that equal to l + r / 2 integer division that equal to l + r / 2 integer division that is going to be 3 + 6 and then integer is going to be 3 + 6 and then integer is going to be 3 + 6 and then integer division by 2 that is going to give 9 / division by 2 that is going to give 9 / division by 2 that is going to give 9 / 2 which rounds down to 4.5 rounded 2 which rounds down to 4.5 rounded 2 which rounds down to 4.5 rounded down is four so we are going to get M as this element right here okay so now we actually need to figure out what we want to do if m is less than R okay so we're not in this situation we're in the else could this be the minimum okay could M actually be the minimum so in the case that m is less than R this actually could be our minimum value and it turns out that it is but we need to keep looking in the correct range so what do we want to narrow in on this minimum so if M could be that minimum and we want to get closer to it we set r equal to M why can we get rid of all of this range here well we know that this value is smaller than over here and therefore we're looking for the smallest value we want to update our range so that we get rid of these bigger values and narrow down in on this minimum so in the case that m is less than or equal to R we actually want R to equal m that gets rid of that right side range and we move down to narrow in on the minimum okay let's do this one more time we'll get our middle value is 3 + 4 / 2 we'll get our middle value is 3 + 4 / 2 we'll get our middle value is 3 + 4 / 2 integer division that's going to round down to three so our middle value is going to be right here we ask the question is the value at M greater than R if this value is greater than over here well we know that the minimum is going to be strictly to the right over here and so what do we do well we follow our same rule we set L to = m + 1 at our same rule we set L to = m + 1 at our same rule we set L to = m + 1 at this point we can see that we have R and L are equal to each other and that is actually when we complete this Loop because we're going to end up doing this while L is less than R when they're equal to each other we break out and that is when we're on the minimum so notice that following these sets of rules right here following those rules we will narrow in on the minimum okay that being said let's write our code so we set n equal to the length of the numbers so we can start our binary search with L is equal to 0 and R is equal to the last index which is n minus one now we want to run this as we said while L is less than R so when they're equal to each other we want to escape and actually both L and R are located at the minimum we get our middle value which is L + r integer division by two which is L + r integer division by two which is L + r integer division by two to get the middle index and then we just keep asking the question hey if nums at M is actually greater than nums at R so if the middle value is bigger than what's on the right the minimum or the Pivot Point must strictly be to the right of M so we set L2 = m + 1 right of M so we set L2 = m + 1 right of M so we set L2 = m + 1 otherwise could M be the minimum yes it actually could but we want to get closer to it and so R we set equal to M we don't want to lose track of the minimum so we don't go past it we set r equal to M after we escape here we could do either nums at f or nums at R because we're escaping when L and R are equal to each other so we'll run that and as you can see that is going to work so for the time and space complexity here well the time complexity is going to be what well we do a binary search and while it's slightly modified one and clever one it's still just a binary search we cut off the search range basically divide it by two every single time because we go and check out our midpoint and then we ditch half the range so our time is going to be Big O of log n that's how fast a binary search will run and the space complexity here well notice we're not really storing anything that's a number these are numbers we really just store a couple numbers and so that is going to be constant space Solution that's our final answer I hope this was helpful and have a great day guys bye-bye
Find Minimum in Rotated Sorted Array
find-minimum-in-rotated-sorted-array
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become: * `[4,5,6,7,0,1,2]` if it was rotated `4` times. * `[0,1,2,4,5,6,7]` if it was rotated `7` times. Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`. Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_. You must write an algorithm that runs in `O(log n) time.` **Example 1:** **Input:** nums = \[3,4,5,1,2\] **Output:** 1 **Explanation:** The original array was \[1,2,3,4,5\] rotated 3 times. **Example 2:** **Input:** nums = \[4,5,6,7,0,1,2\] **Output:** 0 **Explanation:** The original array was \[0,1,2,4,5,6,7\] and it was rotated 4 times. **Example 3:** **Input:** nums = \[11,13,15,17\] **Output:** 11 **Explanation:** The original array was \[11,13,15,17\] and it was rotated 4 times. **Constraints:** * `n == nums.length` * `1 <= n <= 5000` * `-5000 <= nums[i] <= 5000` * All the integers of `nums` are **unique**. * `nums` is sorted and rotated between `1` and `n` times.
Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2]. You can divide the search space into two and see which direction to go. Can you think of an algorithm which has O(logN) search complexity? All the elements to the left of inflection point > first element of the array. All the elements to the right of inflection point < first element of the array.
Array,Binary Search
Medium
33,154
915
hey everybody this is larry this is day 22 of the july league daily challenge hit the like button to subscribe and join me on discord let me know what you think about today's problem and today's problem is partition the way into this disjoint intervals okay so i usually stop this live so if it's a bit slow fast forward uh do whatever you need to do um okay so you want to break this into two parts where every element in left is less than or equal to every other one on the right okay you have to have at least one element and then that has the smallest possible size okay so i think in this case you can do this greedy and by greedy i mean just try it one at a time like can you do one number into two number and as soon as you hit the number or if you hit it such that it is true then you can go away and then now we're just trying to figure out about okay now you're scanning from left to right how do you calculate the invariant in such a way that or finding invariant that you can hold to be true as you go from left to right um right and in this case in brain is that every element in depth is equal to l or yeah less than or equal to every element in right and so that you have to keep you would keep track of the max element in left and keep track of the min element and right as you go from left to right and from that i think that's good enough for us to get started um and of course if we do it naively even though n is 30 000 um that's gonna be n square trying to get the min every time getting the max i think it is pretty straight forward yeah and i think you can we think if you can do this and doing an analog end is also straightforward maybe or it's doable um because you just keep the max element on the left side which you know you keep adding to max and then you're trying to get the main element on the right side i think you can probably do a min queue to get this down to linear time uh like a model uh a model q that is a min queue um but natural yeah i think that's actually true so you can actually do this in linear time because you can just get okay what's the min what's the mean of everything to the right side right um and you can also use the heap to kind of just keep it live in a way but you can actually just get the running min of everything to the right side right so that's actually even easier so let's do that so yeah let's just do so mins is equal to um some infinity times n is equal to length of nums yeah okay and then now we do for index in range of n minus one all the way to i usually do to zero but actually in this case we actually want it to be negative uh we wanted to do an one i guess it doesn't really matter okay um and then now so we're going to get the men of this and so basically captured the rolling min going from the right side right um and in this case uh we just have to be a little bit careful so this is n minus 2 min sub n minus 1 is equal to num sub n minus one and now we're able to go from left to right so we go from yeah left to right trying to think about what's the cleanest way to do it but because so what i'm thinking about is also that we have to guarantee that they're linked one so i'm trying to think about what's the best way to implement that is it's not a big deal convex is equal to max of current max numbers of index and now so okay so we've actually won this thing and also we don't want to go on the last element anyway so yeah so if current max is less than or equal to the min of the right chunk then we can return index so maybe i'm doesn't really matter um just maybe r51 is what i'm looking for because yeah because this is the index but we want the length of it right so we can do that and that should be pretty okay let's give it a submit cool um so yeah as you can see this is linear time linear space um one thing i would say is that yeah if you want so this is two pass yeah i guess this is unavoidable i was gonna say maybe you could do something playing around with heaps if you want to play around with it but there's still going to be multiple paths because you have to put everything in the heap right so maybe that's not an ideal way anyway but yeah so this is linear time because this is linear and this is linear right um yeah and we have linear space here i think you can compress this a little bit but i don't think you can i mean it's not going to be worst case in the near space so it is what this is yeah that's all i have for this one let me know what you think hit the like button to subscribe and drop me a discord hope y'all have a great week i'm still here just hanging out um and i will see you later stay cool stay good take a mental health bye
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
832
hey everybody this is larry this is day 10 of the november league code daily challenge hit the like button to subscribe and join me on discord uh and today's forum is flipping an image binary matrix x you want to fit horizontally inward and then return the image okay which way is horizontally uh like left goes to the right i guess okay i mean this is pretty straightforward in either case you could do it either one by one or you could do it at the same time it doesn't really matter you don't even have to even do it in this order technically because they're independent of each other you just have to do it both those operations uh and it should be pretty straightforward to do it in you know exactly uh whatever so yeah i mean i don't really have much to say so let's get started um let's just do uh flip inward let's say that takes a matrix uh a and then we can go somewhere like for x in range of this is always a square i guess so not always queer good um the end let's go to length of a well for y in range sub n what we want to do is we want to set a sub x sub y is equal to a sub n minus x minus one y now that's the other one you don't want to change the y direction something like that uh and of course this is gonna mess up because we don't we need to do an actual swap so let's just do an actual swap uh but you know but in this case we would double count it so we actually need this to go to n over two um okay so yeah so now we didn't do the inverse yet but let's see if this does what we expected to do well probably not because we should at least in word a note the quarter function uh okay so hmm all right i was looking at the expected answer so this is looking at the expected answer it is mostly right except for that i didn't um i this is flip not in word but i got the terminology wrong but either way um but now we just need to invert it which is pretty straightforward as well right which is just for x and range of n for y and range of and a sub x y is equal to one minus a sub x y to convert it from zero to one and vice versa so now let's run the code again uh looks okay by the eyeball test so let me see if there's any zero case things i don't think so let's give it a go yeah easy problem easy thing uh let me know what you think this is only a couple of for loops i don't really know what to say um in terms of space i do it in place but yeah i don't know depending how you feel you may or may not shoot or should not do any praise that's how you know uh for me i don't care about it for this problem but in some cases you might right um yeah but in terms of space it's going to be i don't use any extra space but if you were to make a copy of it which to be honest is probably a better idea then it would take linear space and also right now it takes linear time because we look at each cell once right uh linear time of course means it's the linear in the size of the input and the size of the input is n squared so it's of n squared time and of n square space if you allocated extra space uh that's all i have for this problem this seems pretty straightforward so i'm not going to dip into it that much but if you have questions let me know because i could be wrong on my assumptions about that one uh yeah i will see y'all tomorrow bye
Flipping an Image
binary-tree-pruning
Given an `n x n` binary matrix `image`, flip the image **horizontally**, then invert it, and return _the resulting image_. To flip an image horizontally means that each row of the image is reversed. * For example, flipping `[1,1,0]` horizontally results in `[0,1,1]`. To invert an image means that each `0` is replaced by `1`, and each `1` is replaced by `0`. * For example, inverting `[0,1,1]` results in `[1,0,0]`. **Example 1:** **Input:** image = \[\[1,1,0\],\[1,0,1\],\[0,0,0\]\] **Output:** \[\[1,0,0\],\[0,1,0\],\[1,1,1\]\] **Explanation:** First reverse each row: \[\[0,1,1\],\[1,0,1\],\[0,0,0\]\]. Then, invert the image: \[\[1,0,0\],\[0,1,0\],\[1,1,1\]\] **Example 2:** **Input:** image = \[\[1,1,0,0\],\[1,0,0,1\],\[0,1,1,1\],\[1,0,1,0\]\] **Output:** \[\[1,1,0,0\],\[0,1,1,0\],\[0,0,0,1\],\[1,0,1,0\]\] **Explanation:** First reverse each row: \[\[0,0,1,1\],\[1,0,0,1\],\[1,1,1,0\],\[0,1,0,1\]\]. Then invert the image: \[\[1,1,0,0\],\[0,1,1,0\],\[0,0,0,1\],\[1,0,1,0\]\] **Constraints:** * `n == image.length` * `n == image[i].length` * `1 <= n <= 20` * `images[i][j]` is either `0` or `1`.
null
Tree,Depth-First Search,Binary Tree
Medium
null
867
question 867 transpose matrix so what the question is asking for is to return the new transposed matrix where it is flipped over its main diagonal switching the row matrix row and column indices so we can see over here that the main diagonal value is unchanged before and after and what's changed are the other values so this is now in this position these two are swapped and then this one is changed with this and same for this one okay um also looking at the second example we have something like one two three and then four five six and what this should return us is something like one four two five three six so we can see that the okay if we label the rows and columns let's do that let me just try using a different color this one zero one two same for this we can see that the main diagonal values where the row and column are the same we can see that they don't change what got swapped are the other values so previously for this value number two it was in row zero column one and now it's in column zero and row one so it's flipped and the same for the other stuff like under the numbers like four where it's previously one zero now it's zero one and then this value it's the same where it's uh zero two now it's two zero and four six it was previously one two and not two one so that's it we can start coding until let me try to figure out how to exit yeah okay so some constraints are listed over here um amster row ends the column and for m and n they are between values one and one thousand and m times n is between one and ten to the power five and the values itself can be positive or negative ranging from minus 10 to the power of 9 to 10 to the power of 9. yeah okay sorry um okay so intuitively i feel like maybe i want to create a empty um new array first with dimensions n by m instead of the original n by n because i want to create a empty resultant matrix with pre-populated with zeros first and then pre-populated with zeros first and then pre-populated with zeros first and then i will traverse through the original matrix and try to replace the new matrix values at the correct position so let me start with that so m is represented by the no the matrix number of rows of the matrix original matrix will be represented by m oops matrix not length of matrix and then n is the length of the first um row which effectively means the column so let us now create a new resultant matrix so new matrix is equal to like let's do something like zero four i in range and because we want a n by n one so now this will be m and then for j in range n so now we'll have n by and matrix n by n matrix yeah i think so okay so um okay now that we have the zeros in place we can start traversing through the original matrix and replacing these zeros with the correct values so for i in range matrix j in range matrix zero new matrix j i is equals to matrix i j and then at the end of everything we return new matrix um i feel like something's wrong somewhere oh okay great it looks like our time run time and memory is not that great i will be looking into that yeah alright that's it for now thank you
Transpose Matrix
new-21-game
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **Example 2:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\]\] **Output:** \[\[1,4\],\[2,5\],\[3,6\]\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 1000` * `1 <= m * n <= 105` * `-109 <= matrix[i][j] <= 109`
null
Math,Dynamic Programming,Sliding Window,Probability and Statistics
Medium
null
456
hello everyone welcome to day seventh of may lead code challenge and i hope all if you're having a great time my name is sanchez i'm working a software developer for adobe and today i present day 676 of daily record problem the question that we have in today's 132 pattern here in this question we are given an array of integers and we need to identify whether a subsequence of three integers exists in this array such that the pattern that gets formed is of type 132 if it does exist then we need to return true otherwise we need to return false i'll be walking you through this example as well as the definition of this pattern why the presentation so let's quickly hop onto it lead code 456 132 patent it's a medium level question on lead code and i also feel the same also in case if you have any doubt understanding this question or if you want to ask anything from me in general please feel free to ping on the telegram group or the discord server of coding decoded both the links are mentioned in the description so do check them out now let's get started with understanding the question what does the question mean by 132 pattern so by 132 what we are actually looking for if we plot these elements on a graph of paper on a 2d plane what kind of structure will it be formed so we'll have one over here we'll have 3 over here and we'll have 2 over here so what we are interested in identifying three subsequence elements such that this kind of structure gets formed so if you carefully observe here then this element is least of the three elements and this element is in the middle this element has a topmost weightage is acting as a peak of the entire three elements so we are looking for three elements such that this graphical structure gets formed now let's take a hypothetical scenario wherein these elements are given to you a1 a2 a3 a4 a5 a6 and a7 let's consider a case where a4 is acting as the peak of the entire array that means it has the highest value across the entire array now comes a concern what will you consider towards the left of a4 and towards the right of a4 so let's talk for each direction one by one let's talk about the right of a4 when you are looking at the right most elements of a4 what will you what property will you look out for you will look out for the maximum element after a4 so whatever element exists across a5 a6 a7 you will try to maximize those elements you will find out the maximum one that exists across these three elements a5 a6 and a7 once you have identified the maximum element after a4 towards the right of a4 across these three elements let's name it as max second max because the first max was a4 let's call it second max now let's move it towards the left direction of a4 across these three elements a1 a2 and a3 what will you do over these three elements you will try and look out for the minimum one towards the left of the a4 so you'll search for the minimum one towards the left of a4 once you have identified the lower value the least value in order to identify whether 132 pattern does exist the rule is simple the least value should be less than the max the second max value that you have identified if this condition is met your work is done your least value on the right side of a4 should be less than the max value towards the left side of a4 if you are able to identify this equation then your work is done you are able to identify the 132 pattern and you will return true in those cases however in case your least value towards the right of a4 is greater in value than the second max value that you have identified over here then you'll have to return false because this graphical structure will not be formed so let's take both these examples one by one let's take numbers as 7 6 5 nine one two and three what is the maximum value across this entire area the maximum value is this one this will act as our a4 what we are interested in finding the second max value towards the right of if a4 the second max value here would be 3 and the least value towards the left of 9 is 5 so the least value is 5 the second max value is 3 when we do the comparison you will see that the least value happens to be greater in value than 3 as a result of which you'll have to return false in those cases let's also talk about a happy case let's assume the input array something like this 5 7 4 9 eight seven three so let's hypothetically assume this is the input error that is given to us the maximum value here is nine and what you look out for the second max value towards the right of it so the second max value over here out of 8 7 and 3 turns out to be 8 the least value towards the left of 9 is 4 so the least value is 4. when you do the comparison you can see that 4 is lower than 8 which satisfies the case as a result of which we are able to identify 132 pattern so what are those three numbers the first one is 4 the second one is 9 and the third one is 8. so if you plot four nine and eight on a sheet of paper what kind of graphical structure is getting formed something like this i hope both these examples are clear to you now comes the question what is the algorithm to go about it for solving this question we'll be using monotonic stacks to actually arrive at the solution and uh if you're not aware of monotonic stacks i'm attaching the playlist in the description below go and check out the daily temperature question it will give you a very good idea how monotonic stacks in general operate now let's proceed ahead understanding the monotonic stack over and test case iteration so let's consider a different example slightly longer so that you get a good hold of concept the elements are 9 4 2 eight three one two what i'm gonna do i'll definitely create a variable named second max let's represent it with sm and let's initialize it to minus infinity and by minus infinity the least possible number of integer data type and what i'm going to do as i told it's a stack based question so definitely i'm going to create a stack i'll simply i trade from the rightmost terminal to the leftmost terminal and let's start the iteration the first element that we that i see happens to be 2 the stack is right now empty there is no element added onto the stack so what we are going to do we'll simply go ahead and add 2 to it let's proceed ahead next we see is 1 so when you see 1 what you will do you will compare this value 1 value with the topmost element of the stack the top most element of the stack is greater in nature than one so in those cases you'll simply go ahead and add one to the stack let's proceed ahead next we see is three so add three what do you see what is the top most element of the stack happens to be one since three is greater in value than one what you are gonna do you simply pop this element out so this element is gone along with this you will compare it with the second max value so consider 3 is getting treated as the maximum element and you have to look out for the second max value across this complete sub array so you compare this sm value with one which one is greater out of one and minus infinity one is greater so this gets replaced by one let's proceed ahead again what is the top most element of this stack the stack is still not empty the top most element of the stack happens to be 2 so again you will compare it with 3 is greater in value than 2 as a result of which 2 gets deleted out of this stack you will again compare this 2 with the second maximum value and as a result of which this gets replaced by two we have successfully identified the second maximum element across this sub array the maximum element that is getting treated is three and the stack has become empty as a result of which will simply go ahead and push this element onto the stack so three gets added onto the stack so far so good let's proceed ahead let's move towards the left and the element that we have is eight so at eight let's do the same thing again let's compare it to the top most element of the stack is three as you can see eight is greater in value than three as a result of it this element will be deleted you'll compare it with the second max variable which is 2 is lower than 3 as a result of which this gets re updated to 3 what does this mean this means that 8 is acting as a peak and we have to identify the second most element across the this sub-array three one and two we have sub-array three one and two we have sub-array three one and two we have successfully done that the sm variable the second max variable holds the value three and the stack has a value eight in it let's proceed ahead next comes the most interesting case guys what element do we see 2 and at 2 what we are going to do we will check what is the top most element of the stack the topmost element of the stack happens to be 8 in nature as a result of which we are not going to delete this up along with this what you will do you will compare this element with the sm value what is the sm value the same value happens to be 3 as a result of which you have identified the lower value towards the left of 8 and the higher value towards the left of 8 you can see that 2 is lower than 3 therefore we can say that we have identified the 132 pattern successfully the time complexity of this approach is order of n also the space complexity is again order of n to conclude it further let's quickly walk through the coding section and i'll exactly follow the same steps as i've just talked here so here i've created a second max variable in initialize to integer dot minimum and i have created a stack of type integer i start iterating from the rightmost terminal to the leftmost terminal in case my current element happens to be less than my second max value the in those cases i simply return true this is a happy case that means that my current value is lower than my second max value uh this is the breaking condition that tells us whether the 132 patent has been identified or not if it is not true then what do we check whether the stack is empty or not and if my current element is greater than the topmost element of the stack i have to pop elements out of it so i do the popping operation and i keep track of the second maximum that have witnessed so far if this condition is also not successful i simply go ahead and add elements onto the stack so all the peaks will be added over here all the peaks will be added onto the stack in case the true condition is not met as a default statement i have written return false in those cases because if this condition is not met then we can say that 132 patent doesn't exist in my input array so let's try this up accepted pretty fine with this time complexity the time complexity in general is order of n and the space complexity is again order of n with this let's wrap up today's session i hope you enjoyed it if you did please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded i'll see you tomorrow with another fresh question but till then good bye take care
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
1,696
To Share Subscribe button and welcome back to my YouTube channel Today we are doing Ninth Question Objective Question Lens for Nico and the question is Champions Trophy Vitamin C The question it will ask and Share and Subscribe Hamare mann hoga to hume ghum kaun tak kar sakte Can subscribe and give us not at all voice mail messages 125 please give me all wedding saw that from here till here we can say ok so are you can reach the last of the index in this we can go till the last because the entry would be Is total but all these things one roti can go in question means one person should visit ok subscribe this channel if you have not subscribed then now if - 151 not subscribed then now if - 151 not subscribed then now if - 151 - 2 - two torch lights this if then I After Gai1 - To Subscribe torch lights this if then I After Gai1 - To Subscribe torch lights this if then I After Gai1 - To Subscribe that I am here were on the first index I will call on the phone because if 022 - will call on the phone because if 022 - will call on the phone because if 022 - What will happen to me then if I so far I have two options subscribe you this question means school appointed If subscribe that we will travel every time ago and inside what we will do is we will submit the every time element and then check that the maximum element is okay, we can record it okay now after that we can still use it. And I will tell you the solution of this, in this we put like subscribe you like subscribe and finally tighten the last indexes. You guys start from Prithvi in ​​this sample guys start from Prithvi in ​​this sample guys start from Prithvi in ​​this sample that farmer starting from 3 so my first initial mostly that for free. Either - initial mostly that for free. Either - initial mostly that for free. Either - Tips could have been given Now on the phone A Meghnad Okay after the step I have to go till the last or else I do my - - If I do then or else I do my - - If I do then or else I do my - - If I do then I know the last element whether it is mine or not so anyway I did Started the look with the lastik, ok, what should I do? Do the first number like I did in the example. Subscribe
Jump Game VI
strange-printer-ii
You are given a **0-indexed** integer array `nums` and an integer `k`. You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**. You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array. Return _the **maximum score** you can get_. **Example 1:** **Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2 **Output:** 7 **Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7. **Example 2:** **Input:** nums = \[10,-5,-2,4,0,3\], k = 3 **Output:** 17 **Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17. **Example 3:** **Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2 **Output:** 0 **Constraints:** * `1 <= nums.length, k <= 105` * `-104 <= nums[i] <= 104`
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
Array,Graph,Topological Sort,Matrix
Hard
664
354
okay let's talk about russian door envelope so you're given 2d array and embedded i represent w i and h i represent height and width and whenever one envelope can fit into an order if only the width and height of both greater than the other so return the maximum number of the envelope you can um right so in this case uh this is a 2d array right and when i saw it i will have to stop based on the first index this is because this will give you one of the smallest through graders right but we also have to worry about in this one if they are the same the first index are the same we have to know the second index so based on the second index the greatest comes first this is because you want to avoid the next coming envelope the russian envelope and put into the other right you cannot have a smaller one so imagine is five four and six four right five is actually less than four but four is not less than four no you know what i mean right you have to say six vote by four so six four can put on five four right so after sorting you'll have two three five four six seven six four and basically you sort it so they just um hold it so m envelope uh comma and using the java a lambda expression this is the a b and based on reversing this if the index to the first in the other set if they understand i will have to earn i think that's first now if they are not the same i would just say okay the smallest one goes first so this is a java along the origin sector not familiar probably just review the double eight so i will have a height just sort i mean just memorizing the this one the height will represent um whatever i told you i less than 5. and assign the envelope index 1 to the height so height i equal to envelope that's just three four seven four this is correct and using a one using the longest increasing subsequence idea i have recorded this video a channel so i mean i'm gonna run it and using this idea you actually solve this question pretty easily so yes the answer is four because you need to return the longest uh increasing subsequence right so i will just call this function obviously in just copy i'm going to put it right here for this function and there we go this is a pushy way which is copy and paste but i will recommend you to know what is in my video all right let's talk about timing space complexity so what about the time this is what according this is another one right without any questions i'm not going to starting in album and this is open and it's not been on this listen now and this is all of them and this is my friend so pretty much it's earned often and this is another length of time is unknown and space is open okay and this will be the solution so if it feels helpful subscribe like leave a comment and i will see you next time
Russian Doll Envelopes
russian-doll-envelopes
You are given a 2D array of integers `envelopes` where `envelopes[i] = [wi, hi]` represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. Return _the maximum number of envelopes you can Russian doll (i.e., put one inside the other)_. **Note:** You cannot rotate an envelope. **Example 1:** **Input:** envelopes = \[\[5,4\],\[6,4\],\[6,7\],\[2,3\]\] **Output:** 3 **Explanation:** The maximum number of envelopes you can Russian doll is `3` (\[2,3\] => \[5,4\] => \[6,7\]). **Example 2:** **Input:** envelopes = \[\[1,1\],\[1,1\],\[1,1\]\] **Output:** 1 **Constraints:** * `1 <= envelopes.length <= 105` * `envelopes[i].length == 2` * `1 <= wi, hi <= 105`
null
Array,Binary Search,Dynamic Programming,Sorting
Hard
300,2123
234
welcome to this video now we have a coding interview question palindrome linked list you're given a singly linked list to determine if it is a palindrome for example if you are given this particular linked list then you have to return true because this linked list is a palindrome if we reverse this linked list then it will be like this one two one all right if we reverse this linked list then we will see this linked list so this linked list and this linked list are the same and don't worry about this null node simply means nothing so in this case you have to return true okay if you're given this particular linked list then also you have to return true because this linked list is a palindrome if we reverse this linked list then we'll see the same link list if you're given this particular link list if you reverse it then we'll see three two one okay so this is not same as this linked list so in this case we should return false right now how we can solve this problem let me go through the inside intuition to this problem okay for a second understanding let's assume we're given this linked list okay now how we can solve this problem first we're going to find the middle note for that first we're going to declare to pointer that will point to the head node so here p1 point to this node and p2 also point to this head node then we're going to move p1 pointer by one node and p2 pointer by 2 node so p1 pointer will point to this node p2 pointer will point to this node okay then we're going to move p1 pointer by one note and p2 pointer by two note so pure will point here and pita will point here okay now we see that the next node where p2 pointer point two is null so we found our middle note now what we're gonna do is that we're going to reverse the left part of the middle node so in this case we're going to reverse this part so it will go here and one will go here all right now what we're gonna do is that we're going to declare new pointer p3 to this node 2 and when we have old number of nodes in a given linked list then we're going to move the p1 pointer to the next node so p1 pointer will point to this node 2 okay and we can skip this pd pointer we don't need this right now we're going to move the p1 pointer and p3 pointer by one note by checking the value all right the current value for v3 and p1 is 2 we see that the value where p3 pointer and p1 pointer points to are the same and that is two then we're going to move p3 by one node so with the point here and p1 by one not so it will point here then we're gonna check the value so we have value one and one so that is match and then we see that the next node where p1 pointer points to is null so we can't move p1 pointer anymore so we see that we haven't found any unmatch for p3 and p1 pointer so this linked list is a palindrome now let's see for even number of nodes okay if we have this given linked list then let's find out first the middle okay p one and p two pointed point to the head node then let's move p one by one and p two by two so p one point here and p two point here and let's move them again so p one point to this node and p two point to this node okay we see that p2 pointer pointed now so we can't move p2 anymore we have found the middle node right there is two now let's reverse the left part of these middle nodes so two will go here and one will go here okay then we're going to declare here new pointer p3 right and we don't have to move p one pointer by one node because this linked list contains even number of nodes all right now let's take the value for p3 pointer and p1 pointer and there is two so this is a match now let's move them one by one so p3 pointer will point here and p1 pointer will point here so we see that the value where p3 and p1 pointer points to are the same and the next node where p1 pointer points to is null so this is a valid palindrome right so in this case you have to return true if we found unmatched for the value of p3 pointer and p1 pointer then we're gonna return pulse right now let's see how we can solve this problem using pseudocode first we're going to declare a function is palindrome that takes head of a given link list and let's assume that this is our given linked list right then we're going to check if here equals to now or hey dot next recall to now that we're gonna just return true if our given link list is now that we're going to return to if we have only one node then we'll return true right then we're going to declare pure pointer that will point to this height then we're going to declare pt pointer that will also points to this head right then we're gonna declare p3 pointer that's points to null at this point then here we're going to find the middle right p1 pointer point here and pt pointer will point here then for next iteration of this while loop p and pointer will point here and p to pointer will point here so we will have our middle here okay we have found our middle node that is two right now let's reverse the left part okay so here we declare a variable typicals to now then previous to null right and current equals to h so current points to this node one all right then we're going to check if current not equals to p1 so this node one is not equals to this node two so this while loop will run then temp equals to current dot next so we're gonna delete temp to this node two okay then we're gonna change the pointer current.next to prep so it will current.next to prep so it will current.next to prep so it will change to null right because we have private equals to null then triples to current so the null pointer temp will point to current and temp will point here okay we have pivotals to current so the null pointer pip will point to the current node so it will point here so this is for prep let's assume here for prep right then current equals to temp so we're gonna shift this current to temp here let's assume c per current okay we know that this node one is connected to this null node right now for next iteration of this while loop temperatures to current dot next so temperatures to current dot next it will point here so temp will point you let's assume deeper temp then current next day goes to prep so this pointer will points to this node one okay then pivotals to current we're going to move this prep to this current here okay then current equals to temp so we're going to move this current to this temp so here let's assume c for current okay then it will be look like this all right we see that this two node one and two has been disconnected from our linked list now let's link up that we're going to link this note to this node okay and here head dot next equals to p1 so hit pointing to this node one right and here dot next equals to p1 so here we have p1 so it will point here then it will be like this okay then we have here if p2 not equals to null and p2 dot next equals to null that means if we have old number of nodes in the given linked list then we will move p1 pointer to the next node so we don't need to move pure point to the next node because we don't have here what number of nodes in this linked list okay then we're going to declare a new pointer that will points to this node 2 where p points to here p3 pointer will point to this node 2 then we're gonna run a loop if you are not equals to now then we're going to check the value for p1 and p2 if this are not equals to null okay so we see p or not equals to null right then p one dot not equals to p three dot val if we see the value where p three pointer and p1 pointed points to are not equal then we're going to return false if not then we're going to move them so p3 will point here all right and p1 will point here and we see that for next iteration the value where p3 and p1 pointed points to are the same so this if condition will not match for the next iteration p1 pointer will point to this node null and p3 pointer will point to this node 2 okay and here recipient pointer is pointing to nouns so this whole loop will stop here then we're gonna just return true and that's how we can solve this problem the solution will take speak up end time complexity where n is the length of the given linked list and it will text space complexity alright guys thanks for watching this video
Palindrome Linked List
palindrome-linked-list
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_. **Example 1:** **Input:** head = \[1,2,2,1\] **Output:** true **Example 2:** **Input:** head = \[1,2\] **Output:** false **Constraints:** * The number of nodes in the list is in the range `[1, 105]`. * `0 <= Node.val <= 9` **Follow up:** Could you do it in `O(n)` time and `O(1)` space?
null
Linked List,Two Pointers,Stack,Recursion
Easy
9,125,206,2236
398
Hello hello friends welcome to codeinator love this channel doing great difficult my channel and please share subscribe my favorite become playlist cricketer and various categories of problems which made for research difficult for your research dynamic programming real mother and son porn you will find play list Aware Subscribe This Problem Random Boys With Randomly And The Giver That This Iodine Target Number Must Adjust In The Morning For Thursday In Tears And Abroad To Give Me To The Giver Dravid Thursday The Index More Seven Target Number And Mrs. Doodh Embroidery Single Member Will Appear at multiplex subscribe number of different places you give the number to numbers from 12345 1010 subscribe phone number three layers of wearing multiple times and times during the next to three and four and so if third number valve co subscribe school se pick subscribe thank you liked The Video then subscribe to subscribe The Amazing Tours But Also Yes This Pitru School Producer Pitru Visarjan And Pitru Water Written Test Ko Hang Mod Pitri Light Ko Turn Right Soega Liye Anukul Recirculation Subscribe To Tried To Return Churi And Subscribe 4,320 4,320 4,320 What can we do they will fight back to different approach to know what the government will start with Sudhir and this is the President of New Delhi this Vansh Pitru Record Chart is side return to first and this Pitru is fennel return how to Do Increment Support Staff Bomb What Happened 131 Do And Pitru School President To 9th Urs And Doing It's Best That Internet Start Victims Experience Quiet Ride Assessment Pitru Yagya Na Ent Time Came To Return On Equity And Internet Chat Start Victims Notification Half Fuel MP3 Original Print Only in The Amazing Friends Page No. 90 Subscribe That So Basically Set Start That Lakshmi Installed Victims ' Revolt And Return To Benefits Are ' Revolt And Return To Benefits Are ' Revolt And Return To Benefits Are That Road Installed Vikram On Bhi Soye Special This Is Not In The Early Random In Random Or Se Thursday Get From Here But Screen Shot Friend 1954 Tours Subscribe Now Massage Aur Chana Rubber Aam Gond Change It's Too Good Even One Update What Do Something Right And This Is How To Update 0123 What Services Professor And 248 Suna Van Veer veer 240 Ho coat paint dont do is this veer wa 1230 length second length of hai are hmm calling wise rock on ka haq hai na ki vivarvar to chulhe the boy was never patented railway crossing 0242 pick tree again that game is what they need To return to be alert and Toubro Ashwin in more subdued tone that transponder to 20451 main one lanka jaaye so what they want to generate a famous in a process will keep on repeating headlines and what they are doing but they best wishes call me To Subscribe Veer That All Software Satisfying Condition Admin Needed Which is Equal Problem Solved Time Real Images A Vision Radically Adventure Stress Wasteful Element Download Subscribe to Wave World Channel Please Like This Channel Subscribe Pick Subscribe Fluid Open Account Do That Aaj Is Free And Dark Red Software In Temple With Jagdish Singh Right That Element And Corresponding NSS Super This Is Not To Dhund Do This Channel White Dark subscribe and subscribe the Channel Please subscribe and subscribe the Channel and subscribe the half hour duration input end Will Have All The Different References Of The Republic In True Spirit Soul Will Not Vote For Them With The Dar Boys Film The Attacks But They Are Not Going To Pick Up That They Argument But Rather Not Glass Person Classes Paper Singh Liner Note Class Ok Subscribe Line Not Much Loss Did Not Aware Of Logic In Ninth Class Is Dahej Started Basically Jhal Induction Start Guide In This Is Well All The Difficult For The White Color Element And Electronic Suna Do Hua Tha When You And Mrs But Which Were To Women Gate And Gateway Subscribe To Give The Phone That Ravana Driving Best Song Starts Patience Setting Stuart Broad Day Light subscribe and subscribe And subscribe The Amazing That Were Doing Work Hai Udhar Item Number Between 0 And Length Dayare Parents Usse Milne I'm Doing The Calling subscribe and subscribe the Channel subscribe On Thee Karo Baje Shopping Amazon Increments Jasveer and Change and Returned and the Return of the Rebel to Call Thursday Subscribe 30 Track Wale Sudhir What is the Function of Mid Day Meal Loot Obscene Dance Will Work This is a different approach Return of target.radheshyam ko Return of target.radheshyam ko Return of target.radheshyam ko dhundh 100 pranam comment one up the end uses craft safe sex subscribe The Channel Please subscribe and subscribe this Video give a video subscribe construct a it all computer fennel bird flu call one is lighter a flying jatt fight verification refrigerator decide Subscribe to Sleep Share Subscribe to Channel Subscribe Video Subscribe Ronit Dhund in the Overall Time Complexity of Bansal Content Made Available Se Traffic Hour's Time is a S especially The Vote A Great Friend [ __ ] Gets Wrong A Great Friend [ __ ] Gets Wrong A Great Friend [ __ ] Gets Wrong and Electrification and Accounts Anytime Soon They Will Also Taking Oath At Random Tribes Which Was The Use Of The Sentence Appointed For The Random Take More Time With Veer Subscribe Quick Tank Elections Laddu Put On Speed Come Here Durgesh Singh Switch Size Declaring Space Witch Saw In Tracks Against Vote Bank Voter Space Complexity Indian Tele Awards Complexity And Difficulty Of Rights Over Time Job School Suhavani Element Click That Bigg Boss Total Number Of Elements Will Be Easy To Come In This Barrel District Here All Due Credit The Subscribe All The Best but Thursday subscribe I am particularly informed and have defeated in the hospital quarter and space suit total time complexity chief send a different for different subscribe and subscribe the Channel Please subscribe and Share and subscribe the how to get away positive you can get the land from description section of this video thank you for watching my with another problem very soon in the state and good bye a
Random Pick Index
random-pick-index
Given an integer array `nums` with possible **duplicates**, randomly output the index of a given `target` number. You can assume that the given target number must exist in the array. Implement the `Solution` class: * `Solution(int[] nums)` Initializes the object with the array `nums`. * `int pick(int target)` Picks a random index `i` from `nums` where `nums[i] == target`. If there are multiple valid i's, then each index should have an equal probability of returning. **Example 1:** **Input** \[ "Solution ", "pick ", "pick ", "pick "\] \[\[\[1, 2, 3, 3, 3\]\], \[3\], \[1\], \[3\]\] **Output** \[null, 4, 0, 2\] **Explanation** Solution solution = new Solution(\[1, 2, 3, 3, 3\]); solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(1); // It should return 0. Since in the array only nums\[0\] is equal to 1. solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. **Constraints:** * `1 <= nums.length <= 2 * 104` * `-231 <= nums[i] <= 231 - 1` * `target` is an integer from `nums`. * At most `104` calls will be made to `pick`.
null
Hash Table,Math,Reservoir Sampling,Randomized
Medium
382,894,912
573
hey everybody this is Larry this is day uh week two of the Leo daddy weekly premium challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's prom squirel simulation B I haven't done before uh yeah I'm still in Hiroshima uh today um if you watch my daily video you'll see the intros kind of did I took a nap and I just woke up so I think like it's not really I don't know I didn't really go over his background but I would say I um started a new relog channel uh of my journey in Japan uh if you want to check that out let me know and I'll put in the comments below uh yeah uh it's a it's very new it's a little bit rough around the edges but I'm still playing around with it anyway today's PO is 573 squirrel simulation let's see given two integers height and width you're given tree you go trees do nuts at these places groc should go to nuts first um okay so H this could be a tricky problem so basically you have to collect all the nuts but you can only hold nut one nut at a time so you go to I so this squirrel goes to a nut go to the tree and then goes to another nut and goes to the tree and so forth uh the first thing I look at is kind of look at how many nuts there are and nut is 5,000 huh because to be honest initially I thought possibly it could be one of those NP problems meaning like you know like a variation of travel traveling sales person stuff so when you look at constraints sometimes it's a little bit of a giveaway um because you're like you know but I think this one is maybe more straightforward I think they are just like a it's a case analysis because basically okay you have the starting point which is the squirrel but other than that you literally just you're at the tree after every nut so then after every nut you're going from the tree get another nut it doesn't even matter at that per Which nut because you have to go to Every nut one at a time so that means that the only differentiating Point here for this problem is which is the first nut that you go and then go to the tree afterwards so I think we can calculate it calculate that basically yeah we can just calculate that boo Force for all of them and of course you have to be careful because if you're not careful you could do an N Square which for 5,000 you could do an N Square which for 5,000 you could do an N Square which for 5,000 is getting a little bit sketch at least in Python on Le code but yeah so okay so let's say let's start coding I think that's generate idea you could do in linear time I believe uh unless my idea is wrong but basically the total is just going to be uh like I said from the tree to every nut right so that's not the best total but that's the total of all the distance between the nuts and we can calculate um I'll show in a sec but we can calculate the total for starting at each nut by subtracting this from it or that from this number right so for XY and nuts maybe NX n y for nuts X and that'ss Y uh and I like maybe just TX Ty y for 3x3 y isal 3 right so we add NX minus t TX plus right so that's the total distance right and then now we can boo Force each nuts in that okay so there may be multiple ways so I don't have to kind of see but let just say best is you go to uh I don't know just Infinity right I'm not going to assume anything that makes it easier to not assume anything but then now so here uh go to nut then tree right yeah is there any other way I guess you could go to the tree first but I that always will because this is Manhattan distance um it doesn't ever make it any sense okay so go to nut then tree right so uh let's also say sxs y your squirr so sxs maybe I should win like a distant form little bit uh but yeah right not treat to not all right so this is the distance and then plus uh from the nut to the tree actually I guess in this case oh this is wrong oh this is insufficient right because from the nut to the tree and then you have to go back so this is two times this that's why I was like something's f a little off right so this is the total because now it's the distance starting from the tree to every price right so then now this is going for a nut then tree so NX minus TX uh why do I have a minus here right so this is that and then now D plus total is going to be the entire thing except for you double count it uh so then now it is actually minus this be because now we triple count it I guess so actually we can just REM um I think just remove this and then do this and that would be fine maybe I'm off by one or something I don't know I'm always off by something and then yeah and then now we could minimize this and that right let's give a spin should of n so it shouldn't be timing out uh let's give it a spin let's give a submit all right yeah um this is linear time constant space uh I'm going to draw it real quick but basically uh because I wanted to make sure a little bit that I get it right first to be honest but uh but basically the idea is that okay so now you have a sort of a manhand distance minimum spanning tree right uh so you know you have this node and then uh you know it goes to some other nodes uh I need a drawing thing I'm drawing with the touch pad and this is like annoying right but the idea here is you know and that one is terrible actually so you could just reduce this to this right this is the man hand distance and uh and you know pretend there more because it's very hard to draw as you can see uh for me here because I don't even have my Mouse um and the idea is that let's say your scroll change the color let's say your scroll basically the idea is that now you're going to you're testing boo Force going to a node and then and because you already did the math for this path times two you know that's the way that we did it now we can just kind of you know do the math with respect to subtracting out what we haven't done and stuff like that and because we've done that then we can do it for every um trying to remove this real quick oops that yeah you could do that for everyone uh every night and this is going to be just linear time as you can see um yeah that's all I have for this one it's uh it's a cute problem I dig it's uh it's a good thinking problem so yeah uh let me know what you think hit the like button hit the Subscribe button join me on Discord let me know what you think about this problem I'll see yall later and take care bye-bye right
Squirrel Simulation
squirrel-simulation
You are given two integers `height` and `width` representing a garden of size `height x width`. You are also given: * an array `tree` where `tree = [treer, treec]` is the position of the tree in the garden, * an array `squirrel` where `squirrel = [squirrelr, squirrelc]` is the position of the squirrel in the garden, * and an array `nuts` where `nuts[i] = [nutir, nutic]` is the position of the `ith` nut in the garden. The squirrel can only take at most one nut at one time and can move in four directions: up, down, left, and right, to the adjacent cell. Return _the **minimal distance** for the squirrel to collect all the nuts and put them under the tree one by one_. The **distance** is the number of moves. **Example 1:** **Input:** height = 5, width = 7, tree = \[2,2\], squirrel = \[4,4\], nuts = \[\[3,0\], \[2,5\]\] **Output:** 12 **Explanation:** The squirrel should go to the nut at \[2, 5\] first to achieve a minimal distance. **Example 2:** **Input:** height = 1, width = 3, tree = \[0,1\], squirrel = \[0,0\], nuts = \[\[0,2\]\] **Output:** 3 **Constraints:** * `1 <= height, width <= 100` * `tree.length == 2` * `squirrel.length == 2` * `1 <= nuts.length <= 5000` * `nuts[i].length == 2` * `0 <= treer, squirrelr, nutir <= height` * `0 <= treec, squirrelc, nutic <= width`
Will Brute force solution works here? What will be its complexity? Brute force definitely won't work here. Think of some simple solution. Take some example and make some observations. Will order of nuts traversed by squirrel is important or only first nut traversed by squirrel is important? Are there some paths which squirrel have to cover in any case? If yes, what are they? Did you notice only first nut traversed by squirrel matters? Obviously squirrel will choose first nut which will result in minimum distance.
Array,Math
Medium
null
36
let's take a look at number 36 that is Sudoku the problem solving algorithm problem is not just you we should be able to solve the problems by writing a code but we're also required to explain our thoughts so I find that it fine creating this YouTube channel and recording these videos is a it's very helpful to me to explain myself so when during the interview I would let the interviewer understand why I did this and what's my what is my thought and yeah I strongly encourage you to do the same to speak aloud when you're writing a code okay number 36 that is Sudoku yeah determine if it's fat only the field cells need to be valid so this is a board nine each row must contain the one nine without repetition yeah also column without okay so the small cell three sub box but also without repetition so like this is the input format of this board your thought means empty so it's true because no one not no numbers it is replicated in this box or in this column or in this row a pseudo Gabor could be valid but not necessarily solvable so yeah only the field cells need to be valid it so we don't need to check whether this board is valid but only check the repetition oh it's very simple actually we could do this with brute force just with one-pass to check the roll one pass to one-pass to check the roll one pass to one-pass to check the roll one pass to check the column one pass to check the rhythm the sandbox so with three passes route force with three passes wow this would be oh well there's no cus the size is fixed so with three passes and would be lying nine three actually during a three passes though first we look through this row and check if this Row is unique it has only unique numbers and check this one and then check the lock column it seems that we can check the row and the column and the sub box at one pass right let's improve it to one pass yeah for that we need to check for like we are we're meeting the number five we need to check if five exists in this row three exists in this row six existing in this row so we can create yeah we can use a rate to store the existence right so we create you used I'd like say is used the first one is new a new array nine okay in row because is used in kaanum we use this three array to track the existence occurrence column new array no cost is used in sub new array this will be three eight one two three oh yeah it's still that my okay for now we traverse through all the notes or the point because it's fixed to fix tonight we just nine now if is used in row just check if it is check this number is if it is duplicated if it is we return right away return false and after that if we did not exist we just update to update the three array right it's pretty straightforward which is four PI J we cache it word i J undefined or zero Bo's Falls is in JavaScript so if it's used in row or it's used in column oh wait a minute it should be there in the index so this I ya know or is using sup this one is not I a sub box index equals 1 0 1 2 3 4 5 6 7 8 right put the index 3 B 1 2 3 2 1 2 3 4 5 3 plus 3 okay so this should be math.floor I divided by 3 should be math.floor I divided by 3 should be math.floor I divided by 3 right this is 1 0 1 2 3 this is 1 okay and + math.floor J divided by 3 like and + math.floor J divided by 3 like and + math.floor J divided by 3 like this is for here the J should be 2 + and this is for here the J should be 2 + and this is for here the J should be 2 + and divide times 3 I think so for these here J should be 2 times 3 6 + 6 + u should be 1 right so it 6 + 6 + u should be 1 right so it 6 + 6 + u should be 1 right so it should be 7 0 1 2 3 4 5 6 7 ok that's right so this is sub box index No we return false and update them now update them into true update this true and finally we turn true and submit it should you should work right it's really straightforward no it is not cannot read properly five-on-one define well defined Oh God oh my bad ah my bad in JavaScript you array you will be aren't defined so there's it's no paw it's not possible to do this how we can how can we do this we just map item actually don't just use this thing okay so new array this will give us a rape in rate so give us the matrix still no work problem is let's say new array 9 Mac new array MC white empty Oh God canapé map okay three you let's fill z0 this should be okay empty cannot be used to map because this is there's no active empty it there's no item there mmm-hmm what okay no it's item there mmm-hmm what okay no it's item there mmm-hmm what okay no it's right this is right and this is right it's used okay which are false console.log you should which are false console.log you should which are false console.log you should say I J it's used i it's used sub box oh my god okay the index is zero three ah oh we forgot the empty character my bad sad interviewers well I picked this on me I think wow this matter still it's still okay this is three four six yeah a second one no and then Phi here five nine okay five six AHA Shetty's you economist you BJ yeah my big wow I'm really not good at algorithms I tried the brute force yesterday and I say LK I can't finish this by improving the for-loop improve the improving the for-loop improve the improving the for-loop improve the traversal but I made a yeah it look like my look at my submission I failed four times this is a fifth time okay it passes finally okay this is over this for this one I just pay more attention yeah when you do traversal say next time bye-bye
Valid Sudoku
valid-sudoku
Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**: 1. Each row must contain the digits `1-9` without repetition. 2. Each column must contain the digits `1-9` without repetition. 3. Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition. **Note:** * A Sudoku board (partially filled) could be valid but is not necessarily solvable. * Only the filled cells need to be validated according to the mentioned rules. **Example 1:** **Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\] ,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\] ,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\] ,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\] ,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\] ,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\] ,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\] ,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\] ,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** true **Example 2:** **Input:** board = \[\[ "8 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\] ,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\] ,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\] ,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\] ,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\] ,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\] ,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\] ,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\] ,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** false **Explanation:** Same as Example 1, except with the **5** in the top left corner being modified to **8**. Since there are two 8's in the top left 3x3 sub-box, it is invalid. **Constraints:** * `board.length == 9` * `board[i].length == 9` * `board[i][j]` is a digit `1-9` or `'.'`.
null
Array,Hash Table,Matrix
Medium
37,2254
1,403
yeahyeah Hello everyone, I'm a programmer. Today I will introduce to you a problem titled minimum substring in sorting. This is descending sorting, right? Don't say that it's not ascending, it means sorting in descending order. Okay, the detailed problem is as follows, giving us an array of integers, a string called the subsequence of a piece when the sum of all elements is In that child's owner is greater than the sum of all the remaining elements in age, then people will call it a child bit, then this lesson will call it a child's one if there are many ways to choose the letter. This child element, then we will return the child element with the size with the least number of molecules. Yes, if there are still many ways to choose this child element, then we will have to return this child element. The child owner with the sum of the elements in the age is the largest . And here we have an . And here we have an . And here we have an example and a definition of the child's , the child can practice Thanh's by doing , the child can practice Thanh's by doing , the child can practice Thanh's by doing we Delete the The element in the fragment goes to form the subletter I am which has a caveat that the solution will be guaranteed to be unique and will have to be presented to the screen with a reduced arrangement. Gradually, now we will go into example 1, showing that in one you see there is 43. We have a piece with 5 elements of 43 19 85, then for these arrays we see that there will be 22 parts. The element is the part to form a child's age that meets the requirements of the question: 19 lesson 18 because in the of the question: 19 lesson 18 because in the of the question: 19 lesson 18 because in the case of 19, you see that ten + that case of 19, you see that ten + that case of 19, you see that ten + that is 19 will be greater than 4 + 3 + 8, right and is 19 will be greater than 4 + 3 + 8, right and is 19 will be greater than 4 + 3 + 8, right and in the session? is 18, then it will be larger than 4 + 3 in the session? is 18, then it will be larger than 4 + 3 in the session? is 18, then it will be larger than 4 + 3 + 9. + 9. + 9. In school lessons, there are many ways, so I say we have to choose the wrong minimem. That is, the size is the minimum ruler, then these two arrays will have the same view. if the size is two then continue and I have to choose the piece that has the largest sum, you see 19 18 then I will choose 19 20 plus 95 19 big 18 sweet and remember I have to return the result which must be The ha is arranged in descending order. Is the number 10 coming first and the main number next? Well, through example 2, we have a piece with 5 elements of 4 7 6 7. We see that to have a child age. form and is greater than all the remaining elements, then I have to choose 76 77 + 6 remaining elements, then I have to choose 76 77 + 6 remaining elements, then I have to choose 76 77 + 6 + 7 which is 20 which will be greater than Four plus four ha + 7 which is 20 which will be greater than Four plus four ha + 7 which is 20 which will be greater than Four plus four ha Yes but Honey I can't choose which one has two elements to get two The largest element is 7 plus 7 which is 14 but Four plus four plus 6 is as big as 14 and it's not bigger like it you can't do like that I will return the pair it must be six seven but remember Do I have to rearrange it to 776? And for example 3, this fragment only has one element like a crocodile, so it follows that the returned result is also bad and the arrangement itself is it now. We will think a little about your algorithms. Well, to solve these problems, we first have to calculate the sum of all the elements in the array ha, but now Now let's take the first example as a model. Now the sum of all the elements in the solution for example 1 gives it 4 + 3 + 10 plus 9 + 4 + 3 + 10 plus 9 + 4 + 3 + 10 plus 9 + the number 9 + 8 is equal to seven 17 26/2 the number 9 + 8 is equal to seven 17 26/2 the number 9 + 8 is equal to seven 17 26/2 634 326 Is it 3 4 HA? Here I can easily calculate it. There is an algorithm that can easily calculate the sum of all the elements in the array, right? After that, I have to reduce the number. Next, I have to sort it. Again, I have to arrange these arrays, so to arrange them conveniently when I export them to the LED screen, I should arrange them in descending order, which means I will arrange the pieces into 19 8 3433 As you can see, sorting in descending order means that the first element will be the largest element, then the second largest element, the third largest, the fourth largest, and the last largest after we have sorted. As for the network, we will have to have a filter loop to check to get from the beginning to the end of the piece. In each filter, in each setup, we will do whatever we want, we will take the largest value. Hey, we keep it and we compare this value of 10. Is it greater than 34 - 12? Why are we - 12? Why are we - 12? Why are we comparing 34 - 12? Because 34 - 10 comparing 34 - 12? Because 34 - 10 comparing 34 - 12? Because 34 - 10 means it represents the sum of All the remaining elements are the right number because I will calculate the total from the beginning when I calculate the sum from the beginning. The sum of the dog's paw sentence, the sum of the molecules, is the focus of his organization so that in this case, October is no greater than 30 - 10, which is inferred as phone. than 30 - 10, which is inferred as phone. than 30 - 10, which is inferred as phone. So I continue to run the program as I run it until there is a second part, a stay at the piece of love, look far away, then now go mine, it runs second to the second element of the fragment then now my one person that is the sum from the y that returns It must be ten dregs for the main, let me check to see if it is greater than 34 - 10 - 90. I is greater than 34 - 10 - 90. I is greater than 34 - 10 - 90. I have to calculate it later. So if 8 + 4 + 3 have to calculate it later. So if 8 + 4 + 3 have to calculate it later. So if 8 + 4 + 3 is equal to 3 4 -10 - the main is equal to 3 4 -10 - the main is equal to 3 4 -10 - the main is definitely Now I think this is not the same or this now I see that it's true that ten is bigger than 34 - 10 is 24 - that's bigger than 34 - 10 is 24 - that's bigger than 34 - 10 is 24 - that's 15 which is ten eggs and bigger than 15 divided By taking a photo, when this calculation is equal to the time, I will stop here and I will return the correct numbers on the front. Yes, it is probably the number 10 and the number 9 and now I have already arranged it. After arranging it will radiate according to the requirements of the topic . I think you can understand . I think you can understand . I think you can understand the math part. Now I will proceed with the test installation using the Roland reader language and then I will proceed with the installation. As follows, I will declare one to three yes with a resort phase and also see why it is a heavy integer number. The round will return why and then in this process I will calculate to find the following job first: I will do it like step 1, first: I will do it like step 1, first: I will do it like step 1, but I will calculate the total of all the elements in the machine. I declare a variable, then at first I set it equal to Phong. Then I have to declare a loop to make Ford know how to run it again. Going from beginning to end, the piece Minh and Y gradually increase by one unit then we will each time we build we will weight the results of the veterinary year in tattooing Well what about when you guys study it's over then we will get Spring's gate the sum of all the elements of this table in The next step is we have to sort the initial piece and in descending order to arrange it as an integer array. There is a descending order in Cola, there is a Phuong, which means the drop has a dot like function, it will help us compose, first we pass to the piece when we need to sort, then we must pass Into a field fan we will pass a method and a function to indicate which way to split. I will declare it inside, the first element is called when I will What is the second thing called and I have to report that the sound is only on TV or in the piece I'm pointing at now. Every time and after that I have to report the tree increasing jaw in this place then get it in this section and I'll return it sour phone then chu When I want to sort in descending order, so Choose when the year network y is bigger than what year Goodbye Y will be the front element and jc is the deep element so the result is that y is larger Fuji is Chu which means it will arrange in descending order of real awareness. Why, after completing this step, our tray will be a piece arranged in descending order ? Now we will have to Go ahead and ? Now we will have to Go ahead and ? Now we will have to Go ahead and declare a final classroom, then put it in this last potion so we can keep the sum on the left side of the run variable. For example, here is 10, for example, here is 19, then we should declare it. A variable I call a temporary sign, but now I will report a circle around the same. The dog goes from Big to the filters, so I should declare the sound that runs back to the small heart. Then Now, the first thing I'll do is when I've sorted it out, I'm sure this guy will be one of the guys that has to be drawn in this result, so I have to say cannot go into something later. Don't say anything about it, I don't have it. That means I'll add the last one, wife. Can you add the last one that stays in this piece? Now I'm going to calculate the sum of the word y up to the variable. I'm going to calculate the sum of the first element to the vet element by The way is to calculate the name of the source for the company. Okay, now I will proceed with the condition so that I will have the condition to stay in the present tense, which is this gate. This gate in front is a stamp. Is it true? And this temporary sign I will compare and what is the problem with the temporary variable? If this field appears, then what does it mean that I have found all the numbers that satisfy Two in the video and now I will end it? keep getting fatter reading Well, after we run all the way to filter powder, we will definitely run to the edge then surely what will happen next is what we need to return to Hoa Binh Thuy run out If this is the case, you don't have to worry about running through this filter without getting into this spot because they guarantee you that there will definitely be a solution, so why don't we? Having solved the first example, now we will create an account to solve other applications. Yes, you can see that we have solved all other examples of the program. Now I will proceed to evaluate the complexity. The complexity of this algorithm is that it has this algorithm. I call N the number of elements in the integer table here. We have a filter circle. To sort according to the sorting method, you know that its average complexity will be kenlloggs and a final filter will return em times but usually it cannot be brought back to it. very long ago But I also consider it as the time in school when I noticed it, I will take the most valuable and highest of the three with these three actions of mine then my sister died and I helped her then I will be big is me Lock And I Yes Then the next step we evaluate the storage space complexity of this storage space we see that we have a variable size variable according to the number of elements in the array Yes, but actually, it is rarely equal to the number of elements in example 42, example 3. You see, make this element equal to the lattice element and the number of thin elements, so here it is. We are both you too Anh Ngoc Okay So I will end the video here. If you find it interesting, please give me a like, sub, like and share the experience. If you have any questions or suggestions or a solution. better than the original and the comments section below And Thank you for watching the video Thank you and the product ah yeah
Minimum Subsequence in Non-Increasing Order
palindrome-partitioning-iii
Given the array `nums`, obtain a subsequence of the array whose sum of elements is **strictly greater** than the sum of the non included elements in such subsequence. If there are multiple solutions, return the subsequence with **minimum size** and if there still exist multiple solutions, return the subsequence with the **maximum total sum** of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. Note that the solution with the given constraints is guaranteed to be **unique**. Also return the answer sorted in **non-increasing** order. **Example 1:** **Input:** nums = \[4,3,10,9,8\] **Output:** \[10,9\] **Explanation:** The subsequences \[10,9\] and \[10,8\] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence \[10,9\] has the maximum total sum of its elements. **Example 2:** **Input:** nums = \[4,4,7,6,7\] **Output:** \[7,7,6\] **Explanation:** The subsequence \[7,7\] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence \[7,6,7\] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-decreasing order. **Constraints:** * `1 <= nums.length <= 500` * `1 <= nums[i] <= 100`
For each substring calculate the minimum number of steps to make it palindrome and store it in a table. Create a dp(pos, cnt) which means the minimum number of characters changed for the suffix of s starting on pos splitting the suffix on cnt chunks.
String,Dynamic Programming
Hard
1871
844
hey everyone welcome back and let's write some more neat code today so today let's solve the problem backspace string compare we're given two strings SNT and we want to return true if they are the same string but there's a catch here we can't just do a basic string compare because there is a special character the pound sign and this counts as a backspace character so let's take a look at this first example so this string here is not going to evaluate to AB pound see it actually evaluates since this counts as a backspace it's going to delete the nearest character or you could even think of it like a stack pop operation if we were iterating through this string from left to right but that would basically be the a then we add the B then we pop the B so we get rid of it and then we add the C and we end up with AC this string will actually become the same string here even though there's a d character here and this one had a B the D is going to be deleted so we have an A then we have a d then we get the pound it removes the D we get rid of it and then we end up lastly with a c so that we find that these two strings actually are equal to each other so I kind of just mentioned how to solve this problem actually we are going to convert each string to its real representation without the pound sign and the easiest way to do it is to iterate through the string from left to right and maintain each character in a stack every time we see a pound character we pop the most recent uh character in the stack if the stack is non-empty it looks like we can stack is non-empty it looks like we can stack is non-empty it looks like we can add Backspaces like we could even start with some Backspaces I guess in the string and not have any characters here in that case the Backspaces don't really do anything we still remain with an empty string AKA an empty stack so this is one valid way to solve this elak code easy problem I think that's the easy solution for this problem it would be iterating over each string let's say the length of this string has n characters this string has M characters the time complexity of course is going to be n plus M we do have to iterate over both strings and the memory complexity in the worst case could be the same we have to have a stack for each string so that might also be n + m each string so that might also be n + m each string so that might also be n + m now I'm not going to code this solution up because I think it's not super difficult and there actually is a solution the followup for this problem is can we optimize the memory complexity can we actually solve this in O of one memory and that I will say probably isn't an easy problem to be able to solve this in constant memory but the solution isn't super difficult now let's think about this without saving anything without having a stack how could we do this by iterating from left to right let's say we're trying to do the exact same thing we're trying to convert this into its real representation AC how would we do that we can't really do it from left to right because let's say we're not even trying to actually like build an extra string we're just trying to actually compare it character by character like we want the first valid character from this string so that we can compare it with the first valid character of this string we don't know like going at the beginning we have no idea is this actually going to be the first character because for all we know there might be a bunch of like pound signs that come after it that end up deleting this character so we really don't know going from left to right are these valid characters or not because the pound in this case is going to delete in that direction notice how the pound is not deleting anything to the right of it only deleting things to the left of it so knowing that the first thing you would try without even knowing what the solution is the first thing you should try is okay maybe we can iterate through the string in the other direction this is a very common technique that can be applied to a lot of problems just because iterating from left to right doesn't work doesn't mean we can't try the opposite we can't try going right to left and sometimes when that doesn't work you end up with two pointers maybe initialized at the edges of the array or maybe something like a sliding window those don't apply in this case but I'm just trying to give you some suggestions for when you're stuck on a problem you can just kind of try things and see if they work or don't work but in this case we go in the opposite direction what we find is we know for sure looking at the last character that this is a valid character because yeah there might be some pound signs to the left of it but those pound signs are not going to delete this character they're only going to delete characters to the left of it so when we are looking for the last valid character in each string that's something we can actually accomplish so that's what we do get the last valid character from each string and we find that they are uh the same so then we shift our pointer now we're going to take the pointer here and we find that it's a pound character so what that just tells us is just move one more spot to the left move these pointers to the left by one so now pointer here and pointer here but that pound sign told us not only to shift like we're not just going to skip every pound sign but we're also going to keep track of it because that's going to tell us that now we can actually skip this character as well we have a count of one here and a count of one here in terms of like the pound signs that we've seen so we shift each pointer by one once again now we end up at the a character we find that these two are equal so far the strings are still the same we shift these pointers out of bounds and then we're done when both pointers go out of bounds we know that the strings are equal because we found that every character we compared was equal and now both of the pointers are out of bounds but suppose that this string actually had another character like there's an X over here but this pointer is out of bounds do you think these two strings are equal probably not this one still has characters this one doesn't have anything so we will have to account for that in our code but that's the idea here notice that the solution basically relies on having two pointers initialized at the end of each string and basically just shifting them in the opposite direction and every time we find a new valid character We compare the two strings so now let's code this up there's multiple ways you can think about this problem the way I'm going to do this actually is with a helper function like I said we want the next valid character for every single string and if we're doing that for both strings we can kind of uh D duplicate that code so we can make this a function it's going to be passed in a string I'm going to call it uh Str or maybe I should just do s but I don't want to like conflict with this but we'll stick with Str and we're also going to be given the index of the string that we're currently at the reason for that is basically like starting from like the end of the string we want to be able to find the next valid character and then the next time we call this function we might be in the middle of the string so starting from there we want to find the next valid character but that's what this function is about so what we're going to do to find the next valid character is of course we want the index to be in bounds so while the index is greater than or equal to zero let us find the next valid character and we're going to use this same pointer and that's ultimately what we're going to return as well now on every iteration of this Loop we are going to take our index and decrement it by one well almost every index because there is one case where suppose that in this string the index or the character is not equal to the pound in that case we do not want to shift the pointer that means we're at a character that's not a backspace and that is the next valid character so we just break out of this loop at that point and then just return the starting index we would not have decremented it at all in that possible case but otherwise we want to count the number of Backspaces so suppose else if that this character actually is a backspace or the pound sign in that case we want to count the number of Backspaces CU we could have mult multiple consecutive Backspaces so I'm going to have a variable that I'm going to increment it's going to initially be set to zero and we're going to increment it on each iteration of the loop and that also reminds me that in this case we could uh be at a point where yes we're at a nonb backspace character but the number of Backspaces is not equal to zero it's greater than zero so we would only want to break if the count was set to zero we have no Backspaces and the character is a is not a pound therefore we break out of this Loop the other case is that we do see a pound in which case we increment the count by one and the last case we don't even need to name the condition like we don't need to specify the condition here because if we know for sure this did not evaluate and we know that the character was not a pound that means it was a non- pound that means it was a non- pound that means it was a non- pound character of course and we don't really need to do anything in that case but we are going to decrement the number of Backspaces cuz we're skipping over that character and we're only going to execute this if backspace was greater than zero so that's kind of how I'm reasoning about these conditions there might be a more intuitive way to write these you can definitely write it a different way if it makes more sense for you but ultimately this is the logic here anytime we see a pound we're going to accumulate the Backspaces if we see a non- pound character we're going to non- pound character we're going to non- pound character we're going to decrement the Backspaces unless the number of Backspaces is equal to zero and we see a non- pound then we just and we see a non- pound then we just and we see a non- pound then we just break out of this so once you do that we've more or less solved the problem at this point we're going to have the two pointers I talked about I'm going to call them index s and index a t you could also do I and J that's what I usually do but we'll keep it a bit more intuitive this time and they're going to be these pointers are going to be initialized to the end of each string and then we're just going to have our TW pointer algorithm so I'm going to have a while loop here for now I'm not going to specify the condition but basically we're going to call next valid character for each of these strings for S passing in index s which is going to be initially at the end of the string and doing the exact same thing for the T string index T and what these are going to return to us are not the characters they're going to return the index and I did that intentionally because what if the index was out of bounds what if the index became less than zero well that's something we're going to have to handle here so we're going to take these and reassign the indices and we want to of course compare the characters we want to compare s of index s is it equal to T at index T and if they're not equal that's actually the more important case that's when we would return false but we know we might get an index out of bounds error like this so what I'm actually going to do here is have a couple variables I'm going to call it character s and the way we're going to get that is a Turner operator I'm going to do something a little bit clever here and that is this is going to be assigned to index uh s at index s if the index is greater than or equal to zero basically if it's in bounds and if it's not in bounds I'm going to give it a default value here I'm just going to give it an empty string to basically indicate that this was out of bounds I'm going to do the exact same thing for T So character T is going to be in string T index T if it's in bounds otherwise it's going to be empty now we don't have the risk of an index out of bounds error here we can replace these like this so that's just like the intuitive way that I like to do it so we don't get any like crazy uh error but that's the thing we're going to be looking for if they are not equal or if one of them went out of bounds of course this will evaluate to false it will return false and otherwise we're just going to take the pointers and decrement them each time just like this and if we were to reach the end of the loop or basically another way to say this is if we were to have one of the strings go out of bounds or the characters are unequal we know for sure this is going to return false but if that was not the case we would probably want to return true out here so last thing is what is going to be the condition for this well if we were to find unequal characters or one of the pointers go out of bounds we would definitely want to return false here so we want to be very sure by the time we get out of this Loop that the strings are equal for us to do that we are going to ensure that the pointers are in Bound so the first pointer is in bounds and the second pointer is in bounds but this actually does not cover one of the cases the reason we need to change this and to an or is because what if one of the pointers went out of bounds but the other one didn't go out of bounds we would want to return false in that case and that's only going to happen with these lines of code so that's why we put the or here if one of these goes out of bounds we want to return false and we do that in the loop instead of outside here so this is the entire code so now let's go ahead and run this to make sure that it works as you can see on the left yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out NE code. thanks for watching and I'll see you soon
Backspace String Compare
backspace-string-compare
Given two strings `s` and `t`, return `true` _if they are equal when both are typed into empty text editors_. `'#'` means a backspace character. Note that after backspacing an empty text, the text will continue empty. **Example 1:** **Input:** s = "ab#c ", t = "ad#c " **Output:** true **Explanation:** Both s and t become "ac ". **Example 2:** **Input:** s = "ab## ", t = "c#d# " **Output:** true **Explanation:** Both s and t become " ". **Example 3:** **Input:** s = "a#c ", t = "b " **Output:** false **Explanation:** s becomes "c " while t becomes "b ". **Constraints:** * `1 <= s.length, t.length <= 200` * `s` and `t` only contain lowercase letters and `'#'` characters. **Follow up:** Can you solve it in `O(n)` time and `O(1)` space?
null
null
Easy
null
1,865
hello guys welcome back to the channel today we are solving another lead code problem that is 1865 finding pair with certain some I would highly recommend before jumping into the solution you should read the problem statement on your own and give at least 15 to 30 minutes to this problem let's get right into it what problem is asking you need to implement two function one is add second one is count for add you will be given a certain index and at that index you have to add some constant positive constant given by the problem itself or given in the query and one thing also that where you have to add this constant its nums to and for the count what you have to do is you have to find the number of pairs i j which satisfy this condition nums one plus nums oh J is equals to a constant you have to find these number of pairs which follow this condition that is very much clear so let's take a test case and understand for the very first call uh or nums one nums 2 are given so let's write nums one this is our nums one let's write nums two five four nums to second is count we have to count the pairs and the constant given is 7 so we have to count I and J which sums to 7. that much is very clear so these three we can take again these three we can take how many six these two with this three plus two eight so this much is clear how count is working and if we see add in add you are given 3 2 you have to add this at third index plus 2 where in the nums 2 so let's write the nums to 4 and 0 1 2 3 4 5 at the fourth no at the third index plus two so what we will do is again write it now when again you have to count you have to use this nums too so that much is clear not running for other cases this much is clear let's move ahead also there is one thing you should keep in mind that numbs one is around 10 00 and nums 2 is around 10 to the power 5. you will understand the significance so if you have done enough lead code problems you know if you something see something like this how to tackle this there are two things you cannot handle two things at one time how to handle this we can do this nums J is equals to constant minus nums I why we did nums minus I this is the reason as we are doing 1000 calls written in the problem statement you should read when at the constraint you will be able to process 1000 only so what to do so we will take this and while solving this kind of problem you have to store it in something place that place you know hash map so that's why it's quite a large size that's why it is stored in the hash map and this one is true and this nums eye is used while doing the calculation if you didn't understand this if it is your very first time that how hashmap just came hashmap is like the history or not the history that after subtracting this we have something if we have something counted as a pair because you can handle one thing at a time and that thing is your nums I and if constant minus nums I am and if it is present in your nums to whatever it is it's nums 1 numbers 2. whatever it is if it is present in nums 2 then nums I plus nums 2 will equal V to the constant so it's very obvious thing but I did explain it again so what we will do is we will just store let me write the algo what we will do is hello store nums to in hashmap for obvious reason because it's also a large in size and tend to and 10 to the power three calls are made and we can only calculate 10 to the power 6 in one second so that's why we have to take nums one and we have to store nums too we fill the nums 2 in the hash map and for ADD you have to handle that while adding and subtracting you have to update the nums too also so update nums to also the map and another thing that you have to do is while calculating it's very easy you have done plenty of times that what to do if with me for count what we will be doing is we will see if constant minus whatever nums one I present if present we will add it if not present then nothing to worry because it was not up here if it is present we will add it if it is not present then nothing can be done because it's numbs too and if you have a doubt that in previous question we used to have one and we just used to plus sit if you have done previous question in this question it's different that's why I have taken this question as you can see for yourself while we are making this pair we are able to count all because for example if map of while we mapped nums to in the hash map two would have three and five How many pairs you can make with three twos and one five is three pairs so we don't need that calculation that we increase this pair before that's not required it was required in previous question if you have done count the bad pairs it was required there it was different here it is different that's why I've taken this question so I hope I was able to make you understand it this was pretty much the elgo uh let's see if we can dry run it yeah try let's try dry running it let's copy over from there copy one let me see the time nums one is the first this is the nums 2 3 nums one and nums two horrible writing comes to one four five two five four yeah put it in the map hash map one is one times 4 is how many times 4 is 2 times 5 is how many times that is also two times I also two is one time so that's it and when the count occurs in the count Docker what is given seven the constant so let's do it less than minus 1 6 is 6 there and minus 1 6 is it there no so n minus 1 6 is it there no 7 minus 2 5 yeah it is there let's again do it send for sorry for the blank out seven minus two five it's still there yeah it's still there then minus two five eight still there yeah it's still there and 7 minus three seven minus three uh so n minus three four it's still there yeah it's still there did we miss something no it we got eight that is our answer now add happens when add happen what happened the nums to this the zero one two three four five at this index three we how much we added two now this jumps to four again we have a count now four is two three and two is now down to zero and when this time counts happen what is given eight minus one seven not present seven again seven not present eight minus two sticks it is still not present again not present eight minus three five yeah it is present this time how much we get is to and yeah we are getting two over here again account happens this time what we are given is four we are given four minus one three is not present this is the mash map if you are not able to see four minus 1 3 not present four minus 2 was present but not currently not present and four minus three one is present so what we get in this case is one so here it is your one and you guys you can do it add you have to just update this and this you can do it quite time taking I hope I made you understand the intuition the algo and the flow of the problem let's see the code I don't want to make this a long video so let's see it an ordered map as discussed why we made this because it is not made globally available so that's why we have to make our vectors assign those vectors and fill the map using which array the nums to array for obvious reason you can see for yourself 10 to the power 5 enter 10 to the power 3 calls are made it will be only manageable when we are using nums 10 to the power 6 call will be made that will be very manageable not with nums too this is ADD while adding I explained you have to decrease that frequency increase the new frequency and also update the or array too that's what we did this is our basic Counting what we are doing over here is we are iterating over nums 1 and if we see if constant that constant is t o t given over here if constant minus the nums 1 or array 1 if it is present we just add it why we just added not like previous problem I just discussed it and after doing that just return it let's see if it is submitting or not it should get submitted yeah it is accepted so I hope I was able to make the intuition very clear and I hope you were able to understand something so if you were so please consider subscribing to my channel and liking this video so you have to do what you have to do so keep grinding you guys are awesome see you in the next one bye
Finding Pairs With a Certain Sum
checking-existence-of-edge-length-limited-paths-ii
You are given two integer arrays `nums1` and `nums2`. You are tasked to implement a data structure that supports queries of two types: 1. **Add** a positive integer to an element of a given index in the array `nums2`. 2. **Count** the number of pairs `(i, j)` such that `nums1[i] + nums2[j]` equals a given value (`0 <= i < nums1.length` and `0 <= j < nums2.length`). Implement the `FindSumPairs` class: * `FindSumPairs(int[] nums1, int[] nums2)` Initializes the `FindSumPairs` object with two integer arrays `nums1` and `nums2`. * `void add(int index, int val)` Adds `val` to `nums2[index]`, i.e., apply `nums2[index] += val`. * `int count(int tot)` Returns the number of pairs `(i, j)` such that `nums1[i] + nums2[j] == tot`. **Example 1:** **Input** \[ "FindSumPairs ", "count ", "add ", "count ", "count ", "add ", "add ", "count "\] \[\[\[1, 1, 2, 2, 2, 3\], \[1, 4, 5, 2, 5, 4\]\], \[7\], \[3, 2\], \[8\], \[4\], \[0, 1\], \[1, 1\], \[7\]\] **Output** \[null, 8, null, 2, 1, null, null, 11\] **Explanation** FindSumPairs findSumPairs = new FindSumPairs(\[1, 1, 2, 2, 2, 3\], \[1, 4, 5, 2, 5, 4\]); findSumPairs.count(7); // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4 findSumPairs.add(3, 2); // now nums2 = \[1,4,5,**4**`,5,4`\] findSumPairs.count(8); // return 2; pairs (5,2), (5,4) make 3 + 5 findSumPairs.count(4); // return 1; pair (5,0) makes 3 + 1 findSumPairs.add(0, 1); // now nums2 = \[**`2`**,4,5,4`,5,4`\] findSumPairs.add(1, 1); // now nums2 = \[`2`,**5**,5,4`,5,4`\] findSumPairs.count(7); // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4 **Constraints:** * `1 <= nums1.length <= 1000` * `1 <= nums2.length <= 105` * `1 <= nums1[i] <= 109` * `1 <= nums2[i] <= 105` * `0 <= index < nums2.length` * `1 <= val <= 105` * `1 <= tot <= 109` * At most `1000` calls are made to `add` and `count` **each**.
Find the minimum spanning tree of the given graph. Root the tree in an arbitrary node and calculate the maximum weight of the edge from each node to the chosen root. To answer a query, find the lca between the two nodes, and find the maximum weight from each of the query nodes to their lca and compare it to the given limit.
Union Find,Graph,Minimum Spanning Tree
Hard
1815
91
hey everyone welcome back and let's write some more neat code today so today let's solve the problem decode ways so we're basically given a string of integers and we want to know with that string of integers how many different ways can we take that string of integers and decode it into a string of characters and we're given a specific mapping so we have 26 characters and each integer maps to a different character so we have an integer 1 2 all the way to 26 and each of these integers maps to a different character now we don't actually need to build that string that we are mapping to we just have to count the number of different ways we can decode it so down here in the example you can see a string like 12 can be decoded in two different ways one way to decode it is just one and two because one maps to a two maps to b so that's one string but remember we can have double digit values so 12 actually maps to its own character 12 itself maps to 11. so there are two different ways that this string of integers could be mapped to a string of characters so we return two in the output now as you can see it would be very simple if we just had numbers one through nine that map to characters right the problem comes from double digits right from 10 a string like this can be taken in two different ways right 1 0 or just 10 right so that's where the complexity is going to come from a string like this we could have two different decisions so we're going to be using a decision tree to kind of figure out all the possibilities with this at least that's going to be the brute force approach the only problem is that there's going to be a few different edge cases we have to worry about for example we could have a string like this we could have a string like zero six right how what exactly does this map to well zero is not even in our input right basically zero itself does not map to any character right six could map to a character but zero does not so if we ever get a zero you know a string starting with zero that's invalid so we have to return zero in that case this cannot be mapped to any uh this cannot be decoded in any way so we return zero okay let's try to figure out the brute force approach to solving this problem and in doing that we'll try to figure out some of the edge cases that we're gonna have to deal with suppose we have a string like this one two one how many different ways can this be decoded well let's say we start at the beginning right we could take one by itself right that's going to be some character right we don't really care what it is but it's going to be some character now we could also take the first two characters by themselves 12 by itself right because that's valid right so that's another decision starting from here we could take one or we could take 12. and by the way if this was a zero we definitely could not take it then we'd have to just stop immediately right because we can't start with a string starting at zero but if we had something like one zero right a ten maybe then we can take it because it's okay if a zero comes after a one and so basically any integer by itself right one two three four five any integer by itself except for zero can be taken right so basically we can create any string of one you know one number from one through nine except zero right we're just not including zero it cannot be taken by itself but any from one through nine are okay right so what we're gonna see here is okay if we went down this path where we chose a one then the next character we're gonna be at is the two right of course two can be taken by itself right any number except for zero can be taken by itself it can be decoded in that way so when we're at this one or one when we're at this position we can take two by itself or we can take 21 right 21 is also some character i don't know what it is but remember we had values from 1 through 26 right so having a 20 21 is completely fine that will decode to its own character right now of course if we had something like a 27 over here then we could not go down this path right then we just would not go down this path because 27 does not map to any character right so we're kind of learning that you know anything the integers have to be within 1 through 26 right and this 27 is not okay and so down this path we reach the end right we had a 1 and we had a 21 right so there's no more characters to choose from here so basically this was one way that we could decode this input so when we reach the end we're gonna count that as a one right that means we found a single way to decode this input so this was a good base case where we return one and from here let's continue this one so we left off at two then we get to one can one be taken by itself of course again it's not a zero so we can take it by itself and so then we reach the end of the string again so this is another good base case one two one is a valid way to decode this string so if we started with one you know over here we could decode this in two different ways if we start with 12 how many ways can we decode it well if we start with 12 then we just have one character left the one character so that can be decoded another way so this is another good base case so basically we saw that we have three different ways that we can decode this string now just to kind of add a couple values to the string what if we had something like 31 after it so then you know let's say we left off over here you know we can choose the three by itself right because any character except for zero can be taken by itself could we take 31 we could not right the same reason we can't take 27 we can't take 31 because it's greater than 26 right how are we going to determine that in the code you can do it a lot of different ways what i'm just going to say is we can only take double digit values if the first digit starts with a one because if it starts with a one then for the second digit we can take anything from zero to nine right anything from zero to nine because then you know this double digit value will either be between 10 to 19 right and this value is less than 26 so that's perfectly fine but if we start with a two digit then the second digit has to be between zero and six because 26 is going to be less than or equal to 26 but if this became too large if it became a 27 that's not less than or equal to 26 so we can't do that's how i'm going to decide it now what if the first digit started with a 3 you know or a four or a five or anything that's never going to work because if we're going to have some other second digit here it's never going to be less than or equal to 26 right it just won't be so we're only gonna have uh two decisions right we're only gonna have two branches if our first digit is a one or if it is a two so this is kind of the brute force approach that i'm showing you but it might not be super efficient because we could have two decisions at every single position then our time complexity would be something like 2 to the power of n where n is the length of the input string so how can we kind of do a little bit better well notice the sub problem that we're doing for example when we take just 1 by itself and consider okay this is just going to be one way that we decode it then we're asking okay how many different ways can we decode the remaining of the string right that's the sub problem over here we're asking how many different ways can we decode 21 when we take the first two characters 12 then we're asking how many different ways can we decode the string one right so that's kind of how the sub problem is going to work the sub problem is just going to be some portion of the string you know for example you know starting from here all the way to the end of the string how many ways can we decode this or how many ways can we decode the entire thing right to be able to solve this problem how many ways can we decode this we have to solve the sub problem how many ways can we decode everything except the beginning and so basically you know how many different ways can we cache it well we're going to have some index i which could either be here or it could be here it's just going to designate starting from here and taking the remaining portion of the string how many ways can we decode it so basically the dimension of our cache is going to be n right so that's kind of that's also going to be the time complexity because every time we get to a position i at most we have two different decisions to make right so that's going to be an o of one operation making those two decisions it's not like we're gonna have to run through a loop or anything like that we're not gonna have any loops and you'll see that when i write out the code if this is the size of our cache this is also going to be the size of our time complexity and this is also going to be the size of our memory this is because it's the size of the cache now just so you know i think this problem actually can be solved when we write out the actual dynamic programming solution not using a cache not doing it recursively but natural dynamic programming it can be solved with of one memory because one thing you might notice okay when we want to know how many ways can we decode this entire string well you know when we're at a pointer i we can either take this character by itself in which case then we're going to shift i by one over here and ask you know what's the result of this sub problem or if we take the first two characters 12 then we're gonna ask okay what's the result of this sub problem right so we're either gonna so basically you know it's a set dp of i we're either gonna ask dp of i plus one or i plus two right those are the only ones that we would need to look at right to compute a value like this we'd only need to at most look at two different positions that come after it so you know when we have our dp cache we actually don't need a full array to solve this problem we could do it with two just two variables similar to like a house robber problem approach to dynamic programming or like a fibonacci sequence problem right but with that being said i think we're ready to get into the code now let's write the code so the first way i'm going to show you the solution is basically the recursive caching solution the o of n time and memory solution so we're going to initialize our cache we are going to put a single value in here basically the entire length of the string is going to map to one because if we get an empty string we want to return one in that case that's just kind of our good base case right and then we're ready to write out the recursive function i'm just going to call it dfs pass in a single variable i basically i is the position that we're at in our string s now one base case is if i is in our dp neither meaning either it's already been cached or i is the last position in the string in which case that's our base case right and then we would just return dp of i so that's you know our good base case it's either been cached or you know it's just the end of the string our bad base case is going to be if it's not the end of the string then we have to check what character it is if the character is starting with zero right if the string is starting with zero then it's invalid right there's no ways to decode a string that starts with zero so then we have to return zero so that's like our bad base case so these are the two main base cases that we have but remember if it's not zero that means it's between one through nine in which case uh we know we can take this value as a single digit right so then the sub problem becomes dfs of i plus one right so that's what the result is going to be we're just going to call dfs on i plus 1 because we took the character at i as a single digit right but we know that there are some cases where we can also call i plus 2. now what's a good way that we can write out that case well first let's this is one of the ways you can do it i'm sure there are better ways but basically if i plus 1 is less than the length of the string basically if we do have a second character that comes after the current one right because we're looking for a double digit character so if i plus one is in bounds and either the character s of i starts with a one right s of i is a one because if it starts with a one and there is a second digit that means that definitely we can take a double digit value right because anything between 10 all the way to 19 is a double digit value right so if as long as it starts with one we know we can make a double digit value or the other case is basically i'm trying to figure out a good way to format this in a readable way but basically or if s of i is equal to two right it starts with a two but if it does start with a two then the second digit right s of i plus one must be between zero and six right how can we check that in python at least we can check okay if this uh character happens to be in this substring one two three four five six right basically we're saying is that second digit any value between zero through six at least this is a clean ish way to write it so i encourage you to reread this uh condition if you don't fully understand it but it's basically what i mentioned in the drawing explanation we're basically checking if this double digit value is between 10 to 26 so then we can actually take it as a double digit value if we can do that then to our result we're going to add dfs of i plus two right it makes sense we're doing i plus two because this is a double digit value the sub problem becomes i plus two and then once we're done with that we can just go ahead and return the result but before we do don't forget to cache it so dp of i is going to be equal to result we're caching it and then we're going to return the result and then uh you know when we actually want to return the result in the outer function we can just return dfs of zero because we want to know how many ways can we decode the string starting at index zero and i ran it and as you can see it works and it's pretty efficient let me just copy and paste the actual dynamic programming solution i don't want to waste too much time to write it out because it is very similar and i think if you can come up with the recursive approach the logic for the dynamic programming solution is also pretty simple we have the exact same cache the only thing is we're doing this bottom up so we're starting at the end of the string iterating in reverse order we have the same base cases basically if s of i starts with zero then the dp is going to be zero right and basically you know this is the same as these two lines of code where we just return zero else meaning you know that means it's a digit between one through nine then we can call dp of i plus one that's the same as when down here when we call dfs of i plus 1. now this bottom part is the exact same as the if statement we had down below right you can see the logic is the exact same you know the condition is the exact same only difference is here we're saying dp of i plus two is added down here instead of using dp of i plus two we actually called the recursive function dfs so this the logic is definitely pretty similar and in this solution at least the memory is o of n but i do think that you can instead of having an entire cache or array or whatever you're using you can just have two variables so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
Decode Ways
decode-ways
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into: * `"AAJF "` with the grouping `(1 1 10 6)` * `"KJF "` with the grouping `(11 10 6)` Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`. Given a string `s` containing only digits, return _the **number** of ways to **decode** it_. The test cases are generated so that the answer fits in a **32-bit** integer. **Example 1:** **Input:** s = "12 " **Output:** 2 **Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12). **Example 2:** **Input:** s = "226 " **Output:** 3 **Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6). **Example 3:** **Input:** s = "06 " **Output:** 0 **Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 "). **Constraints:** * `1 <= s.length <= 100` * `s` contains only digits and may contain leading zero(s).
null
String,Dynamic Programming
Medium
639,2091
1,961
foreign welcome back to my channel and today we guys are going to solve a new lead code question that is check if string is a prefix of array so guys just before starting to solve this question let's read out the question given a string as and an array of words determine whether s is a prefix of a string of words a string is a s is a prefix strings of word if s can be made by concatenating the word K spring in the words for some positive k no longer than word slot length return true if s is a prefix string of word or false otherwise so guys just before starting to solve this question please do subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so that you can get your Breeze from the channel so guys let's understand this question with the help of some examples and the example number one says that s is equals to I love lead code so we have to check that if it's uh if it's a prefix of those or not so I can say that I love and Lead code together as can be made by con connecting or concatenating I love and Lead code meaning that if I just concatenate I this word and this word I can get the s similarly uh just go for example number two I love read quote the string Remains the Same in example number two as well however words I words here you can see that there are different words it's starting from apples and the apples are not the prefix of s so we will definitely return false so let's start solving this so to solve this I will just create um variable s answer and then I will just create a loop for I in range land words as we have already read in the question that it says here it should be word start length so we are just writing the length of word and I will just concatenate over the words I in my answer variable which I have created I String I will con concatenate this and I will check if aren't my answer variable is equal to F if it's equals to S then return true as written false for all the condition so guys what I have done here is I've just created a loop in which I have just concatenate answer in my words I and I have check if once is equals to s is my this string and if it's equal to S just return true for that those kind of for that condition and if it's not then just return me false so let's run this question and see what we have done so see it is running successfully so our logic works and this was all in the question guys I hope that you have understood this question and if you have not understood this question ask me the comment section thank you guys for watching this video and see you next time
Check If String Is a Prefix of Array
maximum-ice-cream-bars
Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`. A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`. Return `true` _if_ `s` _is a **prefix string** of_ `words`_, or_ `false` _otherwise_. **Example 1:** **Input:** s = "iloveleetcode ", words = \[ "i ", "love ", "leetcode ", "apples "\] **Output:** true **Explanation:** s can be made by concatenating "i ", "love ", and "leetcode " together. **Example 2:** **Input:** s = "iloveleetcode ", words = \[ "apples ", "i ", "love ", "leetcode "\] **Output:** false **Explanation:** It is impossible to make s using a prefix of arr. **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 20` * `1 <= s.length <= 1000` * `words[i]` and `s` consist of only lowercase English letters.
It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first.
Array,Greedy,Sorting
Medium
null
1,675
hello everyone welcome to day 19 the february lead code challenge i hope all of you are having a great time after a very long time i am seeing a hard question in the daily challenge which is minimize deviation in an array and to your surprise for all those who have been associated with a channel must know that we have already solved this question in the month of january 2021 here is the solution for this i just went through the video i have clearly explained the approach to go about it and i am attaching the link of it in the description below i hope you guys have a great time watching this up also do watch it till the end because i have coded it live in this session i really hope you enjoy today's session if you do please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded i'll see you tomorrow with another question but till then goodbye
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
33
Hello Gas Myself Amrita Welcome Back To Our Channel Technosis So In Today's Video Are Going To Discuss Lead Code Problem Number 33 Date Is Search In Rotate Sorted Are So Let's Get Started Let's First Understand The Problem So Are The Problem Status Date There Is An Wait Errors Sorted in Ascending Order with Distinct Values ​​Date Mains There Are No Duplicates Values ​​Date Mains There Are No Duplicates Values ​​Date Mains There Are No Duplicates Before You Being Passed Too Your Function Names Is Possibly Rotted Coming in an Unknown Favorite Index So Date Mains Your Names Are That Selected But Nine It Is Rotted for Example Zero One Too Four Five Six Seven this is sorted are but it has bin rotated coming from favorite index 3 so it bikams 4 5 6 7 and 3 element shifted to the right part of d raise date mains it bikams 4 5 6 7 0 1 2 so it se date given di Hey name after the possible rotation and give wait target return d index of target it is in d names and -1 sin example in this particular are if you found this target element give you have tu return its respect vice you need tu return next tu d output is food india adar example you can see target element is 3 which dajunt exist in this are so d output is -1 and also you must write an output is -1 and also you must write an output is -1 and also you must write an algorithm with o of log and run time complexity so nine let's get started and let's understand Are you going to solve this problem so let's take D se date is 4 5 6 7 0 1 and 2 get element is zero so if I start searching this target element in this complete are 1 / 1 I can find it element in this complete are 1 / 1 I can find it element in this complete are 1 / 1 I can find it right but D thing is it Would be your linear search and linear search has time complexity of in so can not see us linear search in this case date mains see can move on too by me but the thing is date binary search works only in de sorted list of elements but science this Are this rotate so date me it is not d completely sorted are but d thing is you can see every date left part is sorted and right part is sorted and in binary search else ho see check in d left part and in d right part of d Hey so dat men see can steal us r binary search so nine let's move on step by step and see ho binary search works and ho see are going to find this target element so d step number van in binary search is dat see have you find d Middle elements and in this case you can see every date this is a middle element but you are going to find date first see need you right your start index date should be your first element and index date is your last element d middle element correct what is your Middle element in this case it is this van correct but ho will you find date you will start plus and by tu this is ho you will find your middle element which would be equals tu plus six by tu which is equal tu three date mains at D third index so this is 0 1 2 3 4 5 6 so dat mains third index is your middle element which is equal to 7 correct so this is your middle element and d first case so in d next step what do c do in d manori Search See Check Weather Your Target Element Is Equal To Your Middle Element Target Element Is Zero Middle Element Is Seven So Which Is Not Equal To Date Mains You Have To Move To D Next Step Once You Found Out Date Your Target Element Is Not Equal To Middle Element You need you check weather you search but in this case binary search works only in de sorted list of elements so date mains c need you first check weather d left part is sorted or not so ho your going to check if n are sorted date mains Your first element will be less then equals tu Date Your Left Part Of D Race Terms What You Need To Do You Need To Check Weather Your Target Element Can Exist In D Left Part Of D Airing So Date Mains It Should Be Between Your Four And 7 C Can Se &lt; 4 And 7 Right So Date mains c have to move to d right part of d are let's take some other example for example if you are target element is instead of zero it give it five you will check there four lines between four and seven correct date bikams so when dat becomes true dat mens nine yuvar are bikams four five six same not 7 because si have already check weather it is equals tu middle element or not so dat mens you are start in this remains but ur end index shift tu de this element ho you Are you going to shift date can you say and index is equal to middle -1 right so nine this is your are and again you are going to do this say -1 right so nine this is your are and again you are going to do this say -1 right so nine this is your are and again you are going to do this say steps on delay so d first step was you find d middle element what is your middle element Every fine nine you will check weather your target is equal tu middle element yes dat is true so every you have found your target element let's cons respect case let me remove this part of d airing because it dajnt between four and seven you can aluminum this part Of de are so nine you are left with only this part of de are which is 01 and 2 so this case your end index remain from but ur start index shift so date mains if it is not equal tu this van den you have tu shift yours start index and your start index bikams middle plus van correct nine again same steps find d middle element this is your middle element once you found your middle element you will check whether target is equal tu middle if note you will check in d left part of d are left part of your erase between zero and tu correct right date is true so you will check whether this is equal tu zero so you have found your target element and then you can return d index of d target element which is correct so d four Will be answer in this case Let's get target element by the way three instant so three is not every three is not in these parts so date mains you can return -1 and parts so date mains you can return -1 and parts so date mains you can return -1 and date case so this is you need you search your target element using binary search And it will give you time complexity of o of people and nine let's try solution for it you are going to follow steps which I did just nine so this is un class date in rotate sorted are nine let's try method date wood B public static in search end your inputs would be one number end target element which was d first step Firstly you need to find your start index which is this element and the end index which is this number dot length - 1 end Find your dot length - 1 end Find your dot length - 1 end Find your middle element which is equal to you start plus and by you half of where you are and where you are start index is less equals you and what you are going to do and where you have Find your middle element while you are starting element is less Give Equals You Enderment You Will Say Date Middle Element Is Half Of D Are Which Is Equals You Start Plus End By Correct Nine Once You Found Your Middle Element What Is This Next Step You Can See Everything You Need You Check Weather Your Target Is Equals Tu middle element so if your target is equals tu middle element which is non come de made give what you need tu do you can directly return your middle index correct if note if it is not equal tu de middle element give where c need tu search in D left part of delay and in d right part easily will check weather it is in d left part of d are so far date first living need tu check weather your left part of d arrest sort it so tu check date see need tu check weather this 4 Give This Less Than Equal Tu 7 Correct Date Mains Date This Less Give Equal Tu Middle Element If Start This &lt;= Middle Element Give Date Mains Left &lt;= Middle Element Give Date Mains Left &lt;= Middle Element Give Date Mains Left Part Of D Race Sort And See Can Check While Your Target Element Is Between Your Start And Middle Element So If you are target give it greater equals tu start element and target give it less than middle element than date mains it less in d left part of d airing c can move tu d left part of d aris date mains end index bikams mines van if note C need tu shift wood b middle plus van correct so this is your van part if start it less equal tu middle element if not that need then check weather your right part of d race sort it else c are going tu check if target it greater Give equals tu middle element date mens namjate mint target give it less equals tu last element dat mens it exist in de right part of de airing give si need tu shift are start in next which be middle plus van adar vice end index which would be middle -1 Correct and come D and you can middle -1 Correct and come D and you can middle -1 Correct and come D and you can retain -1 Date mains you might find D retain -1 Date mains you might find D retain -1 Date mains you might find D element elsewhere in D Left part of D Right part of D Hey nine let's go back you are the main function and let's take D importance 456 701 -1 So you Can see every output is -1 -1 So you Can see every output is -1 -1 So you Can see every output is -1 This is how you need to solve this problem If you have other questions other doubts please let me know in comment section Please provide your feedback in comment section and don't forget to like share and subscribe channel thank you for watching
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array `nums` sorted in ascending order (with **distinct** values). Prior to being passed to your function, `nums` is **possibly rotated** at an unknown pivot index `k` (`1 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,5,6,7]` might be rotated at pivot index `3` and become `[4,5,6,7,0,1,2]`. Given the array `nums` **after** the possible rotation and an integer `target`, return _the index of_ `target` _if it is in_ `nums`_, or_ `-1` _if it is not in_ `nums`. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[4,5,6,7,0,1,2\], target = 0 **Output:** 4 **Example 2:** **Input:** nums = \[4,5,6,7,0,1,2\], target = 3 **Output:** -1 **Example 3:** **Input:** nums = \[1\], target = 0 **Output:** -1 **Constraints:** * `1 <= nums.length <= 5000` * `-104 <= nums[i] <= 104` * All values of `nums` are **unique**. * `nums` is an ascending array that is possibly rotated. * `-104 <= target <= 104`
null
Array,Binary Search
Medium
81,153,2273
1,557
Hai gas welcome me welcome back to me channel so today our problem is minimum number of vertices tu rich jo notes so what have you given us in this problem statement here we have been given a one director a cyclic graph which has total n vertices. The numbering has been done from zero to -1 numbering has been done from zero to -1 numbering has been done from zero to -1 and here we have given you an ad which is you are the refactor, here on C is representing you from me t ok so here it means what is from I from this note. You have one further up to 2 I. Okay, direct today is where you have to find your smallest set of vertices from which notes in the graph are reachable okay and you are guaranteed to have a unique solution so here you have vertices. You can attend here in any order, so what do we do through the example, understand what is the problem, okay so now you see, I have taken the first example here, so in the first example, look at yourself, draw it here. Given because black is not kept then I am also visible loan so from here your is going from zero to your one more than this then from zero to you one is going from 4 to 5 and from you one is going to five A then from three you are what Here we are going to four, so here we start from zero, where can we go from zero we can go to one, okay where can we go from zero, we can break, we can go to five, okay Now what do we do with one? We cannot go from five to five. Okay, now you have all these notes, you have to take the minimum node. Okay, by taking the minimum node, you have to make a set, so what will happen is that you can reach all the notes. If you can reach then you look here at zero, if you take zero you will reach one, from one you will reach you, from you will reach five. Come on, from zero you are able to reach three, no, not at four, but this is where you reach three. People, no, with three you can reach four, with 4, 2, 5, with 0, we can reach 25, but if we take three, we can reach only four, we can reach four. Meaning, three will also be there, four will also be right, if we include these two in our set, then we can visit all the notes. Okay, now what do we do, let us understand through the second example, now what is ours here, what do we have? What do we have from zero to 7? Okay, from zero to what do we have, three will be four, five will be six, okay now what do we do here, let's see where we can go from zero to 0. Where can we go, I would remove this okay, now let's see where we can go from zero to outgoing, what can't we go from zero to outgoing, okay now let's see from one, where can we go from one we you We can go to one, we can go to four, we can go to one, you can go to one, we can go to four, we can't go, four, we can go to four, we can't go, okay now let's see, can we go from you, can we go to story, can we not go Okay then let's see where we can go from three. From three we can go to zero. From zero we can go to six and then the story can't go. From three we can also go to four. Okay this is it. Gone, now we see, we can't go through the story from four to four. From five to five, we can go to one. Okay, no, then we see, even from six to six, we can't go through the story. Again, we see, here I write seven. From zero we can go to zero, from seven we can't go open, then from one where can we go, what can't we go, then from zero we can only go to six. Okay, so this is how we are now here if we have tools. If we have to do this, then which one will we choose? See here, in which case, what is your incoming and this is okay, then you can approach it either through story or story, okay then who will go back in this case, in which there is no incoming ahead of him. It is not possible to make the note rich because no matter which note you start, you cannot go there because it does not have any incoming. If someone's incoming is ahead then we can reach there till some note or the other. Note that it is possible that we can go as far as there, so basically we will see here which are the nodes in which there is no incoming ahead, so here you see what will happen in this also, you see what here. Was there any incoming coming ahead of zero? Look, the answer was I was your zero and three was right. So look, is there any incoming coming ahead of zero? What is outgoing? Okay, there is no incoming of this three. Is there any incoming of three? Look here, three outgoing it. A can go till four, here it is not even yours, is it yours, here it is coming from four, you are also coming from here, okay, we can switch it to someone or the other, okay then four. We can make four rich with three, then we can make five rich with you, we can make four with you, we can make five with you, then we can make one with one, we can make it zero then Child, these two whom we cannot enrich even with the story, okay, so if we include these two then what will happen to us, we can visit all our notes from here, see what is there here, any of the 7 is yours, I am dark color. I take it here There is no There is no There is no one here, what is yours, there is no incoming ahead, then there are two here, so we can make one rich, if we take seven, we can make it till 7, then you can make zero rich, zero Yes, you can do it with 7, you can do it with 3 also, right ok, can we enrich three with story, can't we enrich three with story, if we start from here, we can do multiple notes. Okay, then now look at four, can you do four with a story? Yes, you can do four, you will start with three, you can still do it with one, you can still do one, okay, you can do six also with a story, no story. You can also do this, if you start at 0, you will come at 0, from zero you will come at six. Okay, this way it is yours, so you have seen that if you take these three, then what will happen with taking these three, you visit all the notes. If you can, then see what will happen in the case of five. Here you took five, from five you could have paid one. If you went from five to one, you could have paid six from one. If you go to eat with six, no problem, but then. If we start from seven we can come to 0. From zero we can come to six, right? So if we come from one, you will also come here, like this, from five seven one, you are fine, now here. We take three, we take three, so here we can also go to four, so now look here, 10 1234 567, that is, if we include these three, then we can reach all the notes on this mode, so Basically, what will happen to us here, what will we see here, what have we given to ourselves, one is given, so what it is telling you is that there is one ahead from zero to one, that is, one is getting one incoming ahead, zero. From three to four, what is our incoming ahead? From four to two, that is, 2 also has incoming gas, so we will see here who does not have incoming ahead. Okay, so here we are. Do you know the text, how many notes are there, notes from zero to minus, so what will we do, let's take a widget, okay, whose size will be N, that is, your index will be from zero to minus, okay. Now what will you do, you will see whose incoming is ahead, okay, so in widgetized we will mark it as character, by default this is zero, what is zero, in any vector, if you do not slice only a few and do not give value, then it is zero. It happens, that's fine, after that what do we do, whatever second element is here, what is the second element here, what does it mean, whose one or the other is incoming, then what will we do with them, we will mark them one by one, we have marked them. After this, what we will do is take the vector answer in which we will prepare our final set. Okay, then here we will take i from 0 to i &lt; n, that is, till n - 1. take i from 0 to i &lt; n, that is, till n - 1. take i from 0 to i &lt; n, that is, till n - 1. Okay, now we will see whose i and which are which. The note which is here has not been visited, there is no incoming date, no one is coming forward, so what will we do, we will include it in the answer, then what will we do with the answer here? If you return it, I hope you would have understood it. If you liked the video, please like it and subscribe. Thank you.
Minimum Number of Vertices to Reach All Nodes
check-if-a-string-contains-all-binary-codes-of-size-k
Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`. Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution exists. Notice that you can return the vertices in any order. **Example 1:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,5\],\[3,4\],\[4,2\]\] **Output:** \[0,3\] **Explanation:** It's not possible to reach all the nodes from a single vertex. From 0 we can reach \[0,1,2,5\]. From 3 we can reach \[3,4,2,5\]. So we output \[0,3\]. **Example 2:** **Input:** n = 5, edges = \[\[0,1\],\[2,1\],\[3,1\],\[1,4\],\[2,4\]\] **Output:** \[0,2,3\] **Explanation:** Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4. **Constraints:** * `2 <= n <= 10^5` * `1 <= edges.length <= min(10^5, n * (n - 1) / 2)` * `edges[i].length == 2` * `0 <= fromi, toi < n` * All pairs `(fromi, toi)` are distinct.
We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k.
Hash Table,String,Bit Manipulation,Rolling Hash,Hash Function
Medium
null
1,959
hey what's up guys uh this is sean here so this time it's called number 1959 minimum total space waste database k resizing operations uh this is an interesting problem okay so you're currently designing a dynamic array right and we give we're given like zero index integer array nums where the element is the number of elements that will be in the ray at this time and in addition you're also given like integer k where it's the maximum number of times you can resize the array you can resize to any size okay so and the size of the array at time t right must be at least this uh this number of elements otherwise it won't be able to fill to fit that net that many elements right and then we have a space wasted basically uh pretty straightforward space wasted is the current size of the ray subtract the number of the uh the elements in the array okay and the total space way state is the total uh wasted at each of the uh the time and our task is to find the minimum total space weight wasted if you can resize the array at most k times right and here note that the recons the array can have any size at the start and does not count towards the number of resizing operations right so for example we have numbers uh we have two numbers here the first one is 10 second one is 20 right so which means at time zero we have ten elements and at uh time one we have 20 element and for this one we cannot resize the array at all right but obviously like i said since to start the array we can start array with any size right so which means that you know for this one uh we have to start with 20 right because if we start with 10 right then at time 10 at time what zero is fine but when it comes to reach the time one we cannot resize the array right so that's why for example one here we have to start uh the rate is 20 right and then the answer will be 10 because at time 0 we have 10 at time 1 we have to sorry at time 0 right we have wasted space 0 10 and at time 1 we have a wasted space 0. right i mean obviously we can always we can start with any size which is greater than 20 right but since we're getting the minimum total space wasted right that's why i will use the smallest okay and then in example two here right so for this one we can resize it one once so why not so i think this strategy is like this so we can start with 20. okay we start with 20. that's why we have 10 at in at time 0 right and then we have 0 at time 1 and when it comes to time 2 right we have to resize it right so which means from resize from 20 to 30 we also have like uh wasted zero that's why the total is 10 right and here another example right i'm not going to go through it and the constraints like this so we have 200 right and the number ranges 10 to the power of 6. so for this one you know at the big at the beginning when i look at this minimum keyword here i so basically i'll try to solve out basically try a binary search first right but for this one you know i think binary search will not work because let's say you know binary search we search the uh the answer directly if we search the given like wasted time a wasted space right there's no way we can figure out uh given this uh fixed space wasted if we can make uh resize this array within the k times right so that's why binary search will not work in this case and then uh and now i was also trying also try the greedy right so because this one's quite it's i think it's most like it will it'll likely be a gritty problem but you know um basically when i say greedy i mean that i mean probably i can sort the uh sort the other numbers right from this great from the biggest to the smallest but then we have this k here right so which means that at each point right at each index i don't think there's like optimal solution here because at each of the point at each of the index here you know we can resize it to any numbers right to any size um i don't think there's like a optimal one because we don't know what's after this i here right we don't know what's after this eye so that's why i don't think i was able to find like a greedy approach then it leaves us no option but to try out the possible scenarios right so and then if we were tried uh trying all the possible scenarios and then obviously we should consider dp right because dp you know given the dp state we can avoid processing the same similar scenarios right so how about how can we use dp yeah so the answer is yes and how the problem is that how can we define the state right so obviously the first state will be what would be the index i right so which means that we are we're standing we're at the current index i here and second one is that what probably is the k right k means that how many uh operations resize operations we have left right and this is the what this is the basically the maximum sorry the minimum wasted which is space right given this state basically this means from i to n minus one right so that's the definition of dp you know i was thinking about this approach but then i was like probably we also need like a third state which is the current size right so i was trying to add this one to the state of dp because i was like you know um based on the current size no it depending on if we want to resize the current one or not like if we resize the current one do we have to consider uh the current size right because you know obviously it's not that you know we only resize when the uh when the corner size is smaller than the number we might also resize uh even though the corner size is greater than the current number because you know because we want to max a minimize the wasted time right let's say we have a let's say we have 10 30 and 20 right let's so let's see for this one the k is what k 3 because you know in the optimal way right in the best uh basket scenario you know we can always resize basically here we resize we uh the first one is it's fine right basically we put it 10 here the first one doesn't need to resize and then for the second one we resize to 30 for 20 right i mean if we have remaining operations uh of course we want to resize it to 20 so that we can minimize the uh the total wasted space which in this case will be zero right so which means that you know we don't so resize actually it doesn't will not directly relate to this current size because if as long as we have enough uh operations we can always resize right so and then the pro then the next question is that how can we write the state transition function right so let's say given the dpi and k here how can we move to the next state right so let's we have some numbers here right and we're at like current right i here right so how can we retry how can we um move from the current state to the net to the next one right so if you want to resize okay if you want to re resize at this current place of course we're assuming that we have enough uh k right so what the question is that which number we're going to resize to right so let's say we have 10 uh 25 5 maybe 35 right something like this right no it could be a 100 here right it doesn't really matter okay so we have 100 here but we don't care about the previous state right so if we only look at the numbers starting from i here okay so you know basically we have different numbers here you know we can resize it to 10 to 25 to 5 to 35 right but the problem is that can we use any of the number the answer is no right because obviously from here onward we can only resize it to what to the numbers who is greater than 10 right and then it doesn't make sense to resize it to 100 right because you know 100 it's two it's too big and since we're trying to minimize the wasted time right and obviously this five we cannot even we have five number here we can now resize to five so which means let's so let's say we resize two to ten right so we resize to ten it means that you know this resize will only can only uh stop cover this one number right because if we resize to 10 at the current place it means that when we reach 25 right we have to resize it again otherwise it cannot move forward right but so the next one is 25 right so what does 20 what does resize to 25 means it means that you know if we resize to 20 to 25 uh it can cover up to where up to five actually to either 25 or to five right and similarly for if we resize to 35 right it doesn't really let's say we have a 40 here right so if we resize to 35 and then the it means that we can cover from 10 to 35. right so and then we have a i think we have state transition function here basically you know from here so dp of iron k means what so it's going to be minimum right of after what basically the dp so first we have the next state will be dp uh k sorry j to k plus the wasted right the tot the wasted space and the j is what j is between the uh i plus 1 to n right so which means that you know from i here will loop through each number from the current i to the end right and then we'll try to because you know and we'll basically maintaining uh the maximum number uh so far because that's going to be the number we'll we need to resize because otherwise we cannot cover the entire range right and here along the way and then we can easily if we maintain like the maximum number along the way it's i think we can use uh have a one time to calculate the wasted space total wasted space right and then after this one we're gonna pass this one so it's gonna be k minus one right uh to j and then k minus one which means that let's say the js is here right it means that you know this it means that we're going to resize to 35 which means we'll cover it to uh after resizing to 35 we can cover from 10 from this from 10 to this 35 and the total wastage space by resizing it will be what will be the will be 35 times 4 minus the uh this random sum right and then the next state will be what will be the uh the j uh j to k minor uh j and k minus one right actually you know what so here even though we're trying all the possible ways but there is like a grady approach here you know basically a not approach a greedy idea here basically we only uh resize it to the maximum number right because that's because that will be enough because basically we resize to 35 but not third but not 38 right because 35 is the smallest that can cover the numbers from i to the current j and i think that's it right so i think that's the state's transition function and then we can start coding so dp of index let's do a let's do i and k right ru cache none so we have some basic uh case right so when i is equal to n right uh we have we need to return zero right it means that we have reached the end now the answer it goes to system dot max size right that's the maximum and then we need two things the first one is the max the current max number right and then we have a running sum of zero that help us to calculate the total space right and then we have for j in range of the i to n right so we have the max gonna be the microsoft dot numbers of j right so this one is max maybe we should use like new a new size how about the new size i think new size is better it's more intuitive here and then the of the running sum here with the of j so the answer will be what and the answer will be the minimum of answer plus uh we have the new size right so the new size will cover from j to the current i plot plus one that's the uh the total number it will cover it right and then minus the random sum right and then we do a dp of j plus one and k minus one right and then in the end we return the uh the answer right so this is what i like i said so we have so first we maintain like this the current new size uh with a it's a max number so far because only we only choose this max number so far and that's when we can cover the numbers right the numbers from i to j and after that this is basically this part is like the total wasted right uh for choosing new size as a new operation and covering this uh this number of the elements right and then the remaining will be what will be this uh j plus one and k minus 1. right actually there's like another case let's maybe check here because we should only do this whenever the k is greater than zero right if the k is smaller than zero then we cannot do this so and so the trick is that we you know instead of checking the checking k is greater than zero we can move that trap in into here if the case equal to -1 then into here if the case equal to -1 then into here if the case equal to -1 then we can return the system max size right this will simplify the code a lot because you know whenever we have a case that case minus one right and then basically we'll return the system max size which will basically equivalent to ignoring that uh scenario right and we have n because the length of numbers and then we just return the dp 0 and k right oh one more thing so how about this one right how about this uh the zero index one so at zero at index zero uh we don't need to count this operations right so how do we how have we already us consider that this scenario right so we have because you know let's say for example this one right for example this is a good example we have 10 20 right so at turn 20 right so we are at index 0 and the case also equals to zero so for here we're gonna do two photo p we're gonna do two for loop not two four uh two traverse two loop the first one is zero the second one is one right so when we do the first loop here right the we have zero here and then the next state will be what the next state will be dp one and then the minus one right so this is the next dp state so obviously the so n is equal to 2 right so since i is not equal to n and then but k is equal to -1 that's why this one but k is equal to -1 that's why this one but k is equal to -1 that's why this one will lead to this uh invalid scenario so how about the second one so the second one is like we'll cover recover from like what we'll use 20 right so the 21 is what so the 20 after using 20 so the next state will be dp of two right two and a minus one but at this moment right so what do we have the i is equal to two so which means it will return zero even though the k is minus 1 right but if since we check if i is equal to n first then that's why we can cover this zero size case a zero index case yeah so basically we always allow to move forward but we check if this case is equal to minus one after this uh first uh if check fails that's how we handle this uh the first index doesn't require like uh operation right and yeah so let's okay so let's run the code let's accept it yeah so it passed right because the time complexity for this one you know we have i and k right so the i and k is so let's say this is n right so the state for this one the total state number of state is n square right and then for each of the state here we have what we have another for loop here which is like right like what n cube right which is this one so that's why it can pass with this number uh length yeah i think that's it right i mean this one is a dp but you know the state transition function is a little bit tricky because uh to be able to find to move from current state to the next one we have we need to maintain two variables so the first one is the new size right but you know basically which size we can pick but and after picking this new size it means that we can cover the new basically new size the maximum number so far right and with after picking this new size it means that we can cover from this i to this j all the numbers from this i2 to j and with that we can calculate the time the space wasted and then we can easily transit to the next state cool i think that's it for this problem and thank you for watching this video guys stay tuned see you guys soon bye
Minimum Total Space Wasted With K Resizing Operations
minimum-path-cost-in-a-hidden-grid
You are currently designing a dynamic array. You are given a **0-indexed** integer array `nums`, where `nums[i]` is the number of elements that will be in the array at time `i`. In addition, you are given an integer `k`, the **maximum** number of times you can **resize** the array (to **any** size). The size of the array at time `t`, `sizet`, must be at least `nums[t]` because there needs to be enough space in the array to hold all the elements. The **space wasted** at time `t` is defined as `sizet - nums[t]`, and the **total** space wasted is the **sum** of the space wasted across every time `t` where `0 <= t < nums.length`. Return _the **minimum** **total space wasted** if you can resize the array at most_ `k` _times_. **Note:** The array can have **any size** at the start and does **not** count towards the number of resizing operations. **Example 1:** **Input:** nums = \[10,20\], k = 0 **Output:** 10 **Explanation:** size = \[20,20\]. We can set the initial size to be 20. The total wasted space is (20 - 10) + (20 - 20) = 10. **Example 2:** **Input:** nums = \[10,20,30\], k = 1 **Output:** 10 **Explanation:** size = \[20,20,30\]. We can set the initial size to be 20 and resize to 30 at time 2. The total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10. **Example 3:** **Input:** nums = \[10,20,15,30,20\], k = 2 **Output:** 15 **Explanation:** size = \[10,20,20,30,30\]. We can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3. The total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - 20) = 15. **Constraints:** * `1 <= nums.length <= 200` * `1 <= nums[i] <= 106` * `0 <= k <= nums.length - 1`
The grid is at a maximum 100 x 100, so it is clever to assume that the robot's initial cell is grid[101][101] Run a DFS from the robot's position to make sure that you can reach the target, otherwise you should return -1. Now that you are sure you can reach the target and that you know the grid, run Dijkstra to find the minimum cost.
Depth-First Search,Breadth-First Search,Graph,Heap (Priority Queue),Interactive
Medium
865,1931
438
um hello so today we are going to do this problem which is part of um lead code daily uh challenge of January so the problem says find all anagrams in a string basically we get two strings SNP and we want to return an array of all the start indices of P's anagrams in s right so basically by anagram here they mean just permutations actually um anagram in real life it's permutation but needs to be a valid one but here what they mean really is just a permutation so what we are looking for is in s we are looking for permutations of P and what we want is the indices of the start of those permutations right do you want to return just the list of those indices in any order right um so for example here p is ABC so CBA is an Integra starts at zero so put zero and then the other one that is available is BEC that's a permutation of ABC and starts out at six so we have six here so that's roughly the idea in terms of the constraint the length of each of the string is 10 to the power of 4. and we have only lowercase English letters right but from the length if you do just a Brute Force scan for S by P you'll get something to the lines of 10 to the power 8. so that won't pass so we need something better so let's see how we can do it um so let's think about this so we want to get the permutations of p and find where they are in the shrink s so one way to do it is to find other permutations of P do a b c b a and just search for each one of them in s but that's too big right that's going to be 2 to the power of the length here um so what we can do is that is just flip it a little bit so instead of looking for the permutations of p in s let's just go through all the substring of s right of course we only need to look at those of length p and just see if any of them is a permutation of P right and to check if two strings are permutations it's actually very easy you just need to check that the count of occurrences of every character in one of them is equal to the count in the other so I'll say a b c and BAC to find if there are permutations well we can just use the count so a occurs once B ones C ones b o care is ones AO carries one still carries once and if we compare these two counts um they are equal right because bit ones C ones a ones right and that's enough to check the permutations right and so from that idea what do we do here so from that idea we can use some sort of sliding window right because we know for example here we only need to check strings of length three there is no use in checking this one it will never be equal right because the length is different and so we only need to check those of the same length and so what we can do is just use sliding window exactly for that and so we need sliding window and we need the counter for comparison so first we can just have the count for P right it's just a ones B ones and C ones and then we can have our window that starts out with three a substrate the first substring of length three so it starts out here okay so first C is one and we need to have a result for all the indices right the start of the occurrences of a right and so let's call that I start out here and we keep advancing so if we keep advancing then our I would be at starts out at here so I but it's we can easily let's say NP is the length of P easy to find the starting position is just I minus and the length of P that's the this position the start right so it should be easy to check that um now um let's do our counter for the window for our sliding window see okay red ones be occurred once a occurred ones so you can see the same occurrences for p count so we already know this is valid condition and so we need to add the starting position which is I minus p right plus that it's 3 minus the length which is three so it's zero you could try to calculate it here but in that case you will just need to do plus one here so that works as well if you want to so now we want to advance I we found it so we're going to advance I but we want to maintain the length right so we only need to remove this one right because the window moved and then we need to add this new one here so we need to add C we need to remove C which means we need to decrement the window occurrence so basically we need to do window of the S of I minus NP right is going to we are going to decrement it by 1. okay and so we have zero and then we need to add e so to add e we just let's replace it so e now occurs once okay so that's just by doing window of s of I is going to be plus 1. okay so now we move our window again so we need to add the start position which we said is zero we move our window again so our window moves here okay which means we now have this so we need to remove this one and we need to add this one and so to remove B well let's just remove it and let's add B again because we just have so one now this is still different than the P count because of this e so we don't count it so we move I again let's move I here let's move our window now our window is this we need to remove this a so we'll remove this a and we need to add another a so and it's still not equal and now we advance our I again we advance our window and now we have Bab um now we need to remove this e right and add this B so we'll move this e and add to the B so now we have two B's still not equal to the P count so we continue we move our I again here we move our window so now our window is here we need to remove this B and add this a so to remove B we now have just one count we add another a so we have two now and we advance our window again so now we have here our window changes to this and we need to remove this a so to remove a we now have one and now we have a new C that we need to add and now it matches right one c one a and one B so what is the starting position well it's this is after we are here so it's 9 minus the length or actually if we want to do with this position then it's eight minus the length which is three and so that tells you it's um plus one so it's five plus one it's six okay so we add six and this is the final solution okay I hope that was clear um you need to be careful with these indices because it depends on where you put the check for window equal to count if you put it at the end of your iteration or at the start of the next iteration um then you will need to do it differently depending on where you did the check right but it's either one of those um yeah so that's pretty much it now in terms of time complexity you saw here what we did it was just traversing the string so it's of so it was an oven um operation right because we did just one scan um and one oven scanning and is the length of s in terms of space we are using this P count and this window and both are of length of P so this is oven time and or plus a p length of p is called NP space okay um yeah so that's pretty much it now let's code it up and make sure it passes test cases so first we know we need the length of S and P and we need a counter for p this is just a counter for to check against for the pattern and then we have our window that we'll use in the sliding window and then we need of course the result that we are going to return at the end and we need an index to keep track of where we are and that's the index that we will use here as long as we haven't reached at the end and then each time right we reach for a window we want to remove the starting position of that window because we are just sliding by one space right so to do that we are going to say it's just at I minus the length of P because our window length is p is the length of P right and so what we want to do is remove it because we are adding the new one in at the end so plus one right so this basically if you have i a b c d e a something like this and our window let's say was here instead of length three right so we move our window so we need to remove this B here and add this e and this B is the index is just I minus the length of P let's say p the length of three so it's just I minus the length by three right and then the new one is just this one that we added and so we increment the number of its occurrence and this one we are removing we decrement the number of its occurrence now we just need to make sure for the starting position when we start out right there is no starting we don't have a length of P yet okay so this in Python will go to the end of the string and set a value of -1 there so we don't want a value of -1 there so we don't want a value of -1 there so we don't want that to happen so we want to check here that this is bigger or equal to NP because only then that we know we have a window of at least the sides of the length of P right and now here at the end we want to check if the window the counter for the window is equal to the counter for p because if that's the case that means there are permutation of each other they have the same number of occurrences of characters if that's the case then we want to add this to our result but what do we want to add the index of the start so as we said the start position is just I minus NP plus 1 right so this would be the position of let's say you are here this would be the position of I and so to get so I'll say 0 1 2 3 so 3 minus three that's zero we want to do plus one to get here okay so that should be it now every time we want to of course increment the I so let's run this and listen and that passes okay um yeah so that's pretty much it for this problem please like And subscribe and see you on the next one bye
Find All Anagrams in a String
find-all-anagrams-in-a-string
Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** s = "cbaebabacd ", p = "abc " **Output:** \[0,6\] **Explanation:** The substring with start index = 0 is "cba ", which is an anagram of "abc ". The substring with start index = 6 is "bac ", which is an anagram of "abc ". **Example 2:** **Input:** s = "abab ", p = "ab " **Output:** \[0,1,2\] **Explanation:** The substring with start index = 0 is "ab ", which is an anagram of "ab ". The substring with start index = 1 is "ba ", which is an anagram of "ab ". The substring with start index = 2 is "ab ", which is an anagram of "ab ". **Constraints:** * `1 <= s.length, p.length <= 3 * 104` * `s` and `p` consist of lowercase English letters.
null
Hash Table,String,Sliding Window
Medium
242,567
65
hello my friends welcome back in today's video we want to solve one of the problems from the lead code website initially I thought that I would probably want to solve the problem of the day but today is the December 17th but like they've already posted as you can see the problem of the day for the next day and uh as we can see here it's grated as an easy question and the acceptance rate is like 52% which is interesting for an easy 52% which is interesting for an easy 52% which is interesting for an easy problem but anyway um so then I decided that I would do probably like a hard one so if we go into the filters in here and just like choose all the hard ones and look into these I found this guy the valid numbers right it's rated as hard and the acceptance rate is only 19.3% so this should be an interesting 19.3% so this should be an interesting 19.3% so this should be an interesting one right let's look into that so the problem is actually I identifying a valid number what's a valid number it says that a valid number can be split up into these components so it's either a decimal number or an integer if it's a decimal then you have to follow these rules right there has to be or there could be it says optional a sign negative or positive sign excuse me and then it says there could be one or more digits followed by dot uh one or more digits followed by a DOT and Then followed by some other digits and a DOT followed by one or more digits so something like 05 is a still valid number and uh here it says that for your integer it can be like either small or capital E for like the power of the integer and then it also says that your integer can also have like a plas or negative sign and it can obviously have multiple digits and here it gives you a bunch of valid examples 289 uh1 and you know all of these are valid numbers sounds good and look at these guys in here and these are not valid numbers ABC is not a valid number 1 a is not a valid number because we're talking base 10 so maybe if it was like a he number then sure yeah 1A could be valid value but it's not in this case and here you can see some of the examples and it says for example zero it's true uh e just false cuz it doesn't mean anything just a dot just not a number it's not a valid number cool um so let's look at the function that there is here like the input to the function is a string so that's theut let's just copy the name of the function and start coding uh Define my function is number and the input to the fun funtion is a stram s and let's see what we can do the first thing that we need to do is to decide if the input string is representing an integer or a decimal number so we want to have helper functions for each of them um just going to go um decide if it's uh an integer right and I Define my function and I go like for example is oops isn't right and obviously the input to this function is s and the first thing that I want to check is to check to see if you're passing an empty string right so I'm just want to go if not s then return false okay and before we continue I just want to go return true and so by default I would assume that it's an integer and then I could check the conditions that make it wrong and if it was wrong I'll just go return false so this line would be ignored so yeah as you saw the first thing that I would check is to see if I'm passing anything at all right uh the next thing that we want to check based on uh what they defined here for an integer we can check if there is a sign right so let's do this work now I want to go if S zero the first character is a plus sign or um s z uh equals like a negative sign then exclude that so I'm update s would be S one to the end so I'm just going to get rid of the sign and consider the rest right I don't want to repeat these spting here uh why you may ask it's uh because let's say that you have something like this let's say the input to the function is straight negative sign in there or just like this so after removing this you're left with nothing so there is nothing to do the operation on and like we check if it's an integer or not so we want to return false that's what I did here and uh after doing this there is no other condition to check for integers so I mean there is which would be like the E thingy but I'll take care of that later like before calling each of these functions I want to like uh see what's going what's happening with like I want to like do some pre-processing before to like do some pre-processing before to like do some pre-processing before calling this function when I'm getting when I'm calling this function I'm just assuming that everything is just like in the format that I want and uh finally the last thing that we need to do uh I want to go if not s that is digit right then uh return false right what is this guy it's uh it's an interesting function so if I just go here I'm go to Python and let's look at the very first website it says the is digit method returns true if all the characters are digits otherwise false cool so this is what this function does and you can see the example here if you try it all the characters are digits so it's going to return true right um anyway so this is what this function does I don't know if you knew about this or not but this is a cool function uh so this is our first helper method the other one that I want to Define is decide if it's uh that decimal value right so Define is decimal obvious viously they implict the dysfunction would also be S and I want to do the same thing right so let's let me just like copy everything here and uh well actually like everything from here if I do this uh I want to go tap this backward if not s then return false obviously if it's an empty strength I don't want to do anything on it and in the next we're going to exclude the sign right so if it's like there was a plus or negative sign in the beginning just get rid of that an update as after you update then just like do the comparison again like see if it's all or like an M string or not here we want to do something else too right we want to go here and say if right there is a dot in s right so if there is a DOT what do we want to do right we want to go s equals s. replace we basically want to replace the dot uh with like nothing cuz like a DOT is valid we don't care about it and uh it would be okay so if there was a DOT we're just going to get rid of the dot right and then uh after doing that we want to do basically the same check again see if it's like an empty list or not uh sorry an empty shame or not and then after doing this then we can basically do this again right this we got rid of the dot so everything there has to be digits now again could be like e as like the question says here like we could have any of these cases but before calling each of these helper methods as I said before I would run a pre-processing and uh just get rid of pre-processing and uh just get rid of pre-processing and uh just get rid of those as well so I don't need to worry about it here so I'm just going to go if not s that is digit then return false which is like what we just explained and if that wasn't the case then I want to return true okay so these These are the helper functions that I have and I don't want to do anything else and now I want to go ahead and do some pre-processing so I'm ahead and do some pre-processing so I'm ahead and do some pre-processing so I'm just going to pre processing part uh we can close this so there is more room we can see what's going on exactly here and for pre-processing um it says as the pre-processing um it says as the pre-processing um it says as the question says there could be either lowercase or upper case e so what I want to do I want to go s equals s do L oops as sudore so what this function does is that it takes the string as an input right and just converts it to lower case so everything in that string would be lower case right and if it's already lowercase it just doesn't do anything now that I have that I want to go if uh the reason e in s then what do I want to do right I want to like separate it into two parts right let's say for example look at this example in here um one of the examples that they have is this guy in here let's just bring this right and put it here as an example and see how we're dealing with that and let's just change that a bit I just want to go like add more digits here and uh more oops these are not digits and more digits here right so the plus sign and the megative sign like we take care of it so we don't need to worry about it here uh so we can get rid of it and like we have something like this and like there was a letter e here and uh let's say this was like capital E after doing this it would be lower KC that's cool so what I want to do now is to divide it if there is any in here then I want to divide it into two parts this and call each of these two functions on each part to make sure that each part is actually a digit so let's say that we have like this example right this what I want to do I want to go uh part one is this guy without the e obviously and uh part two would be plus this right and I want to run each of these helper methods on each of these to make sure that they are all digits right so this is what I want to do so here I can just go for example part one as I said that equals s to split so we want to split it but how do we want to split it at e right and uh the first urance of it like make it part zero like the yeah that's the left side of the and then we can do basically the same thing that would be part two as I said and uh well this has to be one right so we have like these two parts and we want to run these functions on it so I want to go uh part one valid right is um what do we want to do we can actually do something else we can do uh just like a one Min return uh what do we want to return right we want to return and uh what is it that you're returning is in of part one so part one could be either an integer imagine this like this could be this right so part one could be either an integer or right is decimal of uh part one so if the part one this part in here which we changed it to like with this part so if it's an integer like there is no dot or if it's a decimal it's valid but we also have to consider this one so if this condition is true right and uh we do basically the same thing for the other one is integer uh part two we don't have to check uh part two for being a decimal cuz you cannot have like this it just doesn't make any sense to like have like a DE simpol exponent that just is not a valid number so if part two is an integer and part one is either an integer or decimal then this is true right and if this is not the case which means that like we don't really have an e in there uh we basically want to return what do we want to return is uh in of uh s CU like there was no e in there so we just want to consider like check if it's like an integer or a decimal so just going to go or is decimal uh s so that's basically all we're going need to do um just to go over it one more time we have two helper functions that decide if the input is just like as I'm explaining it occurred to me that like this s obviously is not the same as this s in here cuz like here look at this before doing any operation I change the S and then I use that in know like to get P1 and P2 and then use P1 and P2 as input to these functions so these s's are not necessarily the same it could be in some cases but it doesn't have to uh so we have these two helper functions right that decides if the input is an integer or if it's a decimal uh you can merge these two functions as well and do the proper checks and well but anyway uh and then like to not to have to deal with like Opera case e and lower case because like if we don't do this step we have to repeat these for capital e as well just basically repeat this and instead of lower case e I just have to go upper case e right but like having a lot of if statements is not maybe good uh but it's up to you can try and see what performance you get uh so I just go lowercase and then if there isas an in there I split it into two parts the first part and the exponent part which is part two and then I consider a check if part one is valid which is like either integer or decimal and part two which is the exponent has to be an integer so that's why I do like an and here and say okay only is int I don't want it to be a decimal it has to be an integer and if not that's not the case so you don't have an e in there so the input has to be either an integer or decimal value and this should work and uh I've actually tried it and I know for a fact that it's working and I got really good performance out of it too so if I copy that and uh come in here and paste my answer hopefully everything is lined no it's not so I just have to tab everything over and uh so if I close this function yeah should be good now so if I submit and uh going to have to log in first um so let me log in and uh see the results okay I'm logged in and we're back and uh that's the same code submit it and it's judging my code now and see what happens and it says that it beats like 82% of the users using Python 3 uh 82% of the users using Python 3 uh 82% of the users using Python 3 uh interesting thing I realized like if I submit again I may actually get a different result um so it was 82% and now like it result um so it was 82% and now like it result um so it was 82% and now like it went down to 75% I don't really know what's happening 75% I don't really know what's happening 75% I don't really know what's happening with their server um like yeah I have no idea if you do let me know uh in the comments below what's happening so keeps going down but sometimes like when I want it to get it went up I think the best that I ever got for this code was like 95% like 95% like 95% 9555 that's the max that I got right I just want to run it one more time see what happens honestly uh it went up again to like 86% anyway um this was the again to like 86% anyway um this was the again to like 86% anyway um this was the solution that I could came up with let me know if you have better Solutions like if you could speed up this code in any way uh maybe like having two statements instead of using uh like this function in here would improve your performance I don't know you'll let me know in the comment section uh hopefully you enjoyed this video and it taught you something I'm hoping and if you did like it then please like the video as well and don't forget to subscribe to the channel so to support me and also not to miss the next videos when I upload them thank you for watching me again take care see you guys all in next video bye-bye
Valid Number
valid-number
A **valid number** can be split up into these components (in order): 1. A **decimal number** or an **integer**. 2. (Optional) An `'e'` or `'E'`, followed by an **integer**. A **decimal number** can be split up into these components (in order): 1. (Optional) A sign character (either `'+'` or `'-'`). 2. One of the following formats: 1. One or more digits, followed by a dot `'.'`. 2. One or more digits, followed by a dot `'.'`, followed by one or more digits. 3. A dot `'.'`, followed by one or more digits. An **integer** can be split up into these components (in order): 1. (Optional) A sign character (either `'+'` or `'-'`). 2. One or more digits. For example, all the following are valid numbers: `[ "2 ", "0089 ", "-0.1 ", "+3.14 ", "4. ", "-.9 ", "2e10 ", "-90E3 ", "3e+7 ", "+6e-1 ", "53.5e93 ", "-123.456e789 "]`, while the following are not valid numbers: `[ "abc ", "1a ", "1e ", "e3 ", "99e2.5 ", "--6 ", "-+3 ", "95a54e53 "]`. Given a string `s`, return `true` _if_ `s` _is a **valid number**_. **Example 1:** **Input:** s = "0 " **Output:** true **Example 2:** **Input:** s = "e " **Output:** false **Example 3:** **Input:** s = ". " **Output:** false **Constraints:** * `1 <= s.length <= 20` * `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`.
null
String
Hard
8
29
lead code 29 divide two integers Solution by Michael Elliott this is an easy solution given two integers dividend and divisor divide divisor into dividend the result must be a 32-bit signed int the result must be a 32-bit signed int the result must be a 32-bit signed int it means we truncate the decimal so 10 divided by 3 will be three dividend is ten divisor is 3 10 divided by 3 will result 3. when dividing numbers if the signs are the same the result is positive a negative but divided by a negative is a positive divided by a positive is positive when the signs are different then the result is negative we start the algorithm in strict mode as usual and we get the sine of each uh each operand so the dividend and the divisor make sure that they're the same a quick note on the math.sign method a quick note on the math.sign method a quick note on the math.sign method returns actually one of five values negative one means the number is positive zero means the number was Zero negative zero means the number was negative zero and Nan means that it was not a number at all who would have imagined that math.signed who would have imagined that math.signed who would have imagined that math.signed would be so complicated but there you have it fun little factoid of the day JavaScript trivia math.sign of the day JavaScript trivia math.sign of the day JavaScript trivia math.sign so once we've determined it uh whether or not they are the same or not we can assign that to the result of is negative and if they're not the same then is negative will be true we then proceed to do our operation in positive so assuming that they are all positive numbers dividend and divisor both positive do that by getting the math.abs method absolute value to get math.abs method absolute value to get math.abs method absolute value to get rid of the minus sign off of both operands if there is one we start out by declaring the return value is zero and we're going to do for our strategy is to minimize the number of iterations in the loop if we are given a loop that uh has a million iterations that will take time and the value of this is remember we can have it's going to be an unsigned sorry assigned 32-bit end assigned 32-bit end assigned 32-bit end assigned 32-bit end assigned 32-bit end assigned 32-bit end so that could be a very large number uh and in order to make that more efficient I think if we divide how many times does one go into a million well just one go into a million once yes and then we can subtract one and then we have 999 and then we could do one and do that which gives us uh nine eight one into that nine eight nine seven that would be a million iterations that would take far too long it'll be slow non-performant non-performant non-performant speed it up by doubling by trying to double see well one goes into a million well okay it does what about one plus one well that go into a million yes and what about the result of that plus that ah so now we're dealing with that's a variable so one plus one is going to be two right two goes into a million what about two plus two that goes into a million and so that would be four plus four yes eight plus eight so now we've already reached eight with one plus one two plus two four plus four three iterations instead of eight and this goes exponentially so it goes much faster we have far fewer iterations and we can see that the strategy for doing this is going to be done in a loop right one plus one and then two plus two and then four plus four and we can just iterate over that Loop so let's get into it now uh we kind of an outer loop well the divisor is less than the dividend then we're going to assign value to be divisor value is going to be our that when I was referring to that in the description of the algorithm so value is the divisor and in our example I'm going to just use 13 for the dividend and two for the divisor so value is the divisor and that's going to be two every time we're in the Outer Loop and multiple is going to be one so now we create an inner loop to add that value onto itself and then check how many times we added it onto itself as our multiple and that means how many times it's gone into it so for example one plus one is two plus two is four so our multiple from one plus one would go from one the multiple is one to two plus two being four and then that would double as well so then that would be four that would only be in the case if the value is one but still a multiple is always going to double from two to four to eight 16 and so on well valuables value is less than the dividend okay so we're going to be checking this and then modifying the dividend potentially outside of this Loop but we're going to see how many times we can get the doubled values into dividend and then go back and see like let's say if we get a number we get this 13 we get 2 into 13 how many times will 2 go into 13. we get two let's just step through it Value Plus value or value is 2 less than 13 yes so value is now going to be 2. uh sorry four Value Plus value is going to be 4. multiple is going to be equal to 2. multiple is going to be equal to two so because 1 plus 1 is going to be 2. and then we're going to continue on this two plus two was four and now we have four values four remember because we incremented it here four plus four is eight that's less than dividend two and dividend is 13. so now value is going to be assigned to eight it's going to be plus equals it's going to we're going to resign it there now value is 8. multiple is now going to be equal to what it was before doubled 4. okay so now value is eight plus eight is sixteen less than 13 no so we're done with the inner loop for now exit that inner loop we go into the statements after that dividend we subtract value from dividend what was value was eight dividend is 13. so now dividend is 5. from 13 minus eight red is now going to be equal to incrementing that by multiple is four so ret is now zero plus four is four okay now we're done with this iteration of the loop now we go back up to our Loop terminal condition is divisor less than dividend divisors two dividend is eight minus 13 was 5 down here we got five so we're going to reset the value to B2 and multiple is one again we're going to try again to see if we can double up that two and that's how that works we've got the remainder of five it's two still might go into that remainder multiple times that's what we have this nested Loop with the outer loop and the nested Loop so two plus two is four that's less than five now we're going to assign that to value is now going to be four multiple is now going to be 2 instead of one so dividend is going to be after that we're going to check to see if this is this Loop terminal condition two plus two was four plus four is eight is that less than five no we terminate that Loop and now we're done with that Loop so now we go to check to see if dividend minus value was four five minus four is one okay now that's what the new value for dividend and now dividend is one and that's going to be our remainder because we already know that one is less than two so we're not going to be able to divide two into one evenly anymore so red is going to plus equal multiple that's uh multiple was four was two so four plus two is six now we go back up to our Loop terminal condition divisor is two dividend is one two is not less than one we're done less than or equal to one we're done so now we have the rhet is we're going to clamp this finally to a 32-bit signed clamp this finally to a 32-bit signed clamp this finally to a 32-bit signed integer we have to consider that we're dealing with a negative number so when we're dealing with a negative number then the result is going to be at the lowest possible number it could be is 2 to the power of 31. but if it's a positive number it's 2 to the power of negative 2 to the power of 31 a positive number it's 2 to the power of 31 minus 1. so we're going to check to see if it's negative if it is we're going to say 2 to the power of 31 and if it's not negative then we're going to subtract 1 from it and then finally we're going to add the sign to the front of it so again your math dot Min rhet whatever's smaller or we did our math and positive numbers the red value or 2 to the power of 31 minus if it's negative then 0 and if it's positive we subtract 1. now we could have gotten Fancy by doing type conversion but uh I just found that this ternary operator was although a little more verbose it's clearer that's how to solve this problem thanks for watching
Divide Two Integers
divide-two-integers
Given two integers `dividend` and `divisor`, divide two integers **without** using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, `8.345` would be truncated to `8`, and `-2.7335` would be truncated to `-2`. Return _the **quotient** after dividing_ `dividend` _by_ `divisor`. **Note:** Assume we are dealing with an environment that could only store integers within the **32-bit** signed integer range: `[-231, 231 - 1]`. For this problem, if the quotient is **strictly greater than** `231 - 1`, then return `231 - 1`, and if the quotient is **strictly less than** `-231`, then return `-231`. **Example 1:** **Input:** dividend = 10, divisor = 3 **Output:** 3 **Explanation:** 10/3 = 3.33333.. which is truncated to 3. **Example 2:** **Input:** dividend = 7, divisor = -3 **Output:** -2 **Explanation:** 7/-3 = -2.33333.. which is truncated to -2. **Constraints:** * `-231 <= dividend, divisor <= 231 - 1` * `divisor != 0`
null
Math,Bit Manipulation
Medium
null
1,689
Ajay Ko Hello Hi Guys Previous Links Problem Call Partition Which Minimum Number Of Tehsil Binary Numbers Seervi And The Students Are Number Withdraw From This Contest 120 Minimum Number Will Give Number 231 I One And Again In This Version 100 New Latest Free Numbers In Total Which Give Three Do The Number Denge Number Is Questions O Mein Aa Lunch Box Certificate Maximum The Types Of Our Lives With Daughter In Law Andar Bihar For Loop In Amla Printing Rate This 70 Want And Not Listen A Plus No Check Witch Numbers Martin Del Potro Characters And Subscribe Now To Minor Elements Such Problems And Help You Avoid Subscribe That And Show Me All Actors Name Of - 2m Digital Dhan Show Me All Actors Name Of - 2m Digital Dhan Show Me All Actors Name Of - 2m Digital Dhan Ki Meeting Hai That Anderson Ko Kar Do I Want You To Return Is Internship In This Site To A Friend Is Chord That When List 169 Points Dance You Don't Like You To
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
1,560
let's look at problem 1560 most visited sector in a circular track given an integer n and an integer array rounds we have a circular track which conver consists of n sectors labeled from 1 to n a marathon will be held on this track the marathon consists of M rounds the ith round starts at sector down rounds i - one and ends at sector down rounds i - one and ends at sector down rounds i - one and ends at sector rounds I for example round one starts from round zero and ends at sector round one return an array of the most visited sector sorted in ascending order notice that you circulate the track in ascending order of sector numbers in the counterclockwise Direction all right so what they're essentially saying is they'll be given a value n which is the number of sections sector you can call it sections let's call it sections so say the section is four so divide a circle into four parts and each part will be one section and the race is going on so a person will be going through they'll also pass how the person is running right so the person is running say from it starts from section one goes up till 3 then goes up till 1 then goes up to two so what essentially is happening is it's going from 1 to three then going to four and then going to one again and then two right they can only run in One Direction which is increasing order not in another Direction so essentially what is happening here is say instead of this example I take a bigger example okay the person continues to run two from 2 to say n is = to say n is = to say n is = to 5 right continuous to run up to two to B right so starts from one ends at three okay let's take that as an example what is essentially happening is let's list down all the sections so all the sections are 1 2 3 4 5 right so a person starts from one right goes up to three then goes up to one which means it goes till five and then reaches one then goes up to two then goes up to four then goes up to three which means again it goes to five and then three right so if you see the person has traveled all sections twice right to cover this okay and only the difference between the last section and the first section is the section that it has covered extra and that's what is a question we need to find the sections that the person has traveled the most so these sections the in these two rounds complete rounds the person has traveled through all the sections equal number of times we can skip that it's as good as not going there right because everybody is getting two the difference is being made by this in case of only in case of if start is less than end start is one end is three so start is less than end so in that case I can simply say end minus so all the numbers between all the sections between start and end these are the sections the person has traveled extra this is condition one there could be condition where another condition where if end is greater or equal to start sorry end is less than or equal to start right or I could write it in this way start is greater or equal to end in this case what happens is let's take an example say the user has started the race at three and ends set 1 our user has started the race at four and ends at two let's take this example okay so what is essentially happening is the user starts at four goes up to one from 1 to 2 from 2 to 4 from 4 to two here what is happening is the rounds where the duration where the person has gone from uh covered entire round that is equal for all sections right all sections has been covered once the difference is this 4 and five 1 and 2 how do we find this difference simple we take from 1 to end right one to end you can see it here this is going from one to end which is two and other is and I'll add some more elements which is from start till n so start till and okay expand this right so the are the parts that the user has travel extra what in case uh these are the parts the users traveled the most what in case the user starts at two and 4 2 and ends at two right so the user has started from Two and ends at two in that case start as less than or equal to we need to do this start is less than or equal to so start will be 2 end will be two so this will only have one element which is two which is because every other element every other section is being visited twice but two is visited twice once here and once here so this condition we make this minor change to the condition that works for us right this covers all the conditions now how to code this what I can do is I can first write down this if rounds 0 is less than or equal to last one right in that case return range gives me an array and that range is from round zero to rounds last round plus one range removes the last elements so I'll add one so that it does doesn't remove the value of the last element so if say rounds minus one is five if I put just this rounds minus one in range then it will not add five in the aray it will just take it till four so I'm putting + four so I'm putting + four so I'm putting + one and in the S case what I can do is I can put the other condition this first condition is done then other condition is it goes from one so range one to end which is rounds -1 + 1 plus another range which will give me another array plus will concatenate both the array so and here I'll take rounds start as like0 comma n + 1 okay so this will like0 comma n + 1 okay so this will like0 comma n + 1 okay so this will cover the second one let's run and see it works for all the cases I could even improve this if you know that in this condition where start is less than or equal to 10 range will only return a valid array if start point is less than or equal to the end point right otherwise it will return an empty so I need not even put this if condition I could just say return this if it is not empty and if it is empty anyway it will I'll just add an or here it will go to the second part okay so it will check the first part if the first part gives me a valid array with it at least one element it will return this otherwise it will realize that it's empty which also means that start is not less than end in that case the second condition will run and the second array will be WR let's run and see worked let's sub that worked 26 millisecond 51% worked 26 millisecond 51% worked 26 millisecond 51% of users has better Solutions let look at the other people's solution this is exactly what we are doing right let's look at more solutions same we'll find most people using the same solution this is the best solution for this seems like same again same solution in a longer fashion so that's how we solve the problem 1560 most visited sector in circular track see you in the next video
Most Visited Sector in a Circular Track
number-of-students-doing-homework-at-a-given-time
Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds[i - 1]` and ends at sector `rounds[i]`. For example, round 1 starts at sector `rounds[0]` and ends at sector `rounds[1]` Return _an array of the most visited sectors_ sorted in **ascending** order. Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example). **Example 1:** **Input:** n = 4, rounds = \[1,3,1,2\] **Output:** \[1,2\] **Explanation:** The marathon starts at sector 1. The order of the visited sectors is as follows: 1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon) We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once. **Example 2:** **Input:** n = 2, rounds = \[2,1,2,1,2,1,2,1,2\] **Output:** \[2\] **Example 3:** **Input:** n = 7, rounds = \[1,3,5,7\] **Output:** \[1,2,3,4,5,6,7\] **Constraints:** * `2 <= n <= 100` * `1 <= m <= 100` * `rounds.length == m + 1` * `1 <= rounds[i] <= n` * `rounds[i] != rounds[i + 1]` for `0 <= i < m`
Imagine that startTime[i] and endTime[i] form an interval (i.e. [startTime[i], endTime[i]]). The answer is how many times the queryTime laid in those mentioned intervals.
Array
Easy
null
29
this is the 29th Fleet crew Challenge and it is called divide two integers given to integers dividend and divisible divided two integers without using multiplication division and mod operator the integer division should truncate towards zero which means losing its fractional part for example 8.345 would fractional part for example 8.345 would fractional part for example 8.345 would be truncated to eight and negative 2.7335 will be truncated to negative two 2.7335 will be truncated to negative two 2.7335 will be truncated to negative two return the quotient after dividing dividend by divisor assume we are dealing with an environment that could only store integers within 32-bit signed only store integers within 32-bit signed only store integers within 32-bit signed integer range for this problem if the quotient is strictly greater than 20031 negative one then return that and if the quotient is strictly less than negative 2 to the power 31 then just return that okay so if the dividend is 10 and the visit is 3 it outputs three because when you divide that it does 3.33 Etc so you divide that it does 3.33 Etc so you divide that it does 3.33 Etc so remove the decimal places just read 7 divided by negative 3 is negative 3.63 7 divided by negative 3 is negative 3.63 7 divided by negative 3 is negative 3.63 so remove decimal place and it's negative two okay so the divisor can't be zero okay so let's get started I think the way to do this is by using addition with the divisor so you have the dividend and these are the divisor to just add sorry if you add it once okay actually I'll just get started in it so I'd explain what it is so something that we should first check is whether they are positive or negative so the ball is positive as in whether the output should be so for this it will be it'll be positive if brief dividend if the visit are positive or if they're both negative so dividend greater than zero and the physical greater than zero so if they're both greater than Siri or they are both Less Than Zero demi-nots positive demi-nots positive demi-nots positive and then I guess easy thing to do first we will just make them both positive so equals math dot ABS dividend and then do the same thing for divisor I think that we can do is because we're truncating it if no I don't need to delete all that if divisor is greater than dividend we just return zero because I mean if the division is greater it's going to be a fractional number so then you just need to return the zero straight away so we have that out the way otherwise just do in total equals zero and okay what's it called the thing that we are returning the question say int quotient equals area and we'll do a while total is less than dividend total plus equals divisible and then quotient plus then return quotient so I think that's all that has to be done so let's say we have dividend 10 actually we'll do Dividend nine divisor two so it starts up a zero we do plus equal which makes the total two and the question one we then do four two six eight we then it'll go to 10 and 5 but then now it's total is greater than dividend so I'm returning the quotient which will be five so I think that's how it worked so let's run that and see if it's all good oh I forgot to okay so apparently I'm doing one too many there which actually that sounds correct so if we'll break out from here and we also need to do this so if not is positive then quotient times equals negative one okay now let's run it Okay so we've got three and negative two so hopefully that's all that needs to be done so let's copy this and put it into lead code we'll double check with the test cases which came back correct and I'll submit okay we've got a wrong answer so dividend one divisor of one output is zero Okay so we need to change this while it's less than or equal to yeah we'll do that okay cool that still Returns the correct answer so it while less than or equal to and we'll do what greater than there and I'll submit okay we got something wrong uh negating the minimum value of two complements number is invalid okay didn't think of this I guess we need to do a check to see if dividend is the lowest int possible because we can't turn that to positive as the positive one is this is negative one hmm bull is Min equals dividend equals int.min equals int.min equals int.min so we have that ismin if is min we will do dividend equals in.max dividend equals in.max dividend equals in.max and we'll have to do math but adding one to it or something I'm not too sure I have to play around with it could be the same for divisible actually hmm I was just thinking what if divisor is negative int and dividend is uh positive int you have to do something there hmm okay I need also check for that so we need to do a check for brief dividend and divisible so if either of them are the men then we change it to Max and we do it like that I guess we could add a check here if divisor it's mitten and sort of so the divisor is the minimum with the divisor is the minimum then it must return zero I think if divisor zero then B also you do a check for if ismin but we turn one are those returns zero because if the divisor is the lowest possible number the only way that you can return one is if it was equal to your grader so the only way it can be greater is if or it's not possible for it to be greater because the positive ones are will always be lower so the only way you can return one is if it's the exact same or higher but the only way it can be is if it's equal so we'll do that so three for them I'm in return and then we don't need to do any more down here we can just do this so we've got the divisor fine now if the dividend is the lowest need to do your check hmm I guess the check with right we're not currently doing plus equals here but we're not checking to see if it is greater than actually total we can just make a double I think that works just making a double actually we could just use doubles for this instead of using ins that makes it easier yeah okay we're going to remove this okay well that makes it easier it will do double there and if quotient is less than int v2.max on in the value that is what we will return else if it's greater than max value return max value otherwise free uh convert dot in 32 let's run this here first and see if that works before we put into leak code so the first one runs but then the second one doesn't not sure why that is might just be my visual studio messing up but let's do a breakpoint okay it does go wrong somewhere restart it go there and we'll go to the next one and we'll just step three well total zero x negative three wait I'm using the wrong values that's why dividend divisor oh we also forgot to use it here as well okay now that should be all good okay there we go let's grab this and put in delete code so it's saying assume we're dealing with an environment that can only store integers within 30 sign range it might be that we can't use doubles but I'm not sure I'm hoping it just means the value range so it's like if using something like python it doesn't have you can use whatever number values so I think hoping it's yeah okay hoping it's just telling you not to use those values greater than you have to uh trim one of those okay let's Summit okay hmm still got the same issue okay we'll just grab these numbers and put it into here okay I see what this is it's for this one I thought that would have covered this though let's go down to here Arch I should probably change these to doubles and then do that set the issue okay I think that was the problem but we should probably add a check for if the divisor is one so if email divisor equals one and we'll just copy and paste this into it because that took way too long trying to because it has to just plus one over and over so with this number three one four seven yep oh actually I need include this as well so if it equals one go down to here that'll make it negative oh that's because it's both negative both of the numbers are negative right so they'll just return int max value I think that's all that has to be done for handling the larger numbers so let's grab that and we will copy it back into the leak code and just to make sure okay without those okay so let's run it make sure we're getting the correct expected output and we did now let's submit hmm so time limit exceeded but it's not saying what the numbers are Maybe I'm not sure what that could be like why wait it's saying all of them pass but it's not giving what failed autonomic seeded that's not very useful you know what I need to go look up what's going on with this one so I guess I'll be right back so I haven't been able to find a proper solution as to what's going on here and why I can't see the actual numbers being used but I did come across a solution to make this more efficient which it's kind of cheating as I should be doing this by myself but if I'm getting a time limit exceeded with this solution then I have to do something else and I wouldn't be able to figure out a way to make this more efficient without looking it up so the way you make it more efficient is by using uh bitwise shifting which is basically shifting uh the bits to the right a bit which is essentially multiplying it by two and this is a way for you to get the multiples more quickly so currently we're just doing one two three four five uh for the quotient but with bitwise you can do one two four eight sixteen Etc and you get up to a point where it's now greater than the dividend and then you reset it and then you start again with the remaining amount so I'm just gonna walk through how all the change what changes need to be made so first of all just get rid of this we will use a double divisor so while this is less than the dividend we then need to do double temp divisor you're going to be doing the bitwise shift on this so we'll make this value and we're going to be creating an INT multiple this is going to be holding oh sorry equals one this is going to be holding the amount of uh multiples that the divisor can be within the dividend so we can remove this part outright we then do another while loop in here which is temp divisor while temp divisor it was shift one is less than or equal to uh is less than or equal to the dividend I don't know what happened there okay why is this not giving okay so it turns out we can't do it on doubles but can do it on Longs I think yep okay and then we'll need to convert too long I assumes you could do it like that we'll just spawn okay so while this is less than the dividend we then just shifted by one which is multiplying by two and then the multiple here we also shift by one so I guess to read through this while the divisor is less than the dividend this is this means that no matter what you can get a multiple of one in it so that's why we initialize this one then in here if temp divisor bitwash F1 is still less than one we bit where shift one of the multiple which is multiplying it by two so then no matter what the device can be in there twice but then if we sh bitwise shift again and it's still less than that means the device can fit into the dividend four times so that's why we shift so it's essentially just doing multiple multiplication without doing multiplication because we're using our big one shift okay so we do that until temp devices now greater than this then what we do is get the divisor and we minus equals the temp so this temp divisor here is the greatest number of the current divisor that can be uh that can fit into the dividend so we move this from the divisor and then we also uh questions plus equals multiple and then with that we just carry on again so I'm not sure if this will work because I haven't tested it yet but let's run it okay return to wrong value there so if first things first I'm gonna just so we can properly see what's going on I'm going to remove this and we will break point through it okay let's go to here so DBL dividend 10 advisor 3. go in get the temp divisor which is three multiple equals one then we tempt advisor one which would make Curt will that make it six yes it would I think so it'll be one zero then we're making it one zero which is yep so two one zero three that'll be four two zero six so you go through here temp divisor it's now six down here and then the multiple is now two so we do that again but then it's not that's not equal to I must have done something wrong so we get the divisor because yeah this should be three actually let's just run through and see what happens okay that makes it negative three that doesn't seem right but let's see what's going on too real divisor is less than turn into a long negative three you go here makes a negative six okay this doesn't okay that's not right it's questioned um keep it as that actually it would change this to int and we'll do if int oh if quotient equals int between Max we can then do this part there no that doesn't make sense change that back to double okay I don't know if we'll do anything but let's just change it so everything is long instead of double see that here no need to cast it there you know as it's no longer dbo uh we'll just call it abs that's what we've done to Absolute okay actually I just thought so we will do um we'll do if it's positive if um int 32.max value actually yeah we'll just we'll do the equation stuff in here so if quotient is greater than into 30 in 32.max value 32.max value 32.max value minus multiple so I was trying to do it equation to plus multiple was greater than this but that's not how that would work you need to draw the other way around because then if this is greater than this then this plus this would be greater than this we then return this otherwise question multiple then we can do the same thing in here if quotient is less than Min value plus multiple we then return the Min value otherwise negative multiple R should this be what should that be an INT and we'll keep it like that and then down here should just be able to turn this right I don't know if I need to do any of that but let's just run I want to see what happens that did not work at all okay how what happened Ah that's right it's not working as I thought it would use that to enter there oh this is meant to be dividend that's what's going on okay now let's run it and step by step through it see what's happening so differences three multiples one is now six multiple one doing bitwise with this is now greater than ABS dividend so we exit from that ABS dividend minus temp divisible makes it four same question plus equals one also two because they're fitting twice and go back here uh the divisor is still less than so we go here uh temp divides is three dividend is four so doing this would make it greater than so skip that you know you want to see call to make it one and the current multiple is one so that will make that three we go then here it's no longer or devices no longer less than dividend so we exit from that and the question is three so let's continue uh yep it's now returning expected output oh it's taken a long time to do this but I think that's finally it so let's copy that we will put that into leap code right here I think I deleted this Kelly press then okay let's run on the test ones just make sure and I'll submit wrong okay so let's put that into the test here to two and it's picked up put should be one let's run that turning zero so let's go through it and figure out what's happening so shimmerton's right there which it didn't which is good so equation zero okay this should be less than or equal to that's the problem so we'll go back to here put the equal sign submit oh and there we go we finally did it took quite a lot of attempts oh I didn't realize I've been out for an hour uh we've done it and although I wasn't able to figure it out myself I've now learned what bit why shifting is how it works it's basically just shifting all the bits to the left one and works as a multiplication of two so if you can't multiply or divide you can use this to bitwise shift so that was the 29th Fleet grade challenge called divide two integers so if you like this video make sure to like And subscribe
Divide Two Integers
divide-two-integers
Given two integers `dividend` and `divisor`, divide two integers **without** using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, `8.345` would be truncated to `8`, and `-2.7335` would be truncated to `-2`. Return _the **quotient** after dividing_ `dividend` _by_ `divisor`. **Note:** Assume we are dealing with an environment that could only store integers within the **32-bit** signed integer range: `[-231, 231 - 1]`. For this problem, if the quotient is **strictly greater than** `231 - 1`, then return `231 - 1`, and if the quotient is **strictly less than** `-231`, then return `-231`. **Example 1:** **Input:** dividend = 10, divisor = 3 **Output:** 3 **Explanation:** 10/3 = 3.33333.. which is truncated to 3. **Example 2:** **Input:** dividend = 7, divisor = -3 **Output:** -2 **Explanation:** 7/-3 = -2.33333.. which is truncated to -2. **Constraints:** * `-231 <= dividend, divisor <= 231 - 1` * `divisor != 0`
null
Math,Bit Manipulation
Medium
null
1,687
hey everybody this is larry this is me going over q4 of the recently code uh bi-weekly of the recently code uh bi-weekly of the recently code uh bi-weekly contest delivering boxes from storage to ports hit the like button hit the subscribe button join me on discord let me know what you think about this problem it was really hard that's what i thought about this farm so usually my format is that for especially for contest problems i explained the solution and the algorithm and maybe a little bit about me dog process and then i give you know uh the video you could watch the video afterwards right um of me solving it live during the contest so two things one is i did not solve this during the contest and two is that this is a pretty hard problem um not in its components but it's just that you need to put three or four uh tricky parts together into one problem i do one solution and that's the part that i didn't solve during the contest and in fact i'll have a link below on the contest video and you could watch me try to solve a during contest i couldn't stop it during the contest and i spent an additional hour just getting it right um and actually to be honest i tried explaining this problem the explanation from scratch and it and that video ran about an hour and a half of just explanation going step by step um so an hour and a half is a long time to spend on a problem uh on a video of a problem not even just solving it right so what i'm going to do here is that i'm going to say that again which i said a few times alright this is a hard problem don't feel bad if you don't excuse me don't feel bad if you're unable to get it that's one i didn't get it i'm not feeling that bad uh two is that okay here's the list of things that i recommend you practicing and if you're unable to solve this problem practice those things and then you have to put them together and even me like i don't know not to be bragging but like you're watching my video right and i'm still not able to resolve it during the contest but i'm here to explain it to you the best way that i can um and let me know what you think i know that this is a really long intro and this is a really weird intro for two minutes but i just want you to understand that this is not an easy problem uh so okay so these are the things that you need to understand about this problem first right one is dynamic programming this is a dynamic programming problem this is dynamic programming solution um so you have to be pretty familiar with dynamic programming um and more specifically there are a couple of different types one is you have to be familiar with prefix sum by itself comes up in random places and you have to be able to pull it out to figure it out to um to solve this form uh you might not need to you could get away with other prefix some e stuff like some people have done segment trees and something like that but i would say prefix some so that's one two uh is shortest path in a dag that's a dynamic programming solution um oh that's a dynam there's a problem with a dynamic programming solution the canonical way is n square uh if those words don't mean anything to you know find another problem that lets you solve that problem uh hopefully either join me on discord or hopefully someone will put a link to some problems that are related to that and practice those problems first because you need to know that as well um and then and once you have those things another thing that you need to already have good understanding of is sliding windows uh sliding windows in itself is two pointers and you know it's okay it's not bad uh and if you are able to have a good deep understanding of it that will help you solve this problem i mean and you need it for this form uh i know that some solution also recommends uh monocule and stuff like that actually that surprisingly is not necessary um you may need to use that to solve it of end times in linear time you really want to get the most uh efficient way but i would argue that's not the most interesting part of that problem maybe you could figure it out but using uh using a heap or some kind of heap like algorithm which you know i'll show you below uh you should be resolved this problem in n log n which it's not optimal but it's fast enough and you already got for a lot of different hard parts right so that basically that's my disclaimer so if you are not super familiar with all each of those algorithms that i point out go back and work on those uh it makes i mean like if you're just gonna you know uh like this problem is not a good problem to solve without a better understanding of those algorithms okay now five minutes in let's get started uh okay so all that being said let's go over uh so i prepare not the right not the final solution uh we'll solve it together but i'm gonna start from the n squared solution so this is my n squared solution uh it works for most small ends playing around with it and stuff like that and the tricky thing is notice that by the number of boxes is n which is could go up to 10 to the fifth and max boxes says n to the fifth and max rate is n to the fifth right so that if you basically if max rate is 10 to the fifth max boxes is 10 to the fifth and rate all the rates are one you're going to become an n squared algorithm so that's basically not what we want but looking at this code this is the way to do it in and square dynamic programming and the reason why we're starting from here and this is how you find the shortest path between um the shortest path in a dag using dynamic programming and the reason why we're starting from here is from here we will do the optimization to get it down to n log n time which is fast enough and then with some hints hopefully to get you to all van okay so sliding window is the first thing that we're going to talk about uh with respect to this problem i'm not going to go too deeply on how sliding windows work sometimes i do sometimes i don't but for this problem i just don't have time because it is a hard problem um so yeah the signing window is that okay let's look at this three seven uh which is point three it has a seven weight say um let's say that um with one trip or one trip has a different meaning here but with one departure say um with one departure you're able to visit you know this node and this node or in one group right then now when you process the next object well the two things that happens right one is that well now we extend this to the right because now we're from here you're able to look at the solution backward to be like okay now we have to consider 3 1 going to 3 7 as well as all the other stuff that we are already convincing right and the reason why we're using sliding window is that this is the only way to use these overlapping solutions so that we are able to calculate this in really fast time otherwise if you do another loop like i do here in the code that's going to be n squared and we're trying to get it faster than that right and let's say that we're able to get the min if we're able to get the min of these segments in log n time then that's enough for us to get in and log in as we go left to right and the two things that happen when we process the three one here and this node and let me make the find bigger one is that we add this segment right i mean that seems pretty straightforward you know you can from three one going backwards you have to connect to three seven otherwise i mean you might you may be too heavy and not go that far but you have to at least start in that consideration um and then the other thing is that well now let's say you added this um this segment or this box and now it's too heavy or too many boxes well now you have to remove boxes and you only remove it from the front uh until it all satisfied right so that's basically the invariant that we're trying to accomplish the invariant here is that within the these segments the number of boxes is less than max boxes and some of the rates is less than max weight right and every time we move that sliding window that holds true so if you have a good understanding of sliding window this is actually not that bad um to understand i mean you have to put it together that's the hard part but right okay so now here from here we ask ourselves okay if we're able to do one uh departure and we're able to go anywhere where would we go right well here we have all varying costs and the answer is well we take the min of everything in inside and then we just go there right and it's kind of like a greedy kind of way but you basically take the min inside that uh segment and then go there um so that's basically the idea behind this dynamic programming but there's one more piece if you recall okay um we talked a little bit about prefix sum i'm gonna come right back to it but for now we're gonna talk about one more thing about calculating the delta right um calculating the you know this segment changing to this segment okay number of boxes is easy because it's just you add one box or you subtract one box depending on how you move the two pointers you know if you for me if sliding windows that's obvious um for the weight same thing right as boxes come off you subtract the rate as boxes come on you add their weight also very basic sliding window situation but then the problem is that well the costs are not the same necessary right okay actually in this case it is but let's say we're here and now we're considering the 4-4 and now we're considering the 4-4 and now we're considering the 4-4 and we're concerned here right well the cost so the thing is that if you're here and you know and this is me just reading from the problem so feel free to read the problem again to make sure you understand the rules of the problem because i because this is already a very long video um but here going here let's say we want to group these together into one round trip right well what's the cost of that well the cost of that is just you know you have one trip for departure you have one trip to come back and then you have one more trip to go from four to three or three to four doesn't really matter as long as you're because it's symmetric right um and in this case so that's one more so total is three uh similarly here if you just look at these segment then the answer is still going to be three because the three and the three are so fourth right but then the problem is that okay if you look at the everything inside here let's say let's just say we keep track of what's inside right um from here at least from the oops from the distance of the three right um so here from three the minimum cost would be zero uh we could add two back later i mean i think that's you know just going and coming back so the two is consistent so we don't have to worry about it for now um and then from the three seven it's still zero because it's the same as the other three this is zero as well and this is zero as well right but now if you look at the four i mean this is kind of uh another great example i would admit because everything should be let's just pretend for a second that this is two then uh then you have one because now you have to go from the departure point go to two go to three and then three again but then you don't have to move and then come back so it takes one here right i'm gonna also change this to two just for clarity um so that you'll see in a second uh but now if you go to four if you just like really naively look at it you know four will be zero because again this is the same thing you start from the departure point you go to four you come right back so there's only two trips again we just ignore the two for now and zero uh here this is one as we said because you have to go from the departure point to three to four to uh and back so there's that one trip in the middle uh same thing here is one this is two uh and we and this drop off reset so we could just ignore it but you know and that's the tricky part about this right is that well actually everything inside here is not the same as everything that's inside here you know this changes as you add more numbers but as it turns out this is where prefix sum comes into play ah this is a long rap give me a second but yeah so this is where prefix sum comes into play right so that now having this you can actually pre-calculate pre-calculate pre-calculate everything for counting from the very end so let me type this out so yeah so for example here five so let's say this is zero this is one because if we were to put this group together we have to go from z you know uh or we have to go from the start go to one go to five and zero so there's only one again this is two this is three this is four right so basically the idea here now is that we don't need to you know we could store different things in here we want to be able to store things inside here that doesn't change and the invariant of this distance metric is that it doesn't have to change anymore right now instead of sewing 0 1 we could just store 3 4 oops and here again is 4 3 three two where now and this is hopefully familiar to you if you're familiar with prefix sum uh is that now you can see that all we have to do is just get the min of what's inside i mean well i guess this includes the two for starting this zone and then we just have to subtract the prefix i mean in this case it's the suffix but suffix sum i guess it's kind of a different thing but right so now because here we subtract basically the delta from here right so that's basically all you need to solve this problem uh i know that is very tricky and it's very hard and now i'm gonna start programming it for you uh so this part maybe a little bit slower because i am trying to do this live a little bit uh not because i wrote this another way when i first solved it but now i think with this it is i feel like it's great um it is easy to understand piece by piece and not just assume some greedy algorithm or some assume you know those kind of things i think when you're able to understand the components to its parts then you're able to you know reproduce how to solve it in the future right if you just memorize solutions it's going to be tough to solve similar but not exactly the same problems so okay now we want to create a suffix sum so i usually write it kind of funky so bear with me but yeah okay let's just do suffix index is equal to n minus one um while suffix index is greater than zero maybe one yeah what we see oh and this should be this times n plus one so yeah so suffix of suffix index uh i guess actually this is n minus two so that we could do this is equal to suffix of the suffix index plus one plus the uh whether they're the same right because here if they're different then we have to add one to the suffix array so oops uh what's it called boxes uh suffix index of the port which is zero is not g code two so something like that right performance and then suffix index minus one actually this could go to zero and let's just do a quick print to make sure that i don't have a typo uh okay so this looks okay yeah okay so then now that we have the suffix array and at least one first question looks okay now we're going to refactor out n squared dp so now we want to rewrite it as a starting uh sliding window uh from left to right so let's just rename some of these things sometimes i get it confused left is equal to zero as well um we could just start over okay let's go uh so now we add a box to the oh uh and i guess the other thing is that okay how do you store this structure right well for me you could actually there are a couple of ways to do it a min heap is actually good enough as well as long as you make sure that when you remove a number you don't use it in the future there are a couple ways to do that but it's a little bit messy so i'm not going to do that for now i'm going to use in pi find something called sorted list and again if you're really good with mono cubes you could actually use mono cubes right now um yeah you're able to use mono q you're able to use the mono queue uh but see if you're able to figure that out i also have a tutorial on mono cues so if you want to watch that i think i did a good job uh a reasonable job of explaining it um let me know what you think but we don't need the monokyo to uh at least i'm not gonna explain the mono cube portion i mean it's not it's a good exercise of self after you figure all the other pieces i think these other pieces are more important to put together right okay so like now we add in uh the right so oh let's start with you know rate is equal to zero number of boxes is equal to zero and yeah so now rate well we add in this rate so the rate is one yeah the number of boxes we increment that's just because we just we now add right box to the uh to the segment i call it maybe um to the sliding window so window maybe okay there we go um and now while number of boxes is greater than max boxes or weight is greater than max weight so basically now our window is too big i'm going to make it smaller right so we subtract boxes of left of one number of boxes minus one and then we move left plus one right so okay so this part it is very elementary sliding window hopefully this is understandable because now we're going to have to incorporate the other parts i think this part is okay if you or should be okay if you're practicing sliding window um okay and then the question is okay uh what happens when we add right and when we add we just move to the um we move right to here so actually we're already covered suffix upright should already give us the answer so you know dp of some answer um let's just say right is equal to some element something here let's just write something uh plus or sorry minus uh suffix of the right maybe off by one but basically what it's doing here is that it takes the min element inside here and then we subtract it from here right um and then we have to add it to two i think uh the two being that you know you just have to go out and then you have to come back in right so that's just part of the problem definition um this is assuming one round trip so yeah so how do we do the something minimum okay so this is where we have sorted lists come comes into play uh as i said you could have maybe used um mono queue or in c plus or even java maybe you use a set or tree map or something like that but basically i just wanted to get something that let me lets me get the min as we roll that sliding window i like sort of list for that reason because um i don't have to worry about anything weird um yeah so basically okay so let's say we added a new number right well that means that we just basically added this to the list so that's actually pretty straightforward right so hopefully this is right because it looks silly if it's not but we add suffix of right um yeah we had suffix of right because uh i was thinking about making it zero but then i remember that we will subtract it later so it will become zero it's fine um but yeah so it adds subject somewhat it adds this to this and then now it has to remove this uh segment which is this uh suffix right so now we just go sorted list that remove suffix of left um and then now minimum is just to sort of list the first element of the sorted list so that's pretty much it uh except for getting the right answer would be nice but um so maybe i have some something i'm missing hang on let me print it out real quick um why is this two that's a little awkward uh i mean this part it may be just because i'm off by one oh yeah because right is zero so this is actually plus oh i'm just being silly uh i mean this part is still right but then now we have to get um so this is the cost from here okay i'm just being silly so this is the cost from here right but we also have to get the cost from this point to the uh from the beginning right so that's basically the rest of this problem is okay yeah so basically what we what i forgot not we i mean it's always we when you're in trouble right uh so what i forgot was that when we put on d here when we put things here uh let's say we you know let's actually say in english so that we can make sure that we get off by once correctly um is that inclusively let's say you know we already took care of all these but will take over these later but right here we want to find this the beginning of this round trip in the shortest cost right and that is if we start the round trip here then it is 3 again minus 3 because of the prefix sum plus dp of uh let's see zero one two three four right because this is then dp sub four is of course the best answer that's right here right uh here is the same thing as minus three plus dp sub three uh this is also minus three plus well the minus three gets factored in later but uh this is db sub two so actually let's remove the minus three uh of course everything is a little bit misaligned now but or a lot misaligned but you get the idea right so that um if you connect let's say this four plus dp of two is what does that mean exactly it means that okay this is one round trip it will cost two because it goes from uh from the root node or whatever the that's uh the beginning to three to two to three and then back so it will cost four plus three so it will cost one plus the dp sub two which is the rest of the journey right so okay so with that in mind uh that should be a easy fix this is plus db sub right minus one because we're adding the right box and actually now dp is off by one because we padded with the no object so let's do that and we also have to make sure we remove that as well um and let's give it a go ooh one time error oh and i forgot that this should be y plus one because again uh you know when this is zero we actually want to populate the first element uh and there you go right answer let's give it a quick submit be awkward if it's wrong yeah okay cool so this was a very long explanation video or i mean i did some implementation as well but this is a very hard problem um maybe on a better day i am able to get it today i'm not um i usually will have a link or i usually have the video like right afterwards of me solving it during the contest but to be frank it's a little long it's a little boring um there'll be a link below to the contest video if you really want to watch me solve it that's fine and you can watch that but i don't want to upload it again um but yeah uh again this is a really hard problem especially if you are not as familiar with every component so uh my first iteration of this video was an hour and a half and it's just way too long to learn so much so hopefully this is a short version and let me know what you think hit like button to subscribe and join me on this call ask me any questions because this is hard and i will see y'all uh another problem bye-bye
Delivering Boxes from Storage to Ports
the-most-similar-path-in-a-graph
You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a **limit** on the **number of boxes** and the **total weight** that it can carry. You are given an array `boxes`, where `boxes[i] = [ports​​i​, weighti]`, and three integers `portsCount`, `maxBoxes`, and `maxWeight`. * `ports​​i` is the port where you need to deliver the `ith` box and `weightsi` is the weight of the `ith` box. * `portsCount` is the number of ports. * `maxBoxes` and `maxWeight` are the respective box and weight limits of the ship. The boxes need to be delivered **in the order they are given**. The ship will follow these steps: * The ship will take some number of boxes from the `boxes` queue, not violating the `maxBoxes` and `maxWeight` constraints. * For each loaded box **in order**, the ship will make a **trip** to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no **trip** is needed, and the box can immediately be delivered. * The ship then makes a return **trip** to storage to take more boxes from the queue. The ship must end at storage after all the boxes have been delivered. Return _the **minimum** number of **trips** the ship needs to make to deliver all boxes to their respective ports._ **Example 1:** **Input:** boxes = \[\[1,1\],\[2,1\],\[1,1\]\], portsCount = 2, maxBoxes = 3, maxWeight = 3 **Output:** 4 **Explanation:** The optimal strategy is as follows: - The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips. So the total number of trips is 4. Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box). **Example 2:** **Input:** boxes = \[\[1,2\],\[3,3\],\[3,1\],\[3,1\],\[2,4\]\], portsCount = 3, maxBoxes = 3, maxWeight = 6 **Output:** 6 **Explanation:** The optimal strategy is as follows: - The ship takes the first box, goes to port 1, then returns to storage. 2 trips. - The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips. - The ship takes the fifth box, goes to port 2, then returns to storage. 2 trips. So the total number of trips is 2 + 2 + 2 = 6. **Example 3:** **Input:** boxes = \[\[1,4\],\[1,2\],\[2,1\],\[2,1\],\[3,2\],\[3,4\]\], portsCount = 3, maxBoxes = 6, maxWeight = 7 **Output:** 6 **Explanation:** The optimal strategy is as follows: - The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips. - The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips. - The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips. So the total number of trips is 2 + 2 + 2 = 6. **Constraints:** * `1 <= boxes.length <= 105` * `1 <= portsCount, maxBoxes, maxWeight <= 105` * `1 <= ports​​i <= portsCount` * `1 <= weightsi <= maxWeight`
Create an array dp where dp[i][j] is the min edit distance for the path starting at node i and compared to index j of the targetPath. Traverse the dp array to obtain a valid answer.
Dynamic Programming,Graph
Hard
null
838
Hey gas welcome and welcome back to my channel so today's our problem is us domino so in this problem statement what have we given here we have got and domino given right in one line and this is your standing vertically what do we need What has to be done is to simultaneously push some dominoes either in the left direction or in the right direction. It is okay after 8 seconds. What will happen if you move a domino in the left direction, then its adjacent one may be in the left direction. It is okay if force is applied to its left side. Okay, if you apply force to a domino in the right direction, then its adjacent side may also be affected by force to the right. Okay, this can also happen. It is possible that a force is being applied on a domino from right direction as well, if force is being applied from left direction also, then what will happen in its relation, will it remain balanced, will it remain standing, okay and here a line has also been given for the purpose. Of this question, will we consider that a falling domino expends no additional force? You are a falling domino and have already fallen in domino, that is, if a force has already been applied on a domino, then it is okay, then you cannot apply it again. What is meant by this, we will understand this. Okay, through the example, here we have been given three states that if domino I is your L, it means that you have to push the domino in the left direction and here if domino R is given, it means. What will you have to do with the domino? It has to move in the right direction. If there is a dot, it means that you do not have to do anything to it. Okay, so what will you do when you push it. What will be the condition after that? What has to be done is to give it fine, it is okay, so look here, R Dot L is given, what does it mean, here the character is four, so here it means that you will have four dominoes, okay, this is end domino. It is done, now what you have to do is to apply force in the right direction, on this side it will move here and there, so you apply this also, this will become right direction and if you apply this, now it will move in the left direction. Now what is happening on this? It is coming from the left also, meaning from the left side it is getting force in the right direction and its neighbor who is on the right side is getting force in the left side. Force is coming from both the sides. So what after 1 second? It will remain like this, it will remain like this in the future, does it mean that dot means that no force will be applied on it, okay, we are doing it simultaneously, that is, force is applied on all the time, whatever amount is given, for whomever it is given, right? Here the condition is RL, so you will not do it, you will do it at the time of coming, okay, so whatever change will happen in which force is not being applied, it can be changed because there is not even a single port on it, so the van will move from its left after a second. It can also be from the right, it can also be from the right, so what will happen if we look at the forces of both, it will get the time balance, okay, then it is yours, if this is yours here, RR, it also looks like this, then here There is no one else left to balance it, a van will be placed from here, after a second, after 1 second, it will become like this, then what will be the answer to this RR What will happen in this condition RR This will remain a dot because it will be ahead. This ray is standing here and here this L will be from its answer. So how can we solve this problem? Before that let's see one more example. R dot will be more correct. After that here L will be ok. Now here, a force will be applied from here and a force will be applied on it from here, it will move it in this direction and what will it do to it after 1 second, it will move it in this direction, okay so what will happen R Ye L and Look, because when this van is here after the second, it will apply force here after the second, but now when it goes after the second to apply it will know that when we changed within the first second. After this, what had happened with the four at the same time had also changed. Due to its force, the force has already been applied on it, so now you cannot apply it again. When it comes to this second, it will be seen that it has moved now. We cannot apply force on it, hence this will happen and RL, the line you have given here that if there is any fruit or falling is taking place then you cannot apply force on it again, so this is the meaning of this line, see. Here it will happen after two seconds but it came to know that if we can apply it in advance, then it is okay, so here we have to solve this problem, so see, to solve this problem, we will use Tu Point Algorithm. Why would we do that because we know that the force exerted on any particular domino is dependent on its two sides, okay, when it is on it, when you see R is written, then it is right, we understand. I will understand that there will be right direction. If L is written then I will understand that it will be in L but if there is a dot then what does it depend on for the dot, what is on the right and what is on its left, after how much time will the force come on it. After how much time will it go from the right side? After how much time will it come from the left side? It depends on both. It is possible that the force is being applied from the left side as well as from the right side but if the left one is applying it first then the left one will be applying the force first. We will move if he comes to know that no, I have to apply the pen on the right side, force is to be applied only after one second, then we will move first, maybe there is someone who is approaching him from the left side after two seconds. And if it is coming from the right side to the left side after three seconds, then in that condition, he will see both of them by comparing them, so what will we do for this, here we have taken two arils, what will this actually do to you? It will be seen that if you are moving any domino from left to right, then after how much time is it changing on the HH index, that time is filled by us here. Okay, now here also we will see that if it is moving from right to left, then after how many seconds it is happening. Okay, if after how many seconds it is happening, if we know that then we will compare. We will find out the final state, so now let's see how we will make it full, so what will we do, here we will take one of our previous state, what is our current state, dot is ok, why will we take dot in the initial because you For this you will see that if you start looking then before this there is someone else there is some push i.e. someone is going to apply force otherwise push i.e. someone is going to apply force otherwise push i.e. someone is going to apply force otherwise so we will take the dot ok more time we will take the van now we have so much time ok we will take the van now we are here Let's see what we have, I will write it here, it will be more correct, dot 8 dot L R dot L dot, how much is 1 2 3 4 5 6 7 8 9 10 11 12 13 14, so here we have given this size of 14. Hey, I have taken the size 14 here. Hey, I have taken it. Okay, now what will we do? Start from here. What is Apna? Here is the dot and in the previous state there is Apna Dot, that is, no force will be applied on it, so here. applied on it, no force will be applied on it, so here. Pay time, how much will it take to change it, zero will become zero, okay, we are moving up for left, down for right, after how many seconds will it be in right direction, but it turns out that it is L, that is, what will you do with it, left direction. If you move it, if you apply force then there will be a factor on it, otherwise, that's why it will be zero, that is, if you are doing full for the right, then it is going to the left, neither will it be zero for this, because here we send it to the right. Ca n't because there is more in life then we will come to this, what is this, along with this we will not change the previous one in the state, okay now this is a dot so only brother can know whether it is right or not this is not right So what will happen here will be zero, okay after that we will fill the dot here, dot will again take the previous state, now we will go to A here, when you come here, you came to know that this is right, so right, get your zero in seconds. If we move to the right, then here it will be zero and together we will take the previous state of our R. Now here the dot is the dot, then it will see whether the previous R is Han R, then what should I do in the next second by changing it. Two, what to do with this, there is zero, one, three, four in one second, this will change, what will happen in one second, we will also increment it and it will remain R because it will change only after one second, right direction, hence R will happen here, it's okay, after that, what will you do in two seconds, will you change it because this is also a dot, both of them, so these two will change in a second, so what will happen, we will keep this audio and make it full, it's okay here, three is done, now this is Now when we come here, we come to know that it will be L, it will go in the left direction, it will not go in the right direction, OK, if it cannot go in the right direction, then we put zero and here we make it L, make it WAN, then here P If there is R, then if R is there then it will happen in zero second, okay it will happen in zero second, then fill eight here, then come to this, then after how many seconds it can change in the right direction, 1 second. If possible later, we will give van here also, then after the change, A will remain the same, otherwise we will come to this, what will happen after 2 seconds, it will change to R because after the previous second, this army will change. Then this van will go on this after a second, it means the force applied by the van will go after a second, then what will happen, it will reach here in a second, okay, so what will happen for LK because we are looking for the right. Now it will be zero so we will update it with L so it is a dot so it will not go to your right hence zero so zero is ok, this is done, now we will look at the bottom one, what will we say in the bottom one that we are in the left direction. In how many seconds can we go in the right direction? In how many seconds can we send in the right direction? So what will we do? We will start looking from here. Okay, so we will take the dot on our app's previous state here because there will be no force on it, but on the last one, here. But what if it is our own, then it is okay, no force will be applied from behind because there is no element here, otherwise we will take a dot here, why do we present a dot where no force is applied, so we will see when we come here. There is a dot, okay there is a dot here also, if there is any force applied, then it will be zero. You will see here, if there is a dot, then it cannot go in the left direction, this will also be zero. Now coming here, if there is a left, then in the left direction, it will go in zero seconds only. It will go because L is putting it on itself and then it is not helping. If I don't know then L, it will be zero only, then what will be the time here, it will be your van. Okay, from L, this is a dot, van will put it after a second, right? Pay M will change after 1 second, so this van has to go, then you will change this state in a second, you will remain here, will increment along with it, will fill it, then when it comes here, you will know that if it will not go to the left, then pay here. What will happen will be zero, okay then when we come here, we will see that L is okay, if it is L, then it will change in zero second, then it will happen in zero second, then we will make it our own, along with this, what will happen is your L. Now what will it do in 1 second? It will change you. It will hit you on the left. It will hit it from here. It will change it in four seconds. Then you will change it in a second. Then it will change it in 3 seconds. Then you will see that you are on the right here. If it is right, then on which force will it apply zero? This is your dot here, if it is right then it will apply force on this, what will not be applied, neither will it be applied on the left, nor can it be applied on the light, if it cannot be applied on the left, then it will be zero here, okay, what will happen after that? Yours is after that, this is the dot here, then what is this, yours is L. Okay, so L will be done in zero second, right, put a van on it, okay, so see what I do to it, then I will write the answer to you. Let me tell you what will happen, how will we compare, here is L, here is dot, here is R, then there is your dot, then there is L, then what is yours, R is R, L is L, dot. Dot is this right L Dot R Dot L R L Dot Ok now see what will happen here you will know that from here in 1 second you are changing to the left D Right in one second you are changing to the right from here Now someone told me that this banda will move in the left direction after 2 seconds, so what should you do in that condition, whom will you consider and hence the thing is that whatever happens in the first second, you will not move it in the direction. So it will depend, we see, look, both zeros are here, this is this and where else zero seven is being formed, 88 is being formed and here you are seeing 11, you are seeing 12, you are seeing 13, so see. Here zero van tu three four five six seven eight nine 10 11 12 13 ok see in the case of 13 there is a dot in its case also there is a dot in its case and in the case of 11 there is L ok then you see the case of van in the case of van Sorry this is your zero this is your van this is your tu 0123 4 5 6 7 8 9 this is 10 ok look in this l is only yours wherever there is zero in both of them the previous state has given it to you Is it the same? Okay, so what will we do here, we will see that in the state of zero, if you have L here, then L is the same, then you have both of them. What is this statement, what is your here P is L. Sorry, there is a little bit more confusion in this. This is L, this is dot, this is R. Let me map it correctly, zero is 234, this is your 6, this is your L, right, what is yours in 11, then your dot is dot, in both 12 also your zero is here, so dot here. There is also a dot here, there is your zero in 11, here if yours is zero, then L is from both of them. Okay, look here, what is there in the condition of van, if there is zero, then zero is from both, then you are from. In the condition also, zero is zero in both of them, so the state of both is dot. Look here at three, this is also zero, so it has R, so what is the condition that when your left is zero, then what will be the state of Domino? From will be the state, okay, this is done, after that now look here, now this is zero and what is yours and what is this is your left, okay so when you see that R is your zero and it has some value. If it is in the condition then it has become L then let's see another condition like this, is there anything like this here where your RJ L is zero and what is yours, there is value in it, meaning if there is value in R then there is something like this visible. If you are not able to see then what will happen in that condition? When your L is zero, okay then you will do full art here. When your R is zero, what will you do? Will you do full L here? Okay, so what is R here? If there is zero, then look here, L is full. Okay, this is yours here. And this is three, it means that in the right direction this change would have happened within a second but in the left direction it would have happened in 3 seconds, then what will the fourth one do, whom will it consider the three seconds or will it consider the van, obvviesli will it be considered? Will consider R, so what is your meaning of four? Here the answer is ok. Okay, this is done, so we will see which one is less and which one is less, we will consider that one, then this condition has become yours. Now we come to the code part. Let us understand that whatever we have done here, we will do the same after going there. Okay, so see what we have given here, that we have taken N here, the size of domino is OK, we have taken left, we have taken right, first of all we have these slices from zero. OK given to everyone then time is your van and previous is your dot we have to keep the previous state ok now we are going from left to right what will we do here we will see if our domino is r is it ok r then do previous r Do two time vans and keep going. In this condition, if we make the zero full, then you have already liked this, then only zero will remain, there is no need to do anything at that place. Here, when you are watching the domino L. So even in that condition, you are filling it with zero, so here, if you have sliced ​​it will zero, so here, if you have sliced ​​it will zero, so here, if you have sliced ​​it will remain zero, but you are changing the state, otherwise you will make it L. Now you will see that if previous is R and domino is dot then what will we do, we will fill the time and if we are doing time plus d then this is done, this is yours, it has been filled for the right direction, now what we will do is fill for the left direction. We will take the dot from the previous one, we will take the time vane, now we will start from the back, okay, we will go from N - 1 to G - &gt;= 0, okay, we will go from N - 1 to G - &gt;= 0, okay, we will go from N - 1 to G - &gt;= 0, okay, so we will see in this condition also, if we are on the left, then we will change the previous state to the left. We will do time, our van will remain right. Now see, when you were getting left, it is in condition, now if you fill it at zero, then if you have sliced ​​it, then there will be you fill it at zero, then if you have sliced ​​it, then there will be no need to fill it here, just do time van for that and continue. Keep it ok, then you will see the domino R, what are you doing in that condition, you are changing the status of the previous one and your initialisation is kept at zero, it is kept at zero full only, there we will not need to do zero here. What is your previous, here pay is L and domino is dot. Okay, so in that condition, the dot one will have to be changed, then you will write its time and do time plus. Okay, this is done, now we have got both left and right. What will we do, we will look at each one, here we will compare all the sets, so we have taken one impacting here, now we will fill all here, what will happen to it, what will we do first, we will check whether the left eye is also zero, whether the right eye is also zero. What if both are zero in that condition what do we take the straight of domino taking the right when our left was zero what do we do in that condition R are we taking the right when our right was zero what do we do in that condition We are taking the left, it is okay, then when the left eye is equal to the right eye, then in that condition we are filling the dot. Okay, what do we do in that condition, we are filling the dot. Did this condition of yours come anywhere? Han had come to the fifth place, look here too you are there, so in this condition look at the fifth place, is it a dot or not a dot, so it is here, what happened due to this condition, if left eye and right eye both are equal. Look, it happens that it is equal even in the condition of zero, but when there is zero on both sides, then it will be the time of the domino or the state, we will take that state, but if possible, respect it, if there is zero and it is from both sides, then it will be in the condition. Will dot ok, now it is that if the left eye is less than the right eye then I have taken the left eye, if it is taking less time for you to go to the left, then laptop people. If it is the reverse, if it is taking less time to go to the right, then you are right people. So you will add R here, what will we do in the final, we will return the answer. I hope you liked the explanation. If you like the video, then please like, share and subscribe. Thank you.
Push Dominoes
design-linked-list
There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. You are given a string `dominoes` representing the initial state where: * `dominoes[i] = 'L'`, if the `ith` domino has been pushed to the left, * `dominoes[i] = 'R'`, if the `ith` domino has been pushed to the right, and * `dominoes[i] = '.'`, if the `ith` domino has not been pushed. Return _a string representing the final state_. **Example 1:** **Input:** dominoes = "RR.L " **Output:** "RR.L " **Explanation:** The first domino expends no additional force on the second domino. **Example 2:** **Input:** dominoes = ".L.R...LR..L.. " **Output:** "LL.RR.LLRRLL.. " **Constraints:** * `n == dominoes.length` * `1 <= n <= 105` * `dominoes[i]` is either `'L'`, `'R'`, or `'.'`.
null
Linked List,Design
Medium
1337
129
Hello One Today Going to Record Delhi Bailey Samjhu To-Do List Number Delhi Bailey Samjhu To-Do List Number Delhi Bailey Samjhu To-Do List Number Questions Page Give Them Through 2000 Rupees Two Phone Numbers In Need To Return Friend intercourse play the giver 11123 subscribe route number 323 452 323 number two’s long ago 120 Bildcon Il Due To Vic Point Number Two Mein Chhunte The What Is Written Statement Lips Encounter Rishtey Toot subscribe and subscribe the Video then subscribe to the Page if you liked The Video then Jhaal To Doodh Question By Using Defiant Young Widow * Difficult Particular Number To The Number Of Phone Number 7 Days 80 Simply Return More Pacific Subscribe To Flu Play List Play Written Statement At What Were Returning To Get The Benefit Of All Possible Simply Not Contain A you will see dark heart panel decided to augment us 123 subscribe must subscribe button 123 plus to point to 10 panel types of this page please click on subscribe to you soe different items and assembly of mine alarm set third parties Withdraw all pre-2005 notes on andhra posting soil conservation patient neer verses from website on bhavya weeravar [ weeravar [ weeravar not true facts not to train time fruit a request to girl title difficult solution that boat oil ne ki show aaye beam function 1999 tension Number Track Loot Meeting That Now He Was Virendra Fruit And Nut Samrat Soe The That A Root Click Question Different Side Reaction Kilometer 100 On Phone Remuneration Web Notification Making Efforts To Reduce The Soul When Death Counter And Brief Note On 16000 Encounter Asli Note Tight Flute And Tried To 209 Dash Havechya Return Diet Ka Path Hum Ine Vadapaav 12413 Loot Will Return Gift Veer Director Website Play Music Industry Live Typing Going To Here Right Minute Pimple Paun Inch To 10 Subscribe To The Page Why Not without opting for me left re sa the water bearer obtained from array of trees and wearing the then skin this question on hua tha so second house will be simply determining during servi society all parts of a loot to 100MB and different return and tenth android 2.1 android 2.1 Angry Birds Pen More Subscribe Media In The bab.la And Now What Pier And Show Loot-Loot Solution Of Class 8 Shri Radhe-Radhe Institute Will Be Simply Subscribe To Alarm Set Software Login And Space Complexity Will Definitely And Drop in Difficult Subscribe Video Subscribe button that stock side gold medal and moment What is the distance between new states and night fall total number of not only on students life in please subscribe course
Sum Root to Leaf Numbers
sum-root-to-leaf-numbers
You are given the `root` of a binary tree containing digits from `0` to `9` only. Each root-to-leaf path in the tree represents a number. * For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`. Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer. A **leaf** node is a node with no children. **Example 1:** **Input:** root = \[1,2,3\] **Output:** 25 **Explanation:** The root-to-leaf path `1->2` represents the number `12`. The root-to-leaf path `1->3` represents the number `13`. Therefore, sum = 12 + 13 = `25`. **Example 2:** **Input:** root = \[4,9,0,5,1\] **Output:** 1026 **Explanation:** The root-to-leaf path `4->9->5` represents the number 495. The root-to-leaf path `4->9->1` represents the number 491. The root-to-leaf path `4->0` represents the number 40. Therefore, sum = 495 + 491 + 40 = `1026`. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `0 <= Node.val <= 9` * The depth of the tree will not exceed `10`.
null
Tree,Depth-First Search,Binary Tree
Medium
112,124,1030
691
hello and welcome back to the cracking Fang YouTube channel today we're solving lead code 691 stickers to spell word we are given n different types of stickers each sticker has a lowercase English word on it you would like to spell out the given string Target by cutting individual letters from your collection of stickers and rearranging them you can use each sticker more than once if you want and you have an infinite quantity of each sticker return the minimum number of stickers that you need to use to spell out Target if the task is impossible return minus one note in all cases all the words okay we don't care about that uh all right so let's look at some basic examples and let's start with example two because it's actually easier so we're giving the stickers notice and possible and we're told we want to spell basic so this one's pretty straightforward that we can't do it because as you can see none of the words have a b so there's no way that we can actually build this so in this case it's impossible so there's no way we can cut up notice and possible um to build this right so that one's easy what about the hat right so as you can see all of these um characters are in at least you know one of these words so what we want to do is okay let's see which words have a t in them well with exam and example and science don't so we have to take from with and we can actually take what T and H right and we can use it twice so we'll have to use with twice and take T and H here so we will B use T and H so we use the two stickers and then we'll have E and A do we have a word with E and a example we can use this one get rid of it and then we'll have used three stickers so obviously if you just look at the problem on the examples it's really easy to figure it out and your brain can kind of just piece things together quite simply but as you can see this is quite a hard question and given the fact that I've been putting this off after two years of doing this channel uh means that it's not that fun so how do we want to solve this question well we got a bit of the intuition already when we were solving it kind of on paper and that is that whenever we have you know whatever word we need to do Target um and whatever we get after we remove characters we need to find a sticker that has those characters so what we want to do is we want to know for each word so for each word we're going to have a map um for each character in that word to uh the count of that character so this will tell us for each sticker um how many times we can use a character so essentially this problem you may think that there's some clever solution but not really um the algorithm is quite straightforward we're going to try we're going to start with we're going to see how many we can make then we're going to call a function recursively um after we've removed as many characters as we can and then we're going to basically keep going to see whether or not we can actually get our string down to an empty string because an empty string means that we finished it and we'll start from each of the characters and we will sorry each of the stickers as our starting point and then we will just continue until the point where we realize we can't do anything because there's no intersection between um our Target string and any of the characters in our stickers or we'll actually be able to reduce it to zero so there's really only two ways that can go either we solve it or it's impossible so essentially at each point of whatever our Target string is for each character in our um sticker we basically have to make a decision a binary decision do we take a character so take a character or multiple if possible or leave it right um so for each one we need to do that now I'm not going to bother going through uh walking through an example because it's just much too complicated and it's a DFS problem with recursion so trying to draw that out in the tree of recursion it's just way Overkill and it's only going to complicate matters but we have a general idea of what we want to do we want to keep track of all the stickers in a word and basically see how many at each iteration we can take away now I've purposely left this quite vague and hard to understand because I will explain everything line by line in the code editor I don't want to waste too much time uh here so let's now move to the code editor and type this out okay so we saw the basic intuition for this problem but like I said I left the explanation part a bit vague because it's not worth it to go over um on paper it's just too complicated it's better to just do it line by line in the code and it'll make a lot more sense the first thing that we want to do here is actually for each string we or sorry for each sticker we need to know exactly what characters are in them because remember we need to chop up those stickers so we can use the characters in them so what we're going to do is we're going to say that sticker uh sticker counts is going to be a list and it's going to contain a dictionary which Maps each character to um the amount of its frequency in that sticker so we're going to say um it's going to be a list of collections. counter and we're going to pass in sticker uh for sticker in stickers so basically you know the indexes will still match so stickers of zero uh sticker counts will just be the dictionary of the counts for that sticker okay now that we have our sticker counts uh like I said what we want to do is we want to use uh memorization here with our DFS and the reason for this is because you know we might be able to remove some characters um and as we basically go through all the possibilities there will be a lot of duplicate uh things for example what was our thing it was like the hat or something if we remove um in the first iteration if we take a sticker and remove these two uh then we'll have eat but then what if we remove these ones it's going to be the same um amount of characters that we still need to delete so we need to find a way to memorize this and also smartly um memorize it such that um because these two words are the same right um eh HT this these are the same amount of characters so we don't actually want to process them twice um whether or not you are able to remove from the strings will depend uh it's the same for both of them they're just in a different order okay so we have the memo now we need to write the DFS function so let's write it DFS and we're going to have our Target string which represents the string that we're trying to build uh from all of the um stickers right so if the Target string is um empty that means that we've actually removed all the characters that we need to remove and we're done because we finished right we're able to get a solution so what we want to do here is if not Target string so basically if it's empty then we want to return uh zero and we're going to be returning basically the number of ways that we can actually um build that word so obviously in this case if it's zero then we don't need to use any stickers so we just return zero the next thing we want to do is actually check whether our Target string is in the memo dict uh if it is then there's no reason to recalculate it we can just use the um memoized solution so we're going to say if the Target string uh is in memo then we simply just want to return memo of the H can't type today of the Target string sorry should Target string uh okay so that's pretty straightforward now what do we do now we actually need to do the processing so what we want to do is actually find stickers which will give us characters that we need but which characters do we need we're going to want to put this into a dictionary such that we can process it uh in an efficient way we don't want to be scanning the string every single time for each character we better just pay the price up front to build a dictionary so we're going to say the target counter so this is going to be a count of our Target string of all of the characters and their frequencies so this is going to be collections. counter of the Target string so now we have a mapping of all of the uh um characters and their frequencies in our Target string pretty straightforward now we need to basically have a local uh variable to store our answer and we'll update this as we do the DFS here so in the beginning it's going to be float Infinity because we haven't found anything yet so we're going to set it to infinity and we're basically just going to try to minimize the amount of stickers uh to basically form Target string obviously if there are no stickers then it should stay at float Infinity because that means that we actually can't um produce it so what we want to do now is basically just try all of the stickers and here's what we're going to do so we're going to say for sticker in sticker counts what we're going to do is we're basically just going to say is there one letter um is the first character of our Target string is it in this sticker right does this sticker have at least one of the characters and we're just going to use to make it simple the first character here so we can avoid like trying to overprocess things we're just going to do things um whatever the first character is if it doesn't have that character then we will just not use that sticker if it does then we need to process it further so we're going to ask ourselves is the first character of our Target string is that in the sticker so if it's not in there then we don't care about this sticker because we're not going to use it right and we're always just going to try to take the first character um and then if it's not in there then we just continue if it is then we need to process right okay so if we were to take this sticker so we now know that this sticker has at least one character we're after but obviously it could have potentially more characters after because we didn't consider any of the other um indexes other than zero so what we want to do is we actually want to update our Target counter we want to take as many as we can from this Cur current sticker right and the way that we're going to do this is you can actually subtract two dictionaries and when they have the same Keys um it will actually subract those keys for us and anything that's not in one dictionary won't like it won't become negative when you do the subtraction it's just if the keys are there it'll subtract um the values from you know the second dictionary uh so for like you'll have dictionary a dictionary B if you subtract them um and we're doing this for counter by the way um this is like the way the data structure works if you have the same key in a and b um it will just subtract the value of the keys um of B from a but it won't actually go below zero uh it will actually just set it to zero if B has more keys than a so this is just you know you need to know your data structures here that counter works this way I guess you could do it manually but luckily counter kind of saves the day on this one so what we want to do is figure out how many characters are remaining after we take um this current sticker so we're going to say that the remaining um characters is going to equal to our Target counter minus the sticker right so remember that Target counter is a collections. counter which is a dictionary which Maps the character to its frequency and same with sticker because we're actually iterating over um sticker counts and not the original stickers and remember that sticker counts is the same thing collections. counter and like I said when you subtract two collections. counters object any keys that are the same between them will get subtracted um and it will actually default to zero if um if sticker B here actually has more than sticker a it won't go negative so that's good to know okay so that will basically take the remaining characters we have so now we were able to basically use that sticker and now we need to move on to the next bid right so we took some characters from our Target string now we need to basically see if we can still form the string uh lower down kind of we need to now try more stickers to see if we can get to zero right but the problem is that our remaining characters are now going to be in a dictionary we need to actually build a string out of it right and the way that we're going to do this is we're just going to process um this remaining thing so we're going to say the letters and we're going to use a string Builder here and we're going to say um what is it so we have the Char and it's count um so we're going to have a character and it's count in the dictionary so we want to basically add that character however many times it shows up in our dictionary um for what is it so it should be Char count in remaining uh characters do items so this will basically build out the characters um we need to use and obviously we need to represent them however many times they show up in our dictionary so that's why we multiply by count again now this is a list of uh strings and we need to join everything together so we're going to say that the next Target string so next Target is going to equal to what so we want to join together our letters here and that will give us our next Target string now what we want to do is we want to actually call our DFS function here and the answer will be the minimum of whatever our current answer is and whether or not um we find a solution from our DFS right so we've just used one sticker here so one plus the DF the result of calling DFS on the next Target so this will be uh how we're updating our answer and this will run for basically all of uh the stickers we have right uh and it looks like I'm actually not indenting this correctly this should be indented there we go okay yeah it needs to be under the for Loop okay so we will run through all of the stickers kick off the dfs's as we go and then basically answer will hold um the global best answer for you know taking whichever sticker gives us the best result at this point because some may better uh be better than others and we're really just trying them one by one okay now what we need to do is actually update our memo dicks because remember we want to use our solution here over and over again because at some point we will have duplicated work and we don't want to recalculate it so we're going to say memo of our Target string because that's what we just processed is going to equal to whatever the current answer is and now all we need to do is simply just return the answer and luckily that is the end of our DFS function so let's just review what we did here first thing we did was checked whether or not the Target string was empty this means that we're actually done and we can return zero because it would take zero stickers to transform an empty string into an empty string right second thing we did was check whether or not we've actually already computed this string by checking if it's in memo and returning it if it is otherwise we got all of the characters and their counts in our current um Target string we created an answer variable to store um our kind of local solution here then we tried every single sticker and we wanted to check whether or not um the first character in our Target string was in that sticker If it wasn't then we'll just move on to the next sticker and if it was then we got basically the difference of the two character counts of the two dictionaries here so Target count is this one that we created up here and the sticker remember is this um dictionary which maps for each sticker it's characters uh to its frequency and the reason this works is because these are collections. counter objects and we can actually never go below zero and it will just update the keys for us again you can do this manually if you're not using python um but it is a little bit extra work luckily we are using python so we can kind of just rely on the magic of collections. counter but it's still a good thing to know that this is the behavior of the data structure so your interviewer you know may just ask you to clarify that and at least you know that it works this way the next thing is because our remaining characters are um in a dictionary we need to create a string builder for this and then we basically just join the string Builder to get a string and then our answer would be the minimum of whatever the current best answer is and then one plus cuz one we just use a sticker so we have to count it plus whatever amount of stickers it takes to build the next Target then we updated our memo dict and then just return the answer okay that was quite the mouthful let me sure make sure I don't mess up the indentation here again so it looks good all we need to do now is simply call uh answer um is going to equal to DFS of Target and then we need to return the answer if answer does not actually equal to float oops it's not equal to float uh infinity obviously if it's float Infinity then we were never able to find a solution uh which means that we couldn't actually use any of the stickers uh in this case we need to just uh return minus one whoops okay wow that was a long problem and I bet you I messed up some indentation somewhere oh okay never mind um miracles do happen Okay let's submit this and accepted cool thank God this problem is horrible all right so let us finish up here by talking about the time and space complexity like I said this problem really boils down to for each string that we have or sorry for each character in our Target we make a binary decision of whether to take a character or not take a character um from a uh what's it called from a sticker right so essentially we have two to the N uh checks that we need to do right because we need to basically check whether or not um we take it right so the two represents that we have two choices and we do it n times for n characters in our sticker and we also do this m times where m is the number of stickers and then n equals the length of the original Target so our runtime complexity here is going to be Big O of 2 to the n * m and going to be Big O of 2 to the n * m and going to be Big O of 2 to the n * m and ASM totically this is probably just 2 to the m because this 2 to the N will grow much faster um than this part so we can actually probably just get rid of this as a constant and it should be 2 to the m but for completeness we're just going to say that it's 2 to the n * m to say that it's 2 to the n * m to say that it's 2 to the n * m and then for the space complexity obviously we need to store basically all the possible um variations of Target string and this is basically going to be 2 to the N because there's like two to the end possibilities of how we could basically chop up Target string taking um one character at a time so time complexity bigo of 2 to the n * m space complexity bigo of 2 to the n * m space complexity bigo of 2 to the n * m space complexity 2 to the n okay thank God that is done this problem is absolutely horrible you can see why it took me 2 years to do it as a matter of fact when I was interviewing at meta I just didn't even bother with this question I was like if I get it okay I'm yeah I whatever luckily it's actually much um easier than I thought uh maybe it's just wisdom of age who knows anyway that's enough rambling hopefully you enjoyed the video hopefully you at least leave me a like and a comment and a subscribe for the pain that I just went through trying to solve this bull problem and you enjoyed uh me suffering through it to give you guys this hopefully easy to understand solution anyway thank you so much for watching I will see you in the next one bye
Stickers to Spell Word
stickers-to-spell-word
We are given `n` different types of `stickers`. Each sticker has a lowercase English word on it. You would like to spell out the given string `target` by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker. Return _the minimum number of stickers that you need to spell out_ `target`. If the task is impossible, return `-1`. **Note:** In all test cases, all words were chosen randomly from the `1000` most common US English words, and `target` was chosen as a concatenation of two random words. **Example 1:** **Input:** stickers = \[ "with ", "example ", "science "\], target = "thehat " **Output:** 3 **Explanation:** We can use 2 "with " stickers, and 1 "example " sticker. After cutting and rearrange the letters of those stickers, we can form the target "thehat ". Also, this is the minimum number of stickers necessary to form the target string. **Example 2:** **Input:** stickers = \[ "notice ", "possible "\], target = "basicbasic " **Output:** -1 Explanation: We cannot form the target "basicbasic " from cutting letters from the given stickers. **Constraints:** * `n == stickers.length` * `1 <= n <= 50` * `1 <= stickers[i].length <= 10` * `1 <= target.length <= 15` * `stickers[i]` and `target` consist of lowercase English letters.
We want to perform an exhaustive search, but we need to speed it up based on the input data being random. For all stickers, we can ignore any letters that are not in the target word. When our candidate answer won't be smaller than an answer we have already found, we can stop searching this path. When a sticker dominates another, we shouldn't include the dominated sticker in our sticker collection. [Here, we say a sticker `A` dominates `B` if `A.count(letter) >= B.count(letter)` for all letters.]
Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Hard
383
35
Hello Welcome back to Anonymous Data Scientist Channel Today we will solve Lead Code Problem 35 Search Insert Position What we have in this is a sorted array is given and we are given a target value. If our target value is inside the array then we have to return its index. If it is not there then we have to return the index where it can be inserted in that sorted array like example number one, in this we are given the target value of f, then the index number of f is 02, so the output is 2. Similarly, here we have given target value to, now two does not exist in this array but whatever two comes, it comes in between one and r, so what is its index number, one then one comes in the output, similarly sen. Here, if it comes last, its index number becomes four, so let us see once how to do it. Once you pause the video, think for yourself what you can use in it because it is a very simple question, you have read it. Yes, we will use binary search in this because the array given to us is sorted, so if we ever have to search in the sorted array, then it is obvious that we will apply binary search in it, so we will apply binary search here, binary search, it is not known what we will do. We will place a left pointer here, we will place a right pointer here and will find the mid value. We will find the mid value. What will happen by multiplying L PS R? Here we assume y but if we calculate then what will be zero plus in our case 0 plus 3. Batu, this one will come, okay, now one will come, so that means our this will come here, now what will we do, our mid pointer will point out here, the mid pointer will now point out here, our target value is five, which is If it is greater than our mid pointer, then we will update our left pointer after that because obviously our left pointer will come here because our target value is greater than the mid value so it will exist on the right side only. So we will update our left pointer here, now what will become our new mid value, that will become our value 2 p 3/2 and h which will come to x 2 p 3/2 and h which will come to x 2 p 3/2 and h which will come to x now which is two means that this f is doing our target value. If there is then we will return the lower second example. What do we do in this? We take the carry in which our target value does not exist. Now we will return the index where our target value should be added. So what will we do again? Our left pot will take the right pointer. Okay, now we will do the left pointer and the right pointer. We will get the mid value from here. What will come to get the mid value? To get the mid value, we will do this. 0 plus 3 will come to the right. Now the value will come. One on one, our mid will come here, our mid value will assist here, now we will check that our target is smaller than the mid value, so on the right hand side, on the left hand side, sorry, assist this side here because our array is If it is sorted, then we will update our right value and bring it here. If our right value is updated here, then now we will check that our target variable is to, now which is to, now what is our L and R key here. If the values ​​of r are equal then If the values ​​of r are equal then If the values ​​of r are equal then our loop will still run, the loop will end only when the value of r becomes less than l, then the loop will run again, then what will be the mid value 0 + 0/2 means value. what will be the mid value 0 + 0/2 means value. what will be the mid value 0 + 0/2 means value. Now the mid value will also come here. On top of this, our mid value is smaller than our target value, so what we do in this case is that we update the pointer on our left. Now update this. If we give it, then where will we bring plus and se L, meaning whatever is our L and if it is zero, then what will it become, it will become one. Now after that, if we run our loop, then the value of our L will shift here. And our right value is here, so our form will end here, so after the end, we will return our lower value, meaning our two should come on one index one. Let's code it once. Just apply binary search and do nothing else, let's start, we will define our left and right, first we will keep the left at zero, we will make the right as length of numbers minus and then after that we will run a loop while L is equal to R. Run the loop till it is there and our mid will come out. Now the mid has come so if our target value is equal to our noms our middle value then we will directly return the mid because that is our found out. If it is not so then it means else if our target value is greater than the value of our names then what we do in this case is our target value is greater means it is on the right side then we will update our left mid plus Now in the case of else from one, where our target value is small, what will we do in this, we will update R from mid minus one because our target value is present on the left side, now we will return our left value, that's all. It was the same work, I ran it is running, submit it, if you have any doubt, you can ask in the comment section, see you in the next video, thank you.
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
1,689
Hello Guys Welcome to Video Series According Suggestions or Drop by Drop Problem School Partitioning * Minimum Number School Partitioning * Minimum Number School Partitioning * Minimum Number of Tasty Minor in Numbers What is the President Number It is the number which consists of its 0ur number 90 has not had any living being considered to be Positive Energy Number 231 3232 Rum In A Boat And Different Ways Of Looking At You Lately Snatching This Bag 1232 But Is The Sellout Know Its Lowest Price Hotel Requested In The Question Is What You How To Use Only The Results For Boys Us Know How To Make A Call Using Only The Richest Women G So Let's Country The Unit Digit You Need To Do This You Need To What You're Doing This You Need To Can You Make To You Zinc Dros Left Side 108 In Any Way To Make A Call To The Number 135 Good Note In WhatsApp A Morvan Shift More Once Him To Make A Note To You Can Also Take Late Se Twelve Vs Ricky Ponting Test One Ok Google Call To The Number 100 What You Want The To The Number 135 Make Money Online From Behind The Way To Make Subscribe That Shows You How To Take Three Lions To Make Three So You Can't Lose 1031 Say It Out Loud Use Unit Minimum 3512 You Write Three One Two Three Numbers And Logically The Thing For Example Of The Answer is Prithivish It's Just Once You Will Not Be Able to Make the Number You Need to Take Minimum 310 OK and You Will Be Us Minimum Free Numbers of Units Luther King to Make a Phone Call Two Three Four 44000 Minimum World Number One Of The Most Unique Number One Is Particular Digit 2018 Paint Most Unique 2581 Chuke Iss Number Denge Number Simple Maximum The Video then subscribe to the Page if you liked The Video then subscribe to the Bell Icon to 5 7 Points 2827 Subscribe C Plus To Get The Interior Valid Se Intercurrent Which Represents Current Value Tension Please Subscribe 428 Soft Example2 Subscribe - 8 - 8 Example2 Subscribe - 8 - 8 Example2 Subscribe - 8 - 8 Finally Bigg Boss Ko Maximum Volume Maximum That Sudeshwar Simple Problem But If The Problem Is Something Which You Can Think About Animals With Solution this video maximum digit soch final video oo in som s great a separate thank you for watching patient and listen
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
1,982
hey what's up guys this is chung here uh so this time it's called number 1982 find array given subset sums uh so this one is a very interesting yet very hard problem and so the description says you're given an integer n representing the length of an unknown array that you are trying to recover right and then you're also given like an array sums containing the values of all the two to the power of n subset sums of the unknown array in no particular order okay and then you need to recover that array the unknown array uh you just need to return any of them okay right and note that task so there it's guaranteeing that there always be at least one correct answer right so first a few things so what is the subset i think most of you should already know the subset and y is 2 to the power of n so this should be pretty straightforward right let's see if we have two values two uh numbers here right let's see it's one three right so what is the total subset for this one right so the first one is always zero right the first one is always like i'm empty which means we're not we don't pick anything right so the second one is peaking one and then 3 and then it's what a 1 is 3 right so that's a subset okay and subset means that the order doesn't matter right and 2 to the power of n that's the total number of the subset because if we have a number another five here right we'll have like eight in total right so that's how we get this one and the sums here basically it's giving us the total okay the total for each for all the subsets and for example right so let's say we have n is equal to three right and obviously this the length of sums how many sums will have we have two to the three of 2 to the power of 3 which is 8. that's why we have 8 total sums here okay and as it listed here right because we have different subsets and the output is this so basically we have three numbers one two and minus three and this one can give us these subsets okay and then here's the here's another one and that's that so the constraint is like uh it's like it's only a 15 right length okay so to solve this problem you know um we need to make a few observations plus we need to have some like knowledge on some basic subsets uh concept right um so the difficulty for this problem is that you know it allows you to use a negative value i mean if this one were only allowing to and positive value that'll be a lot easier but and i think even that we it's i mean it's not that easy but comparing with this negative value right it's easier but to solve this problem we have we need to use that easier uh version as a base so which so let's say uh we only allow positive value or non-negative values or non-negative values or non-negative values uh for this problem and how can we solve it right uh let's try to use an example here okay uh let's say we have three when we have three numbers right we have one three and five okay so that's the three numbers we have here and so how about the sums right for all the subsets so obviously we always have zero means that we're not picking any numbers right and then we have uh one number which is one three and five right and then two numbers uh one three is four and then one five is six right and then three five is uh is eight and then in the end we have nine here okay so we have this number this uh sums list and how can we recover this uh this one the original array here so to solve this one uh assuming everything all the numbers are positive we need to make so one of the observation is that you know the second smallest number in this one is one so what does this one tell us basically this one has to be one of the numbers basically it has to be the smallest number of the current out in this array here that we're trying to recover right and why is that because since every other numbers are positive right and because any time when we pick two numbers the number the sum will become bigger right so which means the smallest the second smallest number besides zero will be the smallest will be basically will be one of the numbers in this array for sure right which in this case is 1. okay so and let's say okay we already find one number we which is one right and now we have two numbers left which is x and x okay and how can we find these two numbers so in order to do that right we are we have this kind of eight sums in total what we need to do is that we need to divide this uh sums into two halves which means we need to divide it in into this uh two halves and why we need to do this because obviously you know with two numbers the total sums where uh the total subsets will be four in this case right and if we can find right if from this eight sums if we can find the four sums for this two numbers then we can utilize the same logic to find another number right similarly as how we find this one from this eight subsets if we have four subsets for these two numbers then if we sort it right and then the second smallest number will also be at the number uh one of the numbers in this two number which is going to be the smallest number as well right okay so and now our question is that how can we split this to basically how can we find those four sum uh subsets or four sums for these two numbers okay because we already have one here right and we know that every time when we add one number to an existing subset we're doubling the total sum right that's why we have that's why we from four we have eight and if we have another numbers from eight we'll have 16 right and after splitting the if we're trying to split this one into half so what do we have you know we are if we try to remove this one from this subset what we will have so let's say we have a this part a uh this one and this one if we do a plus one okay so this upper case plus one will equal to the lower to this uh lowers lower group okay and if we okay so which means that you know because um because by including one here right for example uh let's by including one here with existing uh subsets right basically we're adding one to each of the existing subsets for these two numbers that's why you know if we divide this sums into two groups the upper group plus one will equal to the lower group okay and this upper group will be the group the will be this the sums for this the other two numbers right because you know for example let's say we have nine here right so in this case let's assume we sort this number we sort this uh raise from the biggest to the smallest right so the biggest is nine so the nine should deny obviously will belong to the lower group right because the knight is the biggest right it is the greatest number and this one has to come from some number plus one right that's why the knight is here and then we will have like eight right so now we have eight here and then what's next and then because eight and nine are gone right these two are gone and then the next biggest number six right so now we have six and then we have five right same thing now six and fives are gone so the current biggest is four right and then we have to put 4 below here because it cannot be here because if we put it 4 here you know 4 plus 1 will be 5 but we don't have 5 in the sum sign anymore right so that's why we're going to put 4 here and then three here and one here and zero here right so now we have split this sums into two groups and the upper group will be the group that for the other two numbers the numbers that we haven't recovered right so now we have zero three five eight and as you guys can see we can just apply the same logic to this group right so now we have three as a second smallest number and which means three will be one of the numbers in this group here right so from here we got three we'll have three as a number okay and then with three here we can just split this one into two parts again right by applying the same logic will be this one right so now we have eight here now this one instead of plus one we need to plus three right so it's going to be five and then here it's going to be three and zero right so we have three here and now here it's zero and five right so this one obviously whenever we only have two numbers left right so we have five right that's why we have one three and five right so that's how we uh solve uh a easier version for this problem which only allow us to use a positive number okay yeah because you know this one is going to be like they're basically this one doesn't have any branch right it only has one uh one path because it guaranteed us it there will always be a like uh as a solution a result right that's why we can always split this one into two half and then basically uh recover all the rays here all the numbers here so if you understand this part right and we're going to use the base the same similar logic to solve this problem which in which allows us to find the uh allow us to use the negative value okay so if you take a look this one a little bit closer you'll figure out so what's the most important uh idea in this problem so first is that we do a divide and conquer right so we divide this into two parts and the prerequisite of us dividing these sums into two parts that we already figure out one number already right that's how we can divide this one into two parts because we already know that uh one is one of the answer right one of the number so if we can find a one of the numbers and then we can divide this sums into two parts but the question is that with the negative values how can we find this number okay um so let's say we have some negative values so we have a negative and then we have a positive something like this okay uh so assuming we also sort the sums from smallest to the biggest okay so we have a max right so what does the max equal here the max is equal to what obviously let's say we have some negative values and positive values so the max will be all the values uh all the sums for the positive numbers right okay so that's that right all positive numbers are positives how about the second max so what is this how about the second max so what does this one do so the second max could be so for this one we have two options here we have two scenarios so the first scenario is that you know the second max will be this one will be this part uh except for the smallest a positive number right so that's could that could be the uh one of the second max val sum right or what could be all the positive values uh plus the biggest smallest number right so this is going to be the second uh second option here right so basically since we have these two options right it could be either including this one or inclu it could be either like representing this one or including did this one right either the first uh positive number or the last negative value and if we do a subtract between these two right and what we'll get either this one or this one right obviously you know this one could be a this is a positive number and for the negative one you know we have to reverse the uh the sign here right so now we have a we almost have like a fixed number right but in our case you know remember so for the all positive number case you know there's no branch we simply just follow this one divide and conquer algorithm and it will definitely give us the final the right answer but in this case right we'll have like two branch here it could be either this positive number or it could be this a negative number so which means we have to try both right so for positive numbers here right we can simply use the same logic right basically we will try to pick from the biggest number right we sort this array we pick the biggest number and then we try to find if there's a matching a number uh you can find uh like if we basically if we can divide uh these sums by using this positive number right but how about this negative value right if okay if we're trying to uh to use these negative values how can we divide how can we uh divide this one it's almost the same the only difference is that we have to start from the smallest right because and why is that because you know by including this negative values from the original subset sums right all the sum all the subset sums will become smaller since this one is a negative value and that's why you know when we try to find split these uh sums into two parts we have to try from the smallest value first okay let's say we have a if we have a smallest value here right basically we have a smallest value here this one like this is the sums right all the sums here we have to try inside of from the beginning we have to try sorry instead of trying from the end we have to try it from the beginning it's going to be the smallest value right because from this one uh because from uh this similarize this knight here right let's say this one is negative 10 right and our number is like let's say it's negative so it's negative two okay so with negative ten right if we do a negative term plus two we get a negative eight right so which means that this we have an active ten here it's going to be a like this one right it's two parts so which means that you know below here we have negative 10 and here we have negative eight okay so which means that you know the negative eight so this one will be the uh the subset for this remaining numbers here okay because um since by like i said by including this new uh this negative values all the sums will become smaller right that's why similarize how we uh get the biggest value for the positive case we need to start from the negative case because like sorry i think sorry about repeating myself because i just want to make sure you guys understand this part because like i said so the reason being that you know again so for negative 10 since the smallest value right and we are sure that you know the 10 has to be long have has to belong to the lower case right because if this one if the 10 belong a negative 10 belongs to the upper case then this minus 10 a then also do a minus 2 will become it's going to be a minus 12. but it doesn't exist that's why the minus 10 has to be in the lower part right and then we do a then we have minus eight and then we keep finding the smallest of the kernel just like how we did for the positive one right and yeah i think that's pretty much the basic idea so we have this part for the positive case scenario and for the negative case we use the maximum sum subtract the second max sum and then we have a value right and then we have to try both the positive value and the negative value because it could be either of these two scenario right and then with these two numbers we'll try to split them up okay and then we'll basically try to find a correct a find out like a path that can lead us to the end which means we'll only have will only have two numbers right i know and one of them has to be zero right uh i think that's a long explanation uh let's start coding then and maybe uh i will explain a bit more so um so like i said we need a dfs right so we have a sums here and then um and then here is return the dfs of the sums right um so before that let's sort these sums okay because we want to process the meter from the start or from the end right um okay so the base case is this so we have the n is for the length of the sums and then basically if n is equal to two right so which means we only have one line we only have two left right um let's see we will return the non-zero ones right the non-zero one the non-zero ones right the non-zero one the non-zero ones right the non-zero one which is the uh how community how can we return it we can do this we can do a sums remove this is like such a lousy way of doing this but okay i think there should be another way of doing it some start zero okay yeah i think so basically i simply remove zero from the sums and then i just return the other one okay as i mean as a number okay and then we have x right so we have x gonna be the sums of minus one minus sums of minus two basically this is the maximum subtract the second maximum assuming this thumb size already uh sorted right so now we have we need to try two scenarios right so first one is we try positive x okay so to try the new the positive x uh we have let's say i'm going to have a new sums one right okay so there's a trick here because like i said so when splitting this two splitting this number the sums into two parts right so assuming this sum has already sorted uh we don't want to remove it right we don't want to remove from the list you know like even though i said you know we after picking this 9 8 we want to remove 98 from this array so that it will not affect the others but removing is kind of expensive right so if we're doing that this one this will tle so what we can do is here instead of removing it we can simply mark that number it's not usable right how can we do it we can simply do a counter right so we can count the appearances for each of the number right and then every time when we find a match we simply just decrease the count by one right so we have a counters of this and then for a oh and since we have the counter here right um and since we have like so we tried we part like we tried this number here right and this number minus x could be a uh the corresponding part could be like this one right and so that's why we want to process from here to here right and we process them one by one and then that's why i'm going to do this so i'm going to sums up i'm going to reverse these sums right so we have a b going to be a minus x right so which means so this a is the lower part right and the b is the upper part okay so and then we track this one so if the count 1 of a it's positive has a value and the count two of b is positive okay and then we know okay we have five we find a we find like a match right a pair that's why we have we can just uh new sums one dot append to b right and then we do a count one we have to decrease the count right and then we do a count one of b right we decrease this two and then we move to when we move to here right you know because since we're where we're trying the numbers from the biggest to the smallest and then we're sure that each number all each a here will be the biggest number in the current sums array because we already because we remove the previous biggest number from the from this array by decreasing the frequency okay and then here in the end we check oh by the way so here i know i was trying to do something like this you know if it doesn't work it doesn't couldn't find it i was trying to break it but this is wrong because you know it could be the account 1a is empty right and then we'll still try to do it right we still try to we still need to move the cursor uh forward to keep trying the others okay um i think there might be another way basically if this one is not empty but this one is empty right so if that's the case then we know i think then we can break it yeah i think something like this i think we can do this okay so if right count b is um it's not empty then we do this right else right as i think we can break some we can break here so that can uh improve the performance a little bit so let's see okay now we have this answer one this one gonna be this so basically we check if the length of the of this new sums one is equal to the n divided by two right so we check this basically we're trying to see if we can successfully split these sums into two parts right so if the length is equal to the half of it then we know okay we have already it's we have split this one right successfully that's when we can do the recursion which is going to be the x right plus the dfs of the new sums one but here we have to reverse it okay so here what i'm trying to do is that you know i'm trying to find a way uh to give us to find us the correct answer right so first we know okay so if we have successfully split it and then we know because so the number the x will be one of the number so the remaining will be what the remaining will be we need to pass in the remaining sums to it right so here i'm and but we don't have to sort it anymore because we are processing from the biggest smallest right and then things will do append here so after doing this so this new sums will be already sorted from the biggest to the smallest right that's why i revert it back to its original sorting which is the smartest to the biggest so that we don't have the sort for each of the dfs okay so that's answer one right but remember this answer one could not be the answer right because we also have answer two here the answer to is we try the negative value right i mean i think we can i'll just try to copy and paste negative so we have a sum two column two right and then here we're gonna answer two sum 2 here so for this one you know we want to like i said we want to process from the smallest to the biggest that's why we don't have to reverse it right but this one like we have to do a plus x right remember so we have a we have this one right we have this uh minus 10 right so then the x is minus sorry the x so the x will be a minus 2 in this case right and then for this one we're trying to find the minus 8. that's why we do a plus x okay and so we have count two sorry this one yeah and here uh we don't need to reverse it right because we are processing from smartest to the biggest it's and it will still be assorted so it's going to be answer 2. right so now we have these two answers one of them is the answer and the other one is not right because we always know there will be an answer and how do we know which one is our answer right so obviously you know the one who has the who has more fields who has more numbers will be our answer right i mean so we can do it something like this so we also it returns the ones if the length of the answer one is either greater than the length of the answer two right else answer two okay um yeah i think that's it right i mean this should work but i guess this will tle oops parameters to generate types must be did i oh yeah color it's a function oh i see uh so here we have uh there's some like uh educate no some scenarios we haven't taken into account which means you know this sums has to include zero all the time basically it failed here because it's trying to remove zero but it doesn't exist and why is that you know remember so no matter how we split these two parts right so the remaining parts you know we have this one three five right so this one is we find it and then we're trying to get the sub subset for the remaining two numbers right which means that you know they always be like zero because zero means we don't pick anything right so which means that you know as long as the sum to zero does it does not exist in the sums which means it's not a valid path right i think we can simply do a check here so if zero not in sums right and then we return empty you know we reached empty because you know we're using the length to very to verify uh if this path is a correct one right and if this path is not and then we simply return empty which will result to a shorter answer here right and yeah so let's try it again okay so this one accepted so let's try to run it did i oh i think i know what happened uh here so when we try the negative case instead of x we need minus x right yeah so it works right um not fast but it passed that's all it matters i guess so yeah that's basically the implementation here um so this product so this one is crucial because you know this one can help us remove a lot of uh invalid scenarios right and otherwise you know otherwise if we do it if we don't if we only check it here let's see if we only if we check it here right so let's see if we check it somewhere here instead of at the very beginning okay if that's the case you know if we run it again i believe this it will tle this is because you know let's say the current sums yeah see it's dle let's see if the current one doesn't have a zero let's see it's a 3 6 10 12 something like this one i'll be definitely it's not it will not be a valid path because you know like i said 0 should always be there because we zero means we don't pick anything right and so in this case we there's no need to keep splitting it into half right into two parts and that's why we so that we can basically determine it early right that's why we remove this one move this one all the way to the top to do some pruning here okay yeah and so for the time complexity um so as you guys can see we have how many dfs here right so we have what every time we split this one into half okay so let's say for example we have n here right so which means for each of the and each of the time uh then we are processing a minus one length uh sorry not a minus one like n minus one numbers okay every time we are removing one numbers from the sums here and in total we have n numbers that's why you know and every time we are splitting in splitting this one into two parts which means it's going to be a 2 times 2 to the power of n right so that's the branch the total time of the branch and for each half the branch we do a for loop right so we do a counter we do a for loop and it's going to be a times n in this case right so that's going to be the total time complexity for this one yeah i think that's it for this problem um i mean just to recap right i know this one is a very hard one and it's a long video and so first we uh we're trying to solve this problem by assuming there's only one there's only positive numbers and then that's when we figure out okay we can fit we can just use fix one number right and then we try to remove the number from the sums from the numbers by splitting these sums into two parts right and then we do it in a recursively so that we can get the numbers one by one right but in that when it comes to this problem since we have negative values here uh this one that's why you know we have we'll use the biggest number minus the second biggest number to get x right but for this one in this case we have two scenarios the x could be either this number or it could be this number right and we have to try both and for the positive in the positive case it's the same as the pas the easier version right so we start from the biggest number right and then we try to split them into two parts and for the negative case we need to start from the smallest number and then we split into two parts as well and when we do the splitting uh we use the counter right to improve our performance uh instead of removing the numbers removing the number from the arrays right and then in the end since we have two scenarios we'll pick uh we whichever can lead us to the final answer and which is the uh the one that has the longer length that right the bigger length because it's guaranteed we always have an answer right and yeah and oh and one more thing so here's a little uh trick here we only sort once at the very beginning and then later on since we're always either process from the biggest or smallest or process from smallest to biggest we simply just need to reverse it if we want to keep the original sorting right uh cool i think that's everything i want to talk about for this one and thank you for watching this video guys and stay tuned see you guys soon bye
Find Array Given Subset Sums
remove-duplicates-from-an-unsorted-linked-list
You are given an integer `n` representing the length of an unknown array that you are trying to recover. You are also given an array `sums` containing the values of all `2n` **subset sums** of the unknown array (in no particular order). Return _the array_ `ans` _of length_ `n` _representing the unknown array. If **multiple** answers exist, return **any** of them_. An array `sub` is a **subset** of an array `arr` if `sub` can be obtained from `arr` by deleting some (possibly zero or all) elements of `arr`. The sum of the elements in `sub` is one possible **subset sum** of `arr`. The sum of an empty array is considered to be `0`. **Note:** Test cases are generated such that there will **always** be at least one correct answer. **Example 1:** **Input:** n = 3, sums = \[-3,-2,-1,0,0,1,2,3\] **Output:** \[1,2,-3\] **Explanation:** \[1,2,-3\] is able to achieve the given subset sums: - \[\]: sum is 0 - \[1\]: sum is 1 - \[2\]: sum is 2 - \[1,2\]: sum is 3 - \[-3\]: sum is -3 - \[1,-3\]: sum is -2 - \[2,-3\]: sum is -1 - \[1,2,-3\]: sum is 0 Note that any permutation of \[1,2,-3\] and also any permutation of \[-1,-2,3\] will also be accepted. **Example 2:** **Input:** n = 2, sums = \[0,0,0,0\] **Output:** \[0,0\] **Explanation:** The only correct answer is \[0,0\]. **Example 3:** **Input:** n = 4, sums = \[0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8\] **Output:** \[0,-1,4,5\] **Explanation:** \[0,-1,4,5\] is able to achieve the given subset sums. **Constraints:** * `1 <= n <= 15` * `sums.length == 2n` * `-104 <= sums[i] <= 104`
Is there a way we can know beforehand which nodes to delete? Count the number of appearances for each number.
Hash Table,Linked List
Medium
82,83
1,455
Hello hello brother this welcome to another interesting problem not only from coding school forward do specific of any word in a sentence and easy problem sunil grover two examples for example I love eating burger is the sentence k 122 search category a certificate of duties words morning forward I love eating and burger heaven safiq pure for the world in the sentence and answers-2 return for ur so let's start answers-2 return for ur so let's start answers-2 return for ur so let's start doing in python first and will move want to see plus let's fry come award in any threat of sentence on its own sentence plated Plated space and want to create a list in python and ordered list will be separated by words which were present in the sentence and using in greater noida mu-1 i come varsha i will give me the index mu-1 i come varsha i will give me the index mu-1 i come varsha i will give me the index of 2014 awards and observed and will start from From zero to return the phone quote for example in directions love meeting burger sentence I don't have to return free ok by the way 0123 big prudent for survival after return i plus one businessman x plus one iswara condition side so let's see the connection is satisfied with water starts With Search Words Start With Secretary We Can Just One I Plus One Otherwise They Can No Return - Tied In Python I Hope Can No Return - Tied In Python I Hope Can No Return - Tied In Python I Hope David Villa Work And Target Category It's Working Let's Effective Work In For All The Test Cases Working For The Test Cases And Will Also Bay Cleared Vitamin C Plus And Toilet Beam Is And Translation Logic And Brett Lee Stuart No C Plus Wife Is Sentence I Love Eating Here If N Is Too Short To Word Which Is Gold Berg Listen Is This Is The Time To Search And Deserving Of Science Of 428 Duis I Will Operate Spring Dale School Check N Am Going To Check All The Words Subcenter Sentence Nlc That Is That Prefix Of Work So Let's Get Started Swayam Counter The First Character Limit Invent A Sentence K Encounter First Character Who Is To Directly in the growth in character is cod space vinod achha - world before a to k wherever e see this cod space vinod achha - world before a to k wherever e see this cod space vinod achha - world before a to k wherever e see this page and water before it's so i know that dhawal decide and acquits mirch a ok and the types of forest berg but adjust know that is not The World is on the Side Pay Subscribe Button Superintendent Kunwar - Superintendent Kunwar - Superintendent Kunwar - Tractor And By Making Check Again To Mt This String To Convert Next Character Should Start With Boys Characters Of Space They Can Keep Continue According To Store This Characters In The Calling Improved Next Characters Pen Its Characters At this time strangers vikram love noida govardhan at character beard space one who has got award for rapists should avoid having eyes after festivals capable of checking if it contains the prefix bargi dam looking for deposit is city size equal to the size of my shirt word with just FOR YOU CAN ALSO CHECK AND MAKE HIS FORM LOVERS PET RELATED DIGESTS HAVE SO I'LL JUST AMAZED MT AGAIN AND DUMPED BY MAKING IT AGAIN WILL HAVE TO GO TO THE CHARACTER SHOW THE FORCE CHARACTERS ONLY CONNECT CHARACTER APPS CHARACTERS ENTERED SPECIAL TIPS TO RING THE WORLD Is The Character Is Indore Check String Tractor Mein Characters Live Voting - Characters Which Mein Characters Live Voting - Characters Which Mein Characters Live Voting - Characters Which They Can Stop And Check Soil Check Is Dasha Is Celebrate Thee No Record To Dar Places Which Its Creator The End Of Course Will Just Be A Gift For Characters Of Check Box Office Character leaders not equal to the search button but for specific class so they can just make this a meeting and over to make of next characters I have character some VPN stored in the characters you next character is our and will have g din tha and ok and have Different hydrating scientists were in but keepake account number encounter special account to real declare account exactly 205 and space have increase account on account Vikram 1.23 for boil existing account it Vikram 1.23 for boil existing account it Vikram 1.23 for boil existing account it means 3 ok back to 9 inch one this last word Allah for this last date of Birth Check Be Just Giving And Condition Because From Not Incarnate S Per Schedule Of Its Users To Exit Them For Loot Create 512 Check This And Conditioner Blasts Where Last Word Contain Effects Of Lagengi Children Condition And This Time We Check Condition Improves Blood The Word Is Burger Certificate Heaven Okay So Conditions 272 Return Account Plus That Bigg Boss Main Account Will Have In Just Three Left Turns Free Plus One Wishes For That So Let's Start Writing Course Credit System Clear Water Will Have To Decided To Create A String Majervant Absolutely 2012 Kauthig Check and they will celebrate in account in the return ban in open account 2011 to take 2 medium size of are search world today can check only and size it thing capable to folder prefix for search words to enter into words for starting over all care c Turn of Sentence Preferred Character of Sentence S2 Hydrate Over and Whom He Will Have to Do the Checking File Check If I Don't Have Seen on MTV Europe Music Award The subscribe and subscribe the are not equal to a word can't over the next day subscribe m0 is equal to the search word in condition improves the world can return account plus one in this world can that instrument i one subscribe nano increment i account and dum oil se increment merchant and make ready string to be easy against that mic check Will Again Welcome Equal To Anti Poaching Cases Condition Is Not Spider-Man President And Space Sexual Just Keep Spider-Man President And Space Sexual Just Keep Spider-Man President And Space Sexual Just Keep In Preventing Check Will Love You To The Character Tenth C And Did For This Is Not Able To Give Me The Nation Will Not Be Checked For the last word of the sentence subscribe The Channel and subscribe the Channel Plus One Can No Return - Channel Plus One Can No Return - Channel Plus One Can No Return - Vanshvriddhi Tay Office Song Setting Satisfied 100MB Character Who is Equal to and Space Ki Sudhir Warning Bed Wearing Getting So Let's See Who Were Getting This Point Ko Bhi Forgotten To Give Space Switch Off To Give Its Place And For Everything In Its Getting Accepted S O S Financial Solution Time Complexity And Please Like Subscribe
Check If a Word Occurs As a Prefix of Any Word in a Sentence
filter-restaurants-by-vegan-friendly-price-and-distance
Given a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`. Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one word, return the index of the first word **(minimum index)**. If there is no such word return `-1`. A **prefix** of a string `s` is any leading contiguous substring of `s`. **Example 1:** **Input:** sentence = "i love eating burger ", searchWord = "burg " **Output:** 4 **Explanation:** "burg " is prefix of "burger " which is the 4th word in the sentence. **Example 2:** **Input:** sentence = "this problem is an easy problem ", searchWord = "pro " **Output:** 2 **Explanation:** "pro " is prefix of "problem " which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index. **Example 3:** **Input:** sentence = "i am tired ", searchWord = "you " **Output:** -1 **Explanation:** "you " is not a prefix of any word in the sentence. **Constraints:** * `1 <= sentence.length <= 100` * `1 <= searchWord.length <= 10` * `sentence` consists of lowercase English letters and spaces. * `searchWord` consists of lowercase English letters.
Do the filtering and sort as said. Note that the id may not be the index in the array.
Array,Sorting
Medium
null
942
welcome back everyone we're going to be solving leak code 942 di string match so we're given a permutation of n plus 1 integers of all the integers in the range from 0 to n which can be represented as a string of length n where the ith position inside of that string is equal to I if the ith position in our permutation is less than the next position in our permutation and the ith position in our string will be equal to D if the ith position in our permutation is greater than the next position in our permutation so we're given a string and we need to reconstruct the permutation and return it and if there's multiple we can return any of them okay so we're returning an array so let's just get that out of the way right away we'll say res is going to be equal to this array and we're going to return this res at the end okay now what well let's take a look at this let's say we have this first example right the first position in our string is I so what does that mean that means whatever is inside of our array at the uh this first position has to be less than the next one right and they do that 0 and 4. so how can we achieve this well we can have two variables let's call them low and high we will set low equal to zero at the start and then we will set High equal to whatever the length of our string is the length of us Okay so now what let's run through let's continue through this example let's say the first position is I right so we know it has to be less than the next one well we know low is already less than high so let's just append the low right it'll be zero for the first iteration okay let's move on to our next iteration we see that the second character in our string is d all right well let's take a look at our constraints again well it's D so we know that the current position we're at inside of our permutation has to be greater than the next element we place inside of it okay and we know that the previous element has to follow this constraint where it has to be less than the element that follows it right okay so let's just put the value of high into this position right so let's say it's 4 for this right just to follow the example okay that satisfies the first constraint but now we have to satisfy this one okay let's say we had a d at the third position instead of an i what does that mean that means this value has to be greater than the following value okay well after that iteration we just did if we decrement High the next value we would place inside of it would be three right that still follows this constraint where the previous element is greater than the next one so if we continue through this iteration and just update Low by one whenever we use that variable and update High by decrementing it by one when we use high we'll be able to make this permutation and it'll make a little more sense when I when we type it out so let's do that so we know we're gonna have to iterate through our string right so let's say four character and S what are we going to do well we have to check if that character is an i or a d so let's say if character at or if the character in our string is equal to I what do we do well let's append low right let's just say res that append low and then like I said we'll update them accordingly whenever we use low we're just going to increment it by one okay now what we've settled the case for I let's settle the case for when we run into the letter d and that's these are the only two cases we have so we can use an else block here we'll just say else res Dot append hi and then we'll update High by decrementing it by one okay so what now what do we get at the end of this s of C okay so for we're looking at positions here so four character and range length of s is what I should have wrote okay this is what we get we end up with zero four one three right so why is this wrong this is wrong because even though we're given um we're given a string of four of length four right we need to go one extra because that was in our um our constraint so all we have to do is uh just keep continue following these constraints that we have and how do we solve that at the end after we exit this entire Loop the easiest way we can solve that is just by adding um the low variable One Last Time into our resulting array so if I do res dot append low and then print out res you'll see that we'll get the correct answer right zero four one three two and that's exactly what's expected let's check out case two we have three eyes they want zero one two three we have zero one two three so let's um what do we have to return the array instead of printing it so let's just return res and there you go we pass all three test cases let's submit and we see that it does pass so what is the time and space complexity of this algorithm well we know we're doing a for Loop here and we're touching every single element inside of our original string and appending it to our resulting array so that's going to be o of n our runtime will be o of n now for the space complexity the only other data structure we're dealing with is a return array right what is inside this array it is going to be the number representations of our uh string s so it's going to be what are we returning we're returning the length of our string plus one so that will be our space complexity it'll be s dot length plus one or we could just say it's just going to be the length of our return array and that'll do it for elite code 942 di string match
DI String Match
super-palindromes
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**. **Example 1:** **Input:** s = "IDID" **Output:** \[0,4,1,3,2\] **Example 2:** **Input:** s = "III" **Output:** \[0,1,2,3\] **Example 3:** **Input:** s = "DDI" **Output:** \[3,2,0,1\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'I'` or `'D'`.
null
Math,Enumeration
Hard
null
953
hey everyone welcome back and let's write some more neat code today so today let's solve facebook's most asked question of 2021 verifying an alien dictionary and the funny thing is i think this was also facebook's most asked question of 2020 so i guess they really like to reuse questions but let's get into the problem and you might recognize that we've actually solved a very similar problem to this as before we've solved the alien dictionary problem which was actually a very hard problem and the good news is that this problem is a lot easier and this problem itself is actually a sub problem of that alien dictionary problem so if you've solved that before you'll definitely know how to solve this if you haven't solved that before i think that's a that other problem is a really good follow-up other problem is a really good follow-up other problem is a really good follow-up problem to this problem and i will probably link it below if you want to take a look at the solution for that problem as well but for this the premise of the problem is pretty similar so we're given an alien language that happens to use all 26 lowercase english letters but the difference is that in the alien dictionary language these 26 english characters a b c etc right are they could be in a different order than the a through z order that we are all familiar with the alien order could be some permutation of the abc order and we are given a sequence of words of the alien language that are or should be in sorted order based on that alien language and we want to return true if these words are actually sorted based on the alien language and we want to return false if they're not sorted based on the alien language and we are actually given what the alien ordering happens to be so instead of a abcd all the way to z the alien language in this problem is actually in a different order you can see it's h l a b et cetera right so it's a different order than we are familiar with and we're also given this list of words that should be sorted in order now obviously in real english these two words are sorted how do we know that hello comes before leak code in english order because we look at the first character right we compare character by character these two characters are different right the first different characters are how we compare two words right since these characters are different we want to know okay which one of these characters comes first of course we know h is less than l in english order right h comes before l in the uh english language right so of course in real english h hello is going to come before elite code is that also true in the alien language well let's take a look so we're looking for characters h and l we can see that h is actually the first character in the alien language and l is the second character in the alien language so yes even in this alien language these two words are sorted correctly so we return true of course we can verify the alien dictionary based on the first differing character but suppose we were given two words such as these words we compare character by character right we're looking for the first differing character so we look at the first characters they're both h so they're not different so we're gonna look for the next character that happens to actually be different we look we find an e and an e so again we shift now notice how one word was a prefix of the other because we reached the end of one string but we did not reach the end of the other string so in this case this word was a prefix of the other word so then the question becomes which one of these words is supposed to go first basically it works the same way as in english if one of the words happens to be a prefix of the other word then the smaller word goes first if so therefore this is a true uh alien dictionary right this is verified as true but if it was the opposite if we had uh you know he come after hello that would be wrong right because we reached the end of the second string but then there's still some characters left in the first string so that this would basically be false right we can't have something like that happen and if you kind of want to know why it's basically okay we reached the end of this string so it's basically an empty character and here we have an l so what is smaller technically an empty character aka a space or whatever you want to call it is always going to be smaller than any real character so that's why he comes before hello so those are the only two rules that you really have to know to verify this alien dictionary so now we can finally get into the code now let's get into the code you can see that i basically summarized the two rules that we have up above basically we're looking for the first differing character if we can find it if we can't find the first differing character that means one word is a prefix of the other if word a is a prefix of word b then word a must come before word b so word b must come after word a so the first thing we want to do is actually get the index of every single character and put it in like a hash map or something so that's what i'm going to be doing so i'm going to go through for every index character pair in our input order string in python you can enumerate it to get the index and the character at the same time we're going to use the character as a key and we're gonna use the index as the value so that's pretty much what i'm doing with this one line so then when we do find the first differing characters we'll be able to compare which one actually comes first in the alien dictionary so then we just need to go through every pair of words in our words array and make sure that every pair of words is in order so we can do that pretty simply by going through every single word the length of words minus one because we're gonna be comparing every single pair every adjacent pair so we can get those words now word one and word two that we're going to be comparing word one is going to be the word at index i word two is going to be the word at index i plus one and now we just want to go through character by character in the words we're going to go in range of length of word one because word if the words happen to be similar or if word one is a prefix of word two then we can reach the end of word one and we'll verify that it was in correct order but if we reach the end of word two before we reach the end of word one in which case this would happen right uh the j happened to be the length of word two but somehow we were still in bounds for word one that means that word two is a prefix of word one which is not allowed so if we've ever reached this condition that means we have uh determined that this is not verified we have to return false in this case we reach the end of word two before we reach the end of word one and we didn't encounter any differing characters and word two obviously comes after word one you can see that i plus one so in that case we would have to return false if we don't reach that case we're going to be looking for the first differing character so let's go character by character if the character in word one is not equal to the character in word two then we have found our first differing character now we just want to know we just want to verify that the character in word one comes before the character in word two in our order index map so if that's not the case basically if order index of word to the character in word two happens to be less than the order index of the character in word one that means we do not have an a verified uh word list right because word two is supposed to be greater than word one the character in word two is supposed to be greater than the character in word one if we have the opposite that means that this is not verified that means we have to return false but if the opposite is true that means these two words are verified we're not going to return true quite yet because we might still have some words to iterate through but at the very least we can go ahead and break out of this for loop meaning we can stop comparing these two words we already found the first differing character and it happened to be valid so we don't have to continue and if we end up going through every single adjacent pair of words in our words list and we never returned false either by finding differing characters or by finding some prefix that was out of order then we can go ahead and once the loop is done executing we can go ahead and return true all the way outside of our for loop and of course i always have typos for some reason i took the length of words but we actually want to take the length of words that's what it's actually called and then that gives us the optimal solution as you can see it runs pretty efficiently basically the overall time complexity is the total number of words the total number of characters in all words in the input so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
Verifying an Alien Dictionary
reverse-only-letters
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters. Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `words` are sorted lexicographically in this alien language. **Example 1:** **Input:** words = \[ "hello ", "leetcode "\], order = "hlabcdefgijkmnopqrstuvwxyz " **Output:** true **Explanation:** As 'h' comes before 'l' in this language, then the sequence is sorted. **Example 2:** **Input:** words = \[ "word ", "world ", "row "\], order = "worldabcefghijkmnpqstuvxyz " **Output:** false **Explanation:** As 'd' comes after 'l' in this language, then words\[0\] > words\[1\], hence the sequence is unsorted. **Example 3:** **Input:** words = \[ "apple ", "app "\], order = "abcdefghijklmnopqrstuvwxyz " **Output:** false **Explanation:** The first three characters "app " match, and the second string is shorter (in size.) According to lexicographical rules "apple " > "app ", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ([More info](https://en.wikipedia.org/wiki/Lexicographical_order)). **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 20` * `order.length == 26` * All characters in `words[i]` and `order` are English lowercase letters.
This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach.
Two Pointers,String
Easy
null
1,189
hey everybody this is larry this is day 13 for the september leco daily challenge hit the like button hit the subscribe button join me in discord let me know what you think about today's for our maximum number of balloons why are these in weird funky fonts uh okay so yeah i usually start this live um yeah so if it's a little bit slow just watch it on a faster speed why not okay so i mean this is programming live this is the live part anyway uh okay enough about that let's talk about giving a text string text oh yeah one thing i would say is that i am still going to continue to do this um throughout but actually i don't know the exact timing but i might be a little bit like over the all over the place of the timing because i'm going to be in lisbon for a couple of weeks so you know and i'm i don't know what because i think this gets out when it's like 8 a.m or gets out when it's like 8 a.m or gets out when it's like 8 a.m or something and that's a little bit too early and maybe i would i just too early or i'm doing sunrise photos or something i don't know so we'll see uh hit the instagra uh hit the uh drop me on instagram you want to see some of my photos but anyway today's problem is maximum number of balloons so given the text you'd like to form as many instances of rooney you can use to each character most once it doesn't have to be in order okay so this is a very silly one um because you don't have to because you can do it in any order right so that means that you only carry up carry care about uh the number of times p excess number times a excess the number of elevators and so forth so right off the bat we're going to do counters you go to collections.counter and that just means collections.counter and that just means collections.counter and that just means that we put everything in a map uh time to characters to the number of um appearances there are so this is the frequency table right uh that's required frequency table and of course i'm just being lazy of course because you can actually make a small optimization um that makes this like you know because you don't have to store any character that's not in balloon but you know so you go from olaf what is that over five or five to all of 26 for all of alpha for the number of uh characters you know um yeah and then now we just have to do i mean you can do this a number of ways we can play around with this one um maybe we'll just do neces i mean you can also even hard code this to be honest um or need it maybe you could hardcode this by saying something like okay like or you know something like you can do something like this and i think that should be good enough i mean you know let's pretend that i finished writing this out as i say that um i think this is actually the answer um but of course you can also write a for loop as well uh well i mean obviously i would take out this one but that's basically it unless i have a typo oh did i mess up something i guess this could be all zeroes no i mean that should be okay what am i doing counter object is not callable oh whoops using the wrong thingy even now i'm making mistakes why am i making so many mistakes oh yeah so this should be good i mean it's not as uh it's not as pretty maybe but it'll be good enough right like this is going to be good you can also just do the same thing but put this here like for example you have another input then you can just do something like this where maybe banoon is a variable then now you have uh min is to go to the min of frequency of x over needed of x for x in needed dot keys or something like this and this should also give you the right answer as well uh unless i also have a typo somewhere because i've been having a lot of tables lately sorry about that but it's not intentional but yeah so yeah and of course this could have been an input in that case and of course you don't even actually need this to be aware well but uh but i'm going to keep it this way just for kind of fantasies and yeah the only case that this may be zero is because if need is zero so i think we should be okay we can also test i was going to test no characters but apparently that's not a possible input because i just looked at this and yeah and i don't even have to look at the com the end that much to be honest because you know i have an o of n algorithm right so how slow can it be um that said yeah um but yeah so this is all n because for every character we have to look at it wants to build this frequency well table for space this is of alpha where alpha is the number of alphabets which in this case is 26 of course you like i said you can compress this to only care about the characters that you care about needed but yeah and of course you know we now have this as a possible input of you know here we hardcoded but yeah um you know it's a monday problem i guess it's a little bit easier so that's what i have with this one um stay good stay healthy have a great rest of the week i'll see y'all later bye oh and to good mental health bye
Maximum Number of Balloons
encode-number
Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible. You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed. **Example 1:** **Input:** text = "nlaebolko " **Output:** 1 **Example 2:** **Input:** text = "loonbalxballpoon " **Output:** 2 **Example 3:** **Input:** text = "leetcode " **Output:** 0 **Constraints:** * `1 <= text.length <= 104` * `text` consists of lower case English letters only.
Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits.
Math,String,Bit Manipulation
Medium
1070
1,701
hey everybody this is larry this is me going over q2 of the bi-weekly contest 42 average wait of the bi-weekly contest 42 average wait of the bi-weekly contest 42 average wait time so this one um so most of the uh time i spent on this problem was basically making sure the constraints are what i thought it was uh if not i would have put it in the correct order which makes it a sorting problem um but it's a little bit weird only because they give it to you in the exact order that you need it and it's uh here and it is a non-decreasing order so basically you non-decreasing order so basically you non-decreasing order so basically you can do it with a for loop um with an average rating time so then the idea here is just well it actually is just simulate exactly what you get right which is that okay you're given a time that um it arrives and also add the time that it takes the cook to serve and that's pretty much it and then you make sure that you know if a person came in later then they their start time is later right so basically my code is very short and you could have probably uh wrote less if you want to but i you know like i said during the contest i'm trying to optimize for time it took me about two minutes and i would some of that was just me not sure because i was like this feels a little bit too easy but ah you know sometimes we're lucky than good uh so t is a terrible wearable name but that's just the time of the last um last completed order so that you know you can either move forward in time or that's your constraint of when you uh arrive and then total is just the total amount of wait time for everybody and then the average is just over that uh here is just you know the now this is the new time so basically this is the delta between um when the customer arrives and when it is first getting cooked and then this is just a cooking time and then we reset the next completed order to that new cook or we add it to the we add cooking time to it so this is obviously linear time and constant space because we only use extra variables um yeah i'm just trying to refresh to kind of see what the total acceptance uh about half an hour into the contest and about 1500 people selled it out like 6 000 people so a lot of people have solved this um yeah i'm just trying to figure out why it was a little bit weird uh but yeah a lot of what i spent was just making sure about constraints and once you realize that then it should be okay i think a more slightly more interesting but still the same problem is that if they're given a none uh none not uh they're not given to you in order and you have to sort it in some way then it becomes a sorting problem which is slightly more interesting but still probably a little bit on the easy side um but yeah let me know what you think that's all i have for this prom uh you can watch me solve it during the contest live uh next and remember to hit the like button subscribe button join me on discord ask me questions i always enjoyed that and i was yeah and you can watch me sub next silly mistake okay average wait time okay this is a silly palm so it should be okay now hmm that's not right oh hey uh thanks for watching thanks for the support remember to hit the like button and subscribe and german discord ask me questions i love questions uh let me know what you think and i will see you next problem bye-bye
Average Waiting Time
remove-max-number-of-edges-to-keep-graph-fully-traversable
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers **in the order they were given in the input**. Return _the **average** waiting time of all customers_. Solutions within `10-5` from the actual answer are considered accepted. **Example 1:** **Input:** customers = \[\[1,2\],\[2,5\],\[4,3\]\] **Output:** 5.00000 **Explanation:** 1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. 2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. 3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. So the average waiting time = (2 + 6 + 7) / 3 = 5. **Example 2:** **Input:** customers = \[\[5,2\],\[5,4\],\[10,3\],\[20,1\]\] **Output:** 3.25000 **Explanation:** 1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. 2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. 3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. 4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. **Constraints:** * `1 <= customers.length <= 105` * `1 <= arrivali, timei <= 104` * `arrivali <= arrivali+1`
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use Type 3 edges first, and connect the still isolated ones using other edges.
Union Find,Graph
Hard
null
11
hi guys it's been a while since we did a problem on lead code and as you know being too far away from lead code for a long time can be injurious to one's health or at least injurious to one's um one's coding health so we are back to doing late court and i'm really excited to do this problem this is right now container with most water it's lead code 11. given in non negative integers a 1 a 2 3 a n where each represents a pointed coordinate i a i n vertical lines are drawn such that the two endpoints of the line i is at i a i and i zero find two lines so basically that's just saying that i'll give you a bunch of um an array with values and these values actually represents the heights of the lines at that particular index so um zero for example when your index is zero here and a i will be the length at g of a zero so e zero in this case for example is one here similarly the index here is uh the ai here is eight so that's uh just easy find two lines which together with the x-axis forms a which together with the x-axis forms a which together with the x-axis forms a container such that the container contains the most water and you may not slant the container and that's i guess um it's not much of a problem that's already assumed now lines are i think that slanting is because you know your area calculations become easier if you don't slant so max area water the container can contain is 49 as you can see in this case um the so let's just start from imagine we start with the container here like imagine you take the line the at index 1 so and then this is i guess 0 one two three four five six seven eight nine or if you take one to eight i guess right one two three i think this is height as i'm wondering if what is the distance between these so if it is 0 and this is 1 and i'm assuming that this is two but they don't seem to be equally spaced right so um if i'm assuming let's see this here are they that the distance between them is just one unit apart if there are they are one unit apart then it's very easy because you know you go from here one and that is 2 so that is 1 2 3 4 5 6 7 and 8 right so that's the x axis distance between the left motion the right most multiplied by one so that would only give you eight but if you take the one that he has shown you here in that case it will be seven times the height of the last one so that's 49 and that's why it's coming out to be 49 but why that is the max area in this case the most border container what if i have any other possible combinations of these lines so if i take for example like this right most and this left most is most likely is not going to the case already because as you can see this is 3 and then you will have if you take from here one two three four five six only be 18 right so that's not a good combination either that's not the max area next container either so now if you take for example this guy in this guy so then you get eight minimum of the two is still eight and you got one two three four five so eight times five is only 40 but this one is 49 so as you can now you can see that it's that this indeed is the biggest um the container with most water so similarly now let's take this uh there are only two lines one and of course output will be one and take this one four three two one four um this is easy because you got one two three four times the min of the left and right 4 times 4 is 16. 1 2 1. so if you were to draw this let's say 1 2 1 so you'll have 1 and then you have 2 and then you have one so the minimum height whatever combinations you use is going to be one only one times the maximum x-axis one only one times the maximum x-axis one only one times the maximum x-axis span could be two one and one so that's why it's two so what approach can we what approaches are possible here let's talk about that like what approaches what algorithms can be we can take here so one of the approaches is the brute force and as you know interviewers usually don't like this brute force approaches but it's good to kind of maybe you know a couple of minutes talk about that hey look i do know that's the approach but and i know you're not going to like that but it's not something that we would like to implement in the production code because it's going to be extremely inefficient so the brute force approach would be that let's say you start with two nested loop on like you start with a loop outer loop with i equal to pointing to this guy and j pointing to the i plus one this guy and you iterate over keeping the outer loops index same you trade over all the possible combinations in the inner group and then you repeat that you go back to the outer loop change your that pointer index to the next very next element and then you go for j equal to i plus 1 you just set and you do the same thing now that approach is as you know is going to be n squared because you have this nested loop anytime you have nested loops you will have n square or if you have nasty loops maybe let's say three times then you have o n raise power q so that's why these are usually avoided because you know as n increases um exponentially or if n goes to like from 100 to 10 000 you will basically just your run time will be exponentially increasing that's why it's a very bad idea so let's see what is the next approach we can take can we do better than that so for that i would what we can do for that is how about let us just say that we start with two pointers or indices pointing to the leftmost element and the rightmost element and then uh what intuition can be used here so now let's just start with i equal to pointing to one and j point into um eight because this is one this two versus three four five six seven eight or nine actually and nine minus one is eight though right so that this span is eight so you would have end up having area of basically eight but um it as you can see this approach um now uh so this is one container uh what should we do then from then on now as you know if you want to find a better container uh between these two um these two extremes that we have um what do you think where do you think we should move should we move this guy we should remove this guy now let's say as you can see the moving the right most guy when the leftmost guy was the minimum is not a good idea because the minimum you already have here unless you if you move this side let's say here it was even bigger than that or as long as this guy is the minimum the leftmost guy you basically constrained by your um your area of being limited by that because you see the you will be changing these x-axis x-axis x-axis the span on the x-axis but your y will the span on the x-axis but your y will the span on the x-axis but your y will be just basically pretty much by limited by the minimum of that element so the intuition i would say here is that you start with the left two indices pointing to the two extremes and then you basically adjust them according to which one is minimum of the two so if the left side is minimum it makes more sense to basically advance that to see if you have a bigger element and then basically calculate area from there to keeping the right side as it is and if the right side is minimum like in this case for example what you would have tried is now you see it so happens that immediately the right side becomes the minimum of the two so it makes sense to basically go and try to say if we get anything bigger than that because that's the minimum that's the one that's the constraining factor maybe you have an element much bigger than that and this will happen here but before that happens before it is there you have to move and when you move you will find that you'll end up on this element and this is in this case will be even lesser than what you had last time now you will move here which is um which is basically you'll find that this time the minimum of the two is in the right so you move right to the um once one you basically advance or decrease whatever you want to say then you see now there's the same height and then you will see that you will end up having this area over here right so that is the approach we'll take so when you have um whatever side you have the minimum the two that is the side that basically moves okay so let's see how we can solve that now as you can see we are going to try this first time in c plus most of my solutions so far i've been doing have been either in python or in c but this time we want to try c plus because that's apparently not that hard as we thought so what we're going to do is we'll have a variable accumulator as the call where we keep track of the largest area seen so far and then we have left index pointing to 0 and we have right index pointing to now how do we find the if it was c we would have int a and comma length was in c you have to pass the length of the array as a parameter to the function but in this case since we are given vectors stl vectors it's not too hard either all we need to do is height dot size we need to know that vectors have a method known as size that gives us the length of the that vector and since the indexing in c and c plus happens in starting from 0 to the size minus one so that is why right will be pointing to the right most element will be i dot size minus one now you see what do we do so now let's start our loop so the loop will go we can actually do something like this you know why because we can move as long as they're not same and when they hit into each other that's when we can get out so now what would be the area good point of being see is that you don't have to declare everything in the beginning c plus is that you don't have to declare all your variables in the beginning of the function actually even this would have been allowed in c words inside a block so let's calculate the area and area is going to be i mean so now we are taking these vertical lines and finding the minimum of the two so that's your you basically pass it to the main macro or function whatever the heck it is you basically take the minimum of the two lines two vertical lines you multiply that by the total span of right minus left on the x axis right now all you need to do is that if area is greater than largest area then we basically reset the largest area to area and so that part is done now all we need to do is move the left and right indices depending upon which one was smaller so that is if height the vertical line on the left is less than the vertical line on the right then all we need to do is we have to basically advance the left side as basically advance the right side now you see if they are same it doesn't matter you can basically move either way so that is why we don't have we just have less and then the greater or equal to is so oh sorry actually this will be because you have kind of going backward right when you're on the right most element you're basically moving to the left so that is why you have to decrease not increasing when your left most you are moving towards right so you have to increase so this is done at this point our while loop is finished and all we need to do is return largest area and this we'll try to run first let's see if we get any success here um road four so i see that there's some problem here okay that's easy to fix because we forgot to comment out these lines all right so that's accepted and the output is as it is but before we submit i want to just basically talk about runtime complexity in the space complexity so i haven't i've basically left out the point two here which is what do you think is going to be complexity now because you see we are only walking once so that's why we are walking the array that is given to us on the vector whatever you want to call only one so that's when now that's your time complexity now and the space complexity also is o n because you see we have not done any extra memory allocation or anything like that so it is all looking good let's try to submit and see if it works and there you go it's basically we have a success here and we're getting 24 milliseconds faster than 77 percent of c plus 12 online submissions it's all looking good so what do you think should be our strategy now do you think that we can improve up upon this solution or we are basically hit the dead end as far as the optimizations are concerned so what you think should happen if you find that moving the indices makes no sense like we adjusting you see now what's happening is that we don't even care now you know what i will leave that exercise as a brainstorming exercise for you as a kind of a homework for you to do to see if this can be optimized further are there any scopes for optimization and if so if you can write in the comment section i would really appreciate and it's kind of leaving a little bit out is good for all of us because it gives us rather than having the ready-made rather than having the ready-made rather than having the ready-made solutions and leaving nothing for you to you know to go and do as your homework is not a good thing so i think there's one optimization possible here which is that if you move to your like when you change when you adjust left and right there could be a potential optimization i'm thinking because imagine like in this case or for example imagine you are at this case this is black here sorry the red here in the black here now why do you think it makes no sense to basically or even like for example just take this case why do you think it makes more sense to try now this combination now imagine we already tried this combination we got 49. now should we try the combination with this black line in this red line here why do you think it's of no use because even though this is smaller and we are saying that hey this is the limiting factor and we would like to say there's anything bigger which was here so maybe adjusting from going to here was okay but there's no there was no point in changing or trying out or calculating the area for this combination because there's no way this is going to be more than that so i would leave that for your creative juices to keep flowing so that you get to try something on your own and with that i will see you in the next video and my apologies for keeping away from uh lead coding and not having any more videos to basically watch so i promise to bring you more videos as time goes by it's very fun exercise it's definitely better than wasting your time on destructive activities like day trading or game stop or any of these speculative investment activities actually speculation is not even an investment so um so and that is just one destructive activity i mean the life can be full of many destructive activities so we have to be away from them and come to the constructive activities and i think lead code is definitely a very constructive activities not only good for the activation of our dormant brain cells but also to basically have fun while basically trying to exercise our mental capacities so with that last ending note i leave you guys to keep trying out more exercises on late court and happy interviewing and even if you're not interviewing and you're just doing late code because this is the best thing that can happen to you then all the power to you and i will see you in the next video i do take care bye so
Container With Most Water
container-with-most-water
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`. Find two lines that together with the x-axis form a container, such that the container contains the most water. Return _the maximum amount of water a container can store_. **Notice** that you may not slant the container. **Example 1:** **Input:** height = \[1,8,6,2,5,4,8,3,7\] **Output:** 49 **Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49. **Example 2:** **Input:** height = \[1,1\] **Output:** 1 **Constraints:** * `n == height.length` * `2 <= n <= 105` * `0 <= height[i] <= 104`
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle. Area = length of shorter vertical line * distance between lines We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
Array,Two Pointers,Greedy
Medium
42
1,578
to daily contest day third of October lead Cod Challenge the problem that we have in today is minimum time to make rope colorful here in this question you given an array of colorful balloons arranged on a rope what do you need to identify the minimum time needed to make the Rope colorful and what is a constraint specified in the question as per the constraint no two consecutive balloons of same color should be together you also given the time needed to remove each balloon present in the array and you need to identify the minimum time needed to fulfill the above constraint so I'll be talking about more from the algorithmic perspective about the question why the presentation so let's quickly hop on to it and I'll also explain this algorithm over there so let's quickly move on to it now let's focus our attention on to one example I've have taken a slightly longer example so that you guys get a good hold of the underlying concept here I can see balloons of five different color the first one is of dark orange next is green next is yellow then it's light orange followed by Blue the question says no two balloons of same color can be together that means here out of this slot we'll have to remove three balloons out of the total four here out of these two balloons we'll have to remove one here out of these two balloons we have to remove one and if I ask you which one are you going to remove so you will be removing that one which takes least amount of time because what you want to do you want to identify the minimum time needed to make the entire rope colorful in nature and rope can be made colorful by removing consecutive balloons that have the same color this is the Crux of the problem guys if you have understood this much then your solution is done what I'm trying to say let's try and understand it by the two-pointer approach so the it by the two-pointer approach so the it by the two-pointer approach so the two-pointer approach will help us two-pointer approach will help us two-pointer approach will help us identify the bucket or the cons ative balloons that have the same color so this bucket is of length one so I'll have my start pointer here only and also my end pointer here only since there is only one balloon uh then that means we don't need to delete any of it let's proceed ahead the next bucket that we have will be over here the starting pointer will be over here and the ending pointer will be over here and what I'm going to do I'll be delet eating all those balloons that takes least amount of time to be removed so which one is going to take the least amount of time to be removed out of these four the first one is this the next one is this followed by this one so how many balloons do we have in total we have four balloons and we will be removing these three over here and how to identify this up if I ask you then it's again really simple you iterate over the sum of all the balloons that have same color so what is the total sum of all the balloons that are same color 2 + 5 is 7 + 4 is 11 + 3 is 14 so 2 + 5 is 7 + 4 is 11 + 3 is 14 so 2 + 5 is 7 + 4 is 11 + 3 is 14 so this bucket slot has the total sum of 14 and you can keep track of that balloon which has the maximum removal time which here in this case would be five that means you will be retaining five and you will be deleting the rest of the balloons so how many balloons are you deleting you are deleting 2 4 and three you are retaining this five so 14 - 5 you are retaining this five so 14 - 5 you are retaining this five so 14 - 5 gives you 9 that means in order to remove all the three balloons of green slot total amount that is required is n is of 9 units if you want to formalize this mathematically then the equation would be sum of all the balloons that correspond to the same color as in this case is represented by 2 + 5 + 4 + 3 case is represented by 2 + 5 + 4 + 3 case is represented by 2 + 5 + 4 + 3 you'll be iterating over this and you'll be finding the total sum of for those balloons that have the same color toal total minus you will be subtracting that balloon that has the maximum removal time which in this case is five so total minus Max and by virtue of this you have calculated the minimum time needed to remove rest of the balloons that have the same color which here in this case is 2 4 and three so this is the Crux of the problem total minus Max and let's apply it over to the next slots as well here we have two such balloons that have same color represented by yellow so start would be pointing over here end would be pointing over here and uh here the total sum will come as three you will be retaining the maximum one so 3 - 2 gives you 1 uh so maximum one so 3 - 2 gives you 1 uh so maximum one so 3 - 2 gives you 1 uh so out of this one unit of time is needed so let me just write one over here let me just write 14 - 5 is me just write 14 - 5 is me just write 14 - 5 is 9 and let's proceed to the next slot which is of D what is the total of three and four is 7even so let's write seven over here what is the max time of removal of corresponding to one balloon out of these two the max time of removal is 4 so 7 - 4 gives you 3 that means three so 7 - 4 gives you 3 that means three so 7 - 4 gives you 3 that means three units of time is needed uh here in order to remove all the balloons that have the same color so let's write three over here and the last slot has only one balloon so we are going to skip this up so this is gone what are the times that we have identified 9 1 and 3 so the total turns out here in this case as 13 and we can keep track of this by storing it in a global variable and we'll keep on adding as we proceed towards the iteration across all the balloons that we have this is in syn with our expectation this is a very typical problem of two pointers you just need to keep track of uh the buckets and you need to identify the total sum that corresponds to each bucket and the maximum element that exist over there without further Ado let's quickly walk through the coding section and I'll exactly follow the same steps that I have just talked here I have taken few pointers start end total time and N for keeping track of the length of the input string while my start is less than n and my end is also less than n I've have taken two local variables Max time and Group total till the time I keep on finding the same color across end and start pointers and my end is less than n what do I simply check which balloon will take the maximum time I add the current needed time at the endmost interval onto my group Total and I keep on incrementing my end pointer as I progress ahead so this will give me the maximum time that corresponds to one particular group and Group total will give me the sum of all elements that I have in that group and once I have it I simply subtract these two up and add it to my total time uh for the next iteration to happen appropriately I update my start to end with this uh one once we out of this V loop I simply return the total time variable and let's submit this up the time complexity of this approach is order of n the space complexity of this approach is again order of n u no sorry the space complexity is not order of n the space complexity is of constant time and uh with this let's wrap up today's session I hope you enjoyed it if you did then please don't forget to like share and subscribe to the channel thanks for viewing it your subscription truly means a lot to me so if you want to see more of coding decoded videos please guys hit that Bell icon thank you
Minimum Time to Make Rope Colorful
apples-oranges
Alice has `n` balloons arranged on a rope. You are given a **0-indexed** string `colors` where `colors[i]` is the color of the `ith` balloon. Alice wants the rope to be **colorful**. She does not want **two consecutive balloons** to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it **colorful**. You are given a **0-indexed** integer array `neededTime` where `neededTime[i]` is the time (in seconds) that Bob needs to remove the `ith` balloon from the rope. Return _the **minimum time** Bob needs to make the rope **colorful**_. **Example 1:** **Input:** colors = "abaac ", neededTime = \[1,2,3,4,5\] **Output:** 3 **Explanation:** In the above image, 'a' is blue, 'b' is red, and 'c' is green. Bob can remove the blue balloon at index 2. This takes 3 seconds. There are no longer two consecutive balloons of the same color. Total time = 3. **Example 2:** **Input:** colors = "abc ", neededTime = \[1,2,3\] **Output:** 0 **Explanation:** The rope is already colorful. Bob does not need to remove any balloons from the rope. **Example 3:** **Input:** colors = "aabaa ", neededTime = \[1,2,3,4,1\] **Output:** 2 **Explanation:** Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove. There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2. **Constraints:** * `n == colors.length == neededTime.length` * `1 <= n <= 105` * `1 <= neededTime[i] <= 104` * `colors` contains only lowercase English letters.
null
Database
Medium
null
795
hi guys today I'm going to talk about mythical questions and 9fem the number of summaries with the bombing maximum the in question scene that we now have every and our houses day lower bound and others for opponent the aim is to find the men of the suburbs that meet the requirement is that the maximum of given suddenly shouldn't even bigger than the other gong she must under the lower bound ow so let's take a look at the example here they now have a way to 140 and three people in summary one is two and issues because his maximum mystery and surely not less than two and receive less than three and another server is to one his maximum is two so as a leader several just like former submarine and the third one is three is maximum nation three and not bigger than the town feel so it is a label now let's take a look another severally as a long form three is suppose maximum is 4 which is bigger than a pound three so there are its own law is given Rico let's take a look at a simple example here in this example all of the elements in their way are the tinder opponent they are both the are between two and six and there are four variables all means the college index of therapy and Jamie's star point of memory and count because two almonds J +1 mission is which is the almonds J +1 mission is which is the almonds J +1 mission is which is the cockroach remember the last level for legal summary the rest is all reasoned firstly did manage to come see now researching I Angelica's two and so the count is I'm and cherry plus 1 which is 1 and the count means that now we have Justin one legal summary in this lovely and Jackson we have three well that's 1 and J also stay at e 0 and calculate the count because 3 which means the weight and the light over had to several issues in legal you can see you just the condition of the count element and the last normal element 2 3 because 2 to attend new element 3 and 3 it was just like a single element which is totally new and now and we had the new element floor on also increase the index account because I meant rate plus 1 because 3 we have 3 new summary 12 3 4 &amp; 4 max is 5 3 4 &amp; 4 max is 5 3 4 &amp; 4 max is 5 the count is for the whole four years over the last one 6 late copy the country 5 and which means that we have five new totally new summer wave which were made strong informant say the result here we have 15 liberal suddenly just like ours not a profession that she is one hostile past plus four so what's the bond to it are relatively sophisticated example here the first element is true and see midst a recording so promised to max element this theory also makes the requirement so the update to count to two maximum juice is illegal actually is a condition to the element is less than the lower bond so I will shoot in nothing to the count you death level the real seven rate is filth retail and Brazil as you can see the just a combination of the college element and the previous Lippo separately and in this case the single element summary zero is illegal next element for this label is condition one and update account to four there are four liberal summary in this level notice this Sullivan till one is a combination of a legal element and illegal summary although single atom in several 0 receiving legal but as long as it combines with the label almond it becomes legal sovereignty next Silent One is also an illegal it's lower than the lower bound so there should not be to account and is just a combination of the death of conditions with one and the previous level severally annex element 3 is legal so we will update or account 2:06 on the same idea applies to your 2:06 on the same idea applies to your 2:06 on the same idea applies to your days level one thing involved one is an illegal but as I live in period three it says all have regarded as legal sorry max element five is also legal serve it just opt into account I minus J plus 1 which is 7 and added to the result max element is bigger than that about so we're said that is conditioned through government is bigger than the upper bound in this case we regarded this element as our job in that the salary before this argument can't connected to the element after this element because the subway see the combination of continuous element so as I they have element 8 here solution is a little summary and we just simply move the star point to the next element so long it's to 8 on sense trans to 0 this was in the county level we have no legal summary the maximum element is 5 the count is in immense of J plus 1 is 1 and added to the result notice that there are 2 570 all because the question allows duplicates so although they have same value the actually different summary as they have different start index and then the index Marlys Nick will occur to the government cold do adhesives simple on Trinity there are three logical or clear conditions the forces are legal element in this case we'll just simply update the count element and J plus 1 and then and account the result the second case is the element is smaller than the lower bond in this case we didn't object or hung the chose of the country or result the third case in element is bigger than upper bond in this case we said the star point change to on pass one and then after the count to 0 so does it I know this question still a bit counterintuitive so please feel free to pause the video or will watch it and comment down below our response as soon as possible
Number of Subarrays with Bounded Maximum
k-th-symbol-in-grammar
Given an integer array `nums` and two integers `left` and `right`, return _the number of contiguous non-empty **subarrays** such that the value of the maximum array element in that subarray is in the range_ `[left, right]`. The test cases are generated so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[2,1,4,3\], left = 2, right = 3 **Output:** 3 **Explanation:** There are three subarrays that meet the requirements: \[2\], \[2, 1\], \[3\]. **Example 2:** **Input:** nums = \[2,9,2,5,6\], left = 2, right = 8 **Output:** 7 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `0 <= left <= right <= 109`
Try to represent the current (N, K) in terms of some (N-1, prevK). What is prevK ?
Math,Bit Manipulation,Recursion
Medium
null
6
That a hello hi guys hope you are doing fine welcome back to the video today's question is a conversation question status due paper is higher in his written in superintendent pattern will be one number of crops like this a ko an indian red line by line is a prayer ko Date with the latest in this convention giver number of research that 24 hours computer function convert which takes to argument idea district is number of runes in yii2 written during which aims around play list consider the examples given in the question waiting ssc paper is hearing and Number of Russia District in Punjab School Bluetooth Arguments District in English Number of Russia is a minute to calculate the length of the state and stored in available length eliminator also declared unavailable position that value is equal to the number of cost - value is equal to the number of cost - value is equal to the number of cost - way latest to bank is Used Earth Index to subscribe our The Minister Also Create Another Exams Number Of Russia Amazing Spider-Man Salary Hai Number Of Russia Amazing Spider-Man Salary Hai Number Of Russia Amazing Spider-Man Salary Hai Bluetooth Su Last Algorithm Vijendrasingh District Administration Pick Up In The Valley Of Position After Operation Delhi Police That Previous A Withdrawal Code Demolished Famous Father With Example In That Election Let's With Example Where's Point To The First Index Director Professor And Assistant Director Speech That Diwali Of Pollution Street Show Winter Weather's Accident Slam Just Bus Not Present For The In Computer People Of Position Responsibility Position Is Note 0 That Diwali Opposition Is equal to number of - 105 in this condition is - 105 in this condition is - 105 in this condition is that Vijendra for look promising 202 Number of us is switched off by changing its length Video not and copy character from to The Amazing Column 1 Column 2 Kal su next poppy seeds pair to The Amazing first Problem and Estimate Final Decrement Volume Opposition Election Medicines Position Is One That Supermax Titration Separate One Salat Only 10 Not Written Complaint About Your Position Only One Position 700 Equal Number of Votes - 102 Condition Side and Loot Number of Votes - 102 Condition Side and Loot Number of Votes - 102 Condition Side and Loot Number of Clans Open That A Difficult To Position Daily Officer Particular Character From This Into The Beatles Beans Sub Dollar Sign In The World To Close Loop Sister Scored Is That During Installation With Every Problem Due Position Smart Equal Number Of Russia - Position Smart Equal Number Of Russia - Position Smart Equal Number Of Russia - One Should Be Inserted A Character Of Water Form And Divine Position In these conditions, initially the volume position is sporting and came to the phone that these started to learn a and hear wi-fi acid position Udaipur veer and hear wi-fi acid position Udaipur veer and hear wi-fi acid position Udaipur veer that according to this the dollar and decrement volume positions name of the medicines position this against Sumit Detail Confrontation Between Check Weather's Exclusives Did Not Think Press Vikram and position on Sri Navadurga Lutyens at any house 04 2012 opposition to Number of Thrones - 121 opposition to Number of Thrones - 121 opposition to Number of Thrones - 121 Value Oppositions 2% Father and Mother Position Value Oppositions 2% Father and Mother Position Value Oppositions 2% Father and Mother Position Equal Number of - Awal Equal Number of - Awal Equal Number of - Awal I am only the following candidates Through expressed side and look project 13202 number for oo for bachchan matar ke dance and excellence in more landslide in two third option a ki and decrement the volume opposition on 80's station ki agni chakra wali pakka weather its length and width wali and listening position Opposition Leaders Not Numbers - One Who Can Be In Touch Leaders Not Numbers - One Who Can Be In Touch Leaders Not Numbers - One Who Can Be In Touch With Us Apne Power If It's Well In Opposition Equal Sides Difficult To Enter The Characters From Center Director Sudhir And The First President Of Dollar In The Position Of A Simple Institution Pimp Person Dust Accident Phone Number Should and position changed it is equal to zero and subsequent 20 can update opposition to come again on tiwari and position with number of votes - 121 of votes - 121 of votes - 121 the sims the condition h2 against tarf and loop for the fifth column firing who is the value of care David Silk Chiffon Coping The Character Sketch inder123in That In Agreement Daalunga Position Hai Name Diwali Opposition Of This Dynasty That On Fire From Unexpected Reaction And Chakra Darbari Pakki Accident SIM Status Not Wick Divine Opposition Seduce One To This Condition Spain Web Desk Condition In This App with opposition is equal to aaye the main only that pictures will get dollar send the first to wicket alphabet in dollars on twitter be r next generation that this film diwali for kids road accident shoulder chakradhar position is equal to 0037 image updater verification to 9 channel Subscribe Position Is Equal To Drops - Subscribe Position Is Equal To Drops - Subscribe Position Is Equal To Drops - 121 Towards And Look On A Promising 2002 Number Of Rose And Enter Garlic 10mg Tours1 Tension Up Traversing The Most In These Mins To Tawaif Zid That Is The Chief Guest Column In Two Variable Cost Column and call 100 a balance string that the element of The Amazing route into another string call and that Sufi Towers The final point of The Amazing Road Show Adding directors Pintu and Strength is when the character is not dollar sign up 178 cuts traversing The Amazing Biggest Affairs Painless 5508 Which Was Last Updated On Yesterday Morning Return District RPS And Result 10th Then Finally 12th Code A's Prohibition On 1 Minute Check Weather The Number Producer Is Equal To One Should Be Written Question On Ajay Ko Hua Hai A Victim Extension Part Store Google App Testing Invariant Leg End Declare Variables Pace and Position Some Balance Kisi Ka Toot Na Process - 110 Hua Hai Ki Ka Toot Na Process - 110 Hua Hai Ki End Definition Of K 20 125 Used Oil Traversing District Race Ki Agni Chakra Badal Insight Is One Digestive System Is Female Character It's us in the written test and objectives that a Ajay Ko MP3 the are take of science number of baroda balance a fidgit which alarm show create recent statements of his infidelities start with additional Google webmaster traversing district race is loot low on do the first features now K accident cellular length is to tips ourselves to are the last one and column in to variable cord call in the wake of loop my heart which can compare ring is opposition first vikram seth 2009 one text one and position is zero day update to number of Votes - Par Hai To update to number of Votes - Par Hai To update to number of Votes - Par Hai To Connect With Dar Diwali And Position Is Equal To Number Of Rose Minus One Latest Features After Now This Position Is Equal To Back Particular Way Character From This Institute Of The Reader Condition Is Successful Money Against Hard Look Promise 204 Number Officer Hua Ajay ko 10 best brother's 10 most active is the length of district ho 135 k is vidhi in the range of distance tips of birth character object into new airtel par HB inter to learn simple hai Ajay ko hua hai aap kaun ho play list wali Opposition Is Not Equal To Number Approves - 110th Insults And To Number Approves - 110th Insults And To Number Approves - 110th Insults And Statements Where Means Sadak Character And Pintu The Amazing Frustrated Position Matchbox With Wi-Fi On With Wi-Fi On With Wi-Fi On And This Ginger Pandu From Physical 204 Number And Roots And Weather Divya And Position Is Equal To My Jo alarm show karo ghar members accident length hai ki board is condition satisfied with him officer character from him to the real life story if de hua hai hua tha aisa pin set the tallest symbol as a prop up do sheela loot finally decrement wali Opposition Activists Traversal Loot That Stuart A Difficult Than You Are Agree With Update Balance Election But Travels British Rule Install Characters In To-Do British Rule Install Characters In To-Do British Rule Install Characters In To-Do List In Which Is The Richest Country Is A Loot Low MP3 Convenience Center Bluetooth Number Of That Before Acting On Road A Person Will Tree Another Look To Access The Columns Ajay Ko Do The Spinal Also Art Director To Parivartan String On Ajay Ko Hua Hai A Panel Of Buttons Research Institute Is So Vital For Educational Course Uttar Pradesh And Condition Years On A Soldier Getting From another reason for getting from answer is that difficult to enter this condition in the form of bashir wimbledon mixed not edit tourist trick suicide condition 12th result character and ipl spot-fixing $2 character this ipl spot-fixing $2 character this ipl spot-fixing $2 character this condition has studied in chief director tourism industry sunavai fikar andh shraddha kapoor 234 typing and accepted the a slogan famous father in all data record for bank account this time obscene suicide point this video call to the like button subscribe To My YouTube Channel for More Coming Videos and Nut Solution Thank You To
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
22
looking at lead code number 22. it's a question called generate parentheses i really like this question i think it's a great question as you start getting deeper and deeper into it really clears up a lot of confusion around backtracking recursion it touches on a lot of concepts so i think it's a good one to be very familiar with and i feel it's pretty frequently asked too yeah you can see a lot of companies like to ask this question too i can see why it's a good one that tests a lot of concepts in one go okay so here we're given an uh n pair of parentheses and we want to write a function generate all combinations of well-formed all combinations of well-formed all combinations of well-formed parentheses so here n equals three and we can see that well-formed parentheses so that well-formed parentheses so that well-formed parentheses so the length of our output our sub-result the length of our output our sub-result the length of our output our sub-result is going to be n times two it's gonna be six and so we can see that this is a valid parentheses this is a valid parenthesis so on and so forth n is one so if we multiply that by two the length is going to be two and the only valid parentheses we can have of a length of two is just one parentheses okay so let's kind of take a look at how we can approach this now if you haven't seen the videos uh in my in the other the rest of the playlist i highly recommend checking those out i'm going to be using a backtracking template to solve this we're going to look at an inefficient way of doing this and then we'll look at how we can add a few things to our template to make this very efficient in particular backtracking so the idea here is that we have n equals three and we want to get all the combinations of parentheses when n is uh the length is sixth okay so we can have two options here we can have we can add an open to our slate or we can add a closed to our slate okay here i'm going to just use n is two just for the sake of simplicity because if it goes above 2 this tree is going to get huge and so i'll just use uh 2 as an example so at each level when we go into our recursive case we're going to have two options we can either add an uh an open parenthesis or we can add a closed parentheses okay and as we go down we can add an open parenthesis or a closed parenthesis to our slate open and this will be closed and so on and so forth now i went ahead and drew out the whole tree over here just to kind of give you know just to kind of give you an idea of what this is going to look like when it hits the base case we want to have a base case where the length of our sub result whatever's in our slate is um is equal to n times two right so n times two is four our length equals four that means we hit our base case and we wanna check at this leaf level do we have a valid parenthesis and what we could do an inefficient way is just create a valid parentheses helper function and check is this valid and then if it is we can push that into a global result okay so that's one way we could do this the only problem with doing it that way is that we're going to have to go and make out this entire tree now the question is can we backtrack at some point in this tree can we say okay we have something in our slate that lets us know that there's no point in going down the recursive tree there's no point in building any more candidates because we know that nothing is going to be valid after this point okay so if we look here we can see that this right here starts with a closed parenthesis and if it starts with a closed parenthesis there's no point in going down the rest of this tree here because there's nothing here that's going to be valid okay let's look at what's valid here our valid answers are going to be uh let's see here this is valid and i believe that's it right so we can see here that here there's no point in going down the rest of this tree here because nothing is going to be valid if we have a closed parenthesis likewise if at any point we have more open parentheses than closed then nothing can be valid right if we have three open parentheses and our limit is four there's no way there's not enough close parentheses that's going to match it so we know that we can backtrack right there's no need to go down this tree because nothing is going to be valid okay so what we can do is we can add a backtracking constraint we can keep track of how many open and close parentheses we have as we're going down the call stack and at any point if we have more open parentheses than n okay which is half the number of the length at our base case then we can backtrack so we can say if we'll create a variable two variables we'll say open count is gonna equal zero and close count is going to equal zero okay and so here we're adding one to close count and because it's going to be one and that's higher than open count we can just backtrack right there okay so we can just say if uh close count is greater than open count then we want to return okay so that'll be our first backtracking case now the other case is that if we have more open than n right that means that there's going to be you know if n is four and there's three open parentheses then we know that there's no point in going down and making more uh candidates because none of them will be valid right so we can say if open count is greater than n we can return okay and that's the idea if we add those two in there then we don't have to go down and make you know like go down the inter uh the whole tree now what is our time complex space complexity uh worst case with this right well if we're not pruning then we're going to have to do 2 to the n times 2 right because n is going to be four if we multiply it by two so then our base case is four and so we're going to have to do two to the n times two and then we're gonna have to multiply that by n because we're gonna have to scan this at the leaf level and push it into our global result now if we do this backtracking what is our time complexity well it gets really complicated at this point worst case i feel that it's still o to the 2 to the n times 2 times n but you can see that it adds a lot of efficiency we're going to solve it both ways in the code just to kind of compare and contrast and you can see how much more efficient it is using the backtracking constraints that we added to it okay what about space uh worst case you know it's the same thing it's 2 to the n times n and why is that because we're going to have at any point we're going to have our global result and if we have to add all of these results in there okay that's going to be our 2 to the n and when we get to the bottom here we're going to have space on the call stack which is going to be n okay so we're going to have our call stack space which will be n and then our global result which will be 2 to the n so it'll be 2 to the n times n okay so let's go ahead and jump in the code let's try it both ways and we can use the leap code performance metric to kind of show what are the different time and space complexities that we're getting using an efficient way with backtracking or not using backtracking okay so first what i'm going to do is i'm going to use this template and if you're not you're if you if this is the first video you're seeing of this playlist highly recommend checking out the other videos because i'm using a template i'm not going to go over too much of i'm just going to go ahead and implement it but i do go over this template in great detail in the other videos so highly recommend checking those out so we have a global result okay and i'll call this const result we'll set this to an array and then we're going to have our depth first search recursive helper okay so we'll do cons that first search we'll set i we're going to have n we'll have a slate okay and so now what do we want to check if i is equal to n times 2 that means we're at the base case our leaf level then what do we want to check is whatever is in our slate a valid parenthesis so we can create a helper function so i'll just say if is valid and we'll go just do a slate dot join okay and if it is then we want to push that into our global results so we can just do a result.push just do a result.push just do a result.push slate.join and then we can return outside of that if statement okay so all we're doing here is we're saying when we get to the leaf level here is it a valid parentheses is this a valid parenthesis if it is let's go ahead and push it into the global result if it's not then we just go ahead and return out of there we backtrack okay so now we're going to have our depth first search recursion recursive call and what do we want to add an open so we can say add open paren and add close paren okay so we're going to add an open parenthesis to the slate and a closed parenthesis to the slate so we can say slate dot push we will add an open okay we'll call depth first search we'll increment i we'll have n and we'll pass in our slate and then we'll push we'll pop this off the slate all right and then we're just doing the same thing for our closed but we are just changing this to a closed parenthesis okay and so again all we're doing here is we're coming here we're adding to the slate and then when it comes back we're popping it off and then we're adding it to that so we're just using one slate array rather than concatenating and creating a bunch of extra space okay and so now what we're going to do here is we'll call depth first search uh we'll initialize it with i we'll pass in n a slate will be an empty array and then we'll return our result okay so and then let's just go ahead and create our valid paren so we can create is valid and this will just take in a string and then uh i'm not going to go over valid parentheses i'm just going to write it out but i do have a video where i go into depth on using or how to validate a parenthesis we want to use a stack so we can just say const stack set it to an empty stack and then we can um set i so let i equal 0 left len equals dot length okay and now we just want to say uh while i is less than uh len and then we want to take our character so we can say let her parent equals string at i push this onto the stack.push at i push this onto the stack.push at i push this onto the stack.push and we want to push our current paren okay and now what we want to do is we want to pull off the two elements on the stack and check if it's a parentheses and if it is we pop those two off the stack again i'm not going to go too much into depth on how to do this i do have another video on valid parentheses uh that i would check out if you're confused on this but what we're going to do here is let's see here we're going to have open so let open is going to equal stack at stack.length -2 stack.length -2 stack.length -2 okay let closed equals stack at stack.length minus one okay and then we just want to check if open plus closed equals a parenthesis then we want to pop those two off the stacks we just want to call stack.pop want to call stack.pop want to call stack.pop and stack.pop and then lastly we want to and stack.pop and then lastly we want to and stack.pop and then lastly we want to just if there's nothing left in the stack that means we have a valid parentheses so we just want to return stack dot length equals zero okay i'll zoom out so you can see all of this code in one go let me just zoom out one more so that way it's clear okay and let's go ahead and run this and see what type of performance we get uh let's see we have uh we have oh we have to increment i sorry there we go okay and so we can see here that this works but it's terrible performance right we're only beating five percent of uh parent of the submissions on time and five percent on space right so it works but it's not very efficient okay so let's look at how can we make this more efficient by adding backtracking okay so like i said here we know that if we keep track of the open count in the close count and at any point our close count is greater than our open count we can return and also if at any point our open count is greater than n we can return right and so we don't even need to use this is valid helper all we need to do is just pass in an open count and pass in a closed count all right and now all we have to do is if i if it actually gets to the bottom we know it's valid so if it gets to the bottom we just add this to our results we just say result dot push slate dot join and then we return out of here okay so this is going to be our base case all right and now we're going to have our back tracking case all right and what do we want to check if uh open count is greater than n we want to return and if close count is greater than open count we want to return okay if we just add those two constraints okay if closed count is greater than open count okay or if close count open count is greater than n then we backtrack right and here we just want to say if we're adding open count we're going to say oh count plus one closed count and here we want to add o count and close count plus one right and then we just initialize here with zero and zero right so those small changes we don't need to use that helper and let's take a look at how this goes yeah you can see we get like almost 10 times better performance just by using this backtracking case right here and keeping track of the count now this is hard to understand if this is your first time seeing this on how you pass these variables down and how this all works and that's why i highly recommend drawing out the tree okay just do it with n equals two get a pen and paper and draw it out and once you start once you draw it out you start realizing oh you can backtrack like when you draw the tree you can really see is there something going on in our tree where at some certain point in our slate we know nothing else is going to be valid after that point so we don't need to continue on and we can backtrack right from there we don't need to go all the way down to the leaf level we can just backtrack at this level right there and when you draw up the tree it's very clear to see that when you're looking at the code it doesn't it's not intuitive it's not just going to pop out and make sense and that's why i think that takes a little time to get your head around recursion combinat combinatorials and backtracking this takes a little bit of time but once you kind of once you get this it starts making perfect sense and i think the way you want to approach it is to draw out the tree use a small input where you can draw out the tree and then start figuring out like is there a way to backtrack here okay i really love this problem i think it's a great problem let's just submit it one more time so you can get even better performance but i think it's a great case of looking at okay if we're yeah so here we got 84 on time and 93 on space i think it's a great problem that really highlights the usefulness of using backtracking and if we add backtracking to these types of problems how we can just increase the efficiency significantly okay so that is lead code number 22 generate parentheses i hope you enjoyed it and i will see everyone on the next one
Generate Parentheses
generate-parentheses
Given `n` pairs of parentheses, write a function to _generate all combinations of well-formed parentheses_. **Example 1:** **Input:** n = 3 **Output:** \["((()))","(()())","(())()","()(())","()()()"\] **Example 2:** **Input:** n = 1 **Output:** \["()"\] **Constraints:** * `1 <= n <= 8`
null
String,Dynamic Programming,Backtracking
Medium
17,20,2221
237
welcome ladies and gentlemen boys and girls today we are going to solve not a coolest question because if you see the like and dislike the show i think this is one of the worst question on the lead code i don't know like i've never seen two this one dislikes till now in any questions okay so like i've seen the disclaimer note this amount so we will do this and i add it to the list as well so if you have not like this just check in the description it's only for you guys all right let me just open my whiteboard and see what we can do okay all right here we go all right so another question is being let's just look at the first question that a function to delete a node in a single linked list you will not given the access to the head of the list instead of you will give you given x to the node to be directly okay so what this question is like they did not give the access to it to its head so we don't know like where the head is or this node we just only have given the direct access to the given node so let's say we have to remove this node so they just give the direct access to this one okay so it is a guarantee that a node to be deleted is not a tail node okay so they give it one more condition like we have two conditions so we don't know the head and the tail one cannot and i will not be deleted in any test case okay so it may like the deleted one should be present between the head and ten okay that's only the thing we know all right so i don't know like why this question put too many hairs but uh i think for the interview purpose might be let's see we will go through the discussion section of this question but before that let's solve this question so that's the question similarly alright ladies and gentlemen so what we're going to do so we just have node over here so what i will do is it's very simple so let's say i have to let's say my note.well let's say my note.well let's say my note.well if i'm on that value then what i will do i will go to his next one i will go to the next one so whatever i'll say i said note dot next so well all right okay now one last step yes believe me the another last step so now what you have to do i have to point like you know i am on i have to remove this node so what will happen like this the node address this one is changed so i have to change this address so that it can start pointing on this one so for that one what i will do i will simply say node dot next equals to node door next yes ladies and gentlemen this is all what we have to do in this question so let me just run this one as well and we will see any compilation error i don't know like any compilation error in this one and here we go so is some meeting let me submit this one so i can tell you spam complexity and space complexity so in this one you see going hundred percent is too much faster so like in this test i go a little bit more faster using the memory use so it depends on uh code server okay the server on the net code the load server on like load on the server only okay but whatever so let's talk about is time compressibility time complexities big o one and space complexities we go one as well like we are not using any extra spaces we just have to simply remove this though no extra time is delivering that we are just not going to the uh number of mode or as it does the complexities and let me show it to you the discussion tab over here let's see most people are writing over here if you go to the most words so you know in the starting time i just check might be this is the kind of something question like might be this is the answer this is a good answer i just click on this one i say while he could i said this to you and then i see this guy literally written this thing this question is stupid should we do it immediately and he was 757 likes impressive bro okay so there are people are saying like i was the kind of doing correctness and all that but this guy just clearly write the correct thing he's like instead of criticizing like they are trolling this question seriously they're calling this person code instead of criticizing uh this the guy name let analyze why this problem is not a good interview question okay so that like let us know understand what he's saying so he's saying the whole point of asking a candidate like this problem is to test if the candidate thinks about edgy cases including okay so it's saying like uh you know the whole point of you ask the lead linked list question in the interview like the interview wants to know what kind of test case you think like what the test will be do you think like it in which your core will definitely gonna fail or like you your code will not run this testing like that so now he's saying like deferencing null pointer usually targeting tail pointer when given head is none uh they don't give him head and when there are duplications in the list okay the question is specifically mention all the workplace questions so i mean like this guy literally just i find he's like that's it good thing all of them they are just folding this question so okay let's go back and they like they just told us talking about this thing already okay so let me show you the uh perfect one so like it's going like 93 in 97 for the memory usage you see and was the is 100 for that uh time run time is sold we do not have enough acceptance from chips we're throwing hundreds one time so believe it okay so all right ladies and gentlemen that's all for this question is so likely we just did it thank you very much for watching this video i don't think you like you will have any doubt in this one but if you still have this do written in the comment section and thank you ladies and gentlemen for watching this video i will see you in the next one till then take care bye and i love you guys take care bye
Delete Node in a Linked List
delete-node-in-a-linked-list
There is a singly-linked list `head` and we want to delete a node `node` in it. You are given the node to be deleted `node`. You will **not be given access** to the first node of `head`. All the values of the linked list are **unique**, and it is guaranteed that the given node `node` is not the last node in the linked list. Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: * The value of the given node should not exist in the linked list. * The number of nodes in the linked list should decrease by one. * All the values before `node` should be in the same order. * All the values after `node` should be in the same order. **Custom testing:** * For the input, you should provide the entire linked list `head` and the node to be given `node`. `node` should not be the last node of the list and should be an actual node in the list. * We will build the linked list and pass the node to your function. * The output will be the entire list after calling your function. **Example 1:** **Input:** head = \[4,5,1,9\], node = 5 **Output:** \[4,1,9\] **Explanation:** You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. **Example 2:** **Input:** head = \[4,5,1,9\], node = 1 **Output:** \[4,5,9\] **Explanation:** You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. **Constraints:** * The number of the nodes in the given list is in the range `[2, 1000]`. * `-1000 <= Node.val <= 1000` * The value of each node in the list is **unique**. * The `node` to be deleted is **in the list** and is **not a tail** node.
null
Linked List
Easy
203
881
today we will solve a problem called boats to save people so here we have a number of people each person has different weights and we have a number of boards so we have to safely uh move all the people from one side of the river to other so let's take an example so there are some conditions so one condition is that maximum two people are allowed in a boat so this is one condition and the boat has a limit you cannot put heavier people than the limit in the boat and it's also given that all the boats will have some limit and let's take a boat which has a limit l then none of the persons will have weight more than l so the heaviest person will be less than or equal to the boat limit so all the boards have a limit so you got the idea max two people if let's say a boat has a limit of five all the boats have a limit of five and there is a person with a weight of five then you cannot uh put two people here although you can there is a space for two people but the weight limit is exhausted by this single person itself or let's say there are people of weights four and two and the limit is 5 still if you put these 2 we will get a total of 6 which will be more than the limit so these are the conditions and of course in this problem we want to find the minimum number of modes required maximum number would be put one person in a single mode all the people in separate boards so let's see how we can solve this problem so first we will look at the heaviest person or the lightest person anyone is fine so let's say the heaviest person is 4 or in general case weight of heaviest person is h and the lightest person's weight is l so we will see what is the capacity what is the total weight when we put heavy and low smallest and heaviest both together is it greater than equal to is it greater than limit equal to is allowed then the heaviest one will go alone because if you would want to pair as many people as you can or in this case maximum 2 is allowed so you would like that or whenever you are sending a person you pair somebody someone with him so that you minimize the number of boards only 2 is allowed so whatever is the heaviest person one choice is that you send him alone second choice is that you pair him with some other person or if you take the lightest person if you can pair the lightest person with heavier one heaviest one then you can pair it with any one so better pair with the heaviest one or if you look at the heaviest person if you can pair it with the lightest person send him with lightest person and if this is more than limit then definitely if the lightest person cannot pair with the heaviest person then it will not pair with any other person because all the other weights are more than or equal to the lightest person so if this is true that is this lim is more than the limit then heaviest person has to go alone in place of l any weight you replace it will be more than that so in this case if h plus l is more than limit is capital l then this will go alone if this is less than equal to limit then heaviest and lightest goes together now you see that this is correct we are not violating any constraint we are sending two people max two people are allowed it's within the limit and we are following that so how why will this work if we go on so now in this case we are we have two less people so earlier we had n here we have n minus one because we sent the heavier one alone and we are left with so one boat is exhausted and one person is reduced so number of boats is one here so whatever was the number of boats it increases by 1 and number of percent decreases by 1. in other case we spared heavier and lightest person heaviest and lightest so again the number of boats increases by 1 and the number of people decreases by 2. so we have a smaller problem if we sort them in some order increasing or decreasing let's say lightest is here heaviest here then we have a smaller problem in both cases in one case from here to here and this is the case of alone this is together so why will this work why will it give a minimum number of bolts so uh there are two cases case one is that lightest person goes with heaviest person that is h plus l is less than equal to limit so if this is the case then the lighter person can be paired with anyone because the lighter lightest person can be paired with heaviest person then it can be paired with any other person because the heaviest is the heaviest so if you replace it with any smaller value than l then h then still it will be smaller than equal to l so it's correct to pair it with heavier one because we are sending a heavier person out so it's intuitively correct so the lighter person can be paired with any person so we pick the heaviest among that so we are not losing on anything we are sending them together and max two are allowed so it's not that you can pair more people here so only two are allowed the other case is that so in this case it has to work the other case is that a lighter one cannot be paired with h that is h plus l is more than l so the heaviest person cannot be paired with any other person if the heaviest person cannot be paired with lighter one lightest one it cannot be paired with any other person so in this case heaviest one has to go along there is no other choice we pick the lightest one and even that cannot fit in this so in this case we will send along in this case we will send two so we cannot do better than this so this is the optimal solution so what we are doing in this case first we are sorting it this list of weights so this denotes the weight of first person weight of second person weight of third person fourth and fifth this array and this is the limit so first sort them so in this case it will be 1 2 4 and run our algorithm so initially number of boards will be zero and each time we increment the boat count by one so in either case number of boats increases by one and if h plus l that is first and last one index will be here one index will be in the end beginning and end if we add these two and this condition is there that h plus l or if this is i and this is j then people i if people i plus people j is more than limit then what we do we send the heaviest one alone there is no other choice so j decrements so let's say i was in the beginning of the sorted list and j was in the end this is the lightest this is the heaviest and boat count increases by one irrespective of this so let's keep it outside this and else uh i plus j minus because we can send them together and still board count increases by one and we run this entire loop till i is less than equal to j so let's write the code for this so first i will write in c plus less than java and python so let's see the time complexity what is the time complexity here so we are sorting this list so if the list has n number n people then sorting will take n log n time and then we are iterating this list from once i is moving in this direction j is moving in this direction we stop when they cross each other so another n so n log n plus n that is n log n and space we are using uh if we are changing this list itself we are sorting it itself without creating a new list then we are not using any other variables other than some pointers so space 0 of 1 now let's complete our code so first step is sorting so in sword we pass the two iterators from where to where sort so we are sorting the entire list so people dot begin and people dot end now this is sorted in ascending order and any order will work for us we will just need to tune our algorithm i 0 and j is the last index that is size -1 boards initially it's zero if it's more than limit send the heaviest one alone no choice so j decreases else i plus and j minus so j minus is common so better write the different code here and there is no else required because j minus is there in both cases so we have put it outside or you can write if else if it make makes it more clear if it's more than limit j minus if it's else i plus j minus so you see j minus is common and then boats also is common this solution is accepted so we did not run through our example i hope it was clear but let's run through it so in this case we have sorted it so four plus one is five limit is five so 4 and 1 go together one board then we have a smaller array this one so i plus i is now here j minus so j now comes here i moves here smallest plus lightest is 3 which is less than limit so 2 and 1 goes together and i comes here j comes here both here now 2 is less than limit so 2 goes along so 3 boards are required so in this case the answer should be 3. we don't have to write the exact solution just the count so our c plus bus solution is accepted next we will write in java and python which will be very simple very similar to this one java solution is also accepted finally we will do it in python you python solution is also accepted
Boats to Save People
loud-and-rich
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum number of boats to carry every given person_. **Example 1:** **Input:** people = \[1,2\], limit = 3 **Output:** 1 **Explanation:** 1 boat (1, 2) **Example 2:** **Input:** people = \[3,2,2,1\], limit = 3 **Output:** 3 **Explanation:** 3 boats (1, 2), (2) and (3) **Example 3:** **Input:** people = \[3,5,3,4\], limit = 5 **Output:** 4 **Explanation:** 4 boats (3), (3), (4), (5) **Constraints:** * `1 <= people.length <= 5 * 104` * `1 <= people[i] <= limit <= 3 * 104`
null
Array,Depth-First Search,Graph,Topological Sort
Medium
null
987
Everybody Welcome to My Channel Today Have Any Problems Vertical Reversal of Boy's Tree to Give It Return More That Point Note Position Access Oil Left and Right Channels Pet Position - 151 - Running Vertical Line Pet Position - 151 - Running Vertical Line Pet Position - 151 - Running Vertical Line From - Infinitive Vertical From - Infinitive Vertical From - Infinitive Vertical Line Shyamlal Report Divya of the Order From Top to bottom decreasing why did not have the same position in the valley of not reported subscribe button list of sports in to-do list of this is the name sports in to-do list of this is the name sports in to-do list of this is the name in the left right to understand over 100 effigy start from road to this fruit mode of trees Will Shine More Hair 100MB Left Activities - 151 - - - 121 Ko - Activities - 151 - - - 121 Ko - Activities - 151 - - - 121 Ko - 93005 20300 - - - - - - 21st To Call - 93005 20300 - - - - - - 21st To Call - 93005 20300 - - - - - - 21st To Call - 2 Ki Swadeshi Coordinator Behind All Notes Inventory 9 Vidron In Three Different Values ​​Affairs - 101 And Toubro Pressing Values ​​Affairs - 101 And Toubro Pressing Values ​​Affairs - 101 And Toubro Pressing Lines In Vertical Lines With His Mother Carried You And Third One Is This And Fourth 1981 Over India First Vertical Lines Will Not Have Been Written Like This Point To Subscribe From Top To Bottom Subscribe 602 108 From Decreasing Day By Coordinator For The Decreasing Author Top 30 Feet This - 200 Will Print Dollars Like Three 500 That You Turd The 90 Will Come And Live Class Notes Satvik Sudhir And This Is The Answer Which We Are A Creative Fennel How Will Solve This Problem Solve Crops Forget About The Coordinate And Dip Value Less Print In Vertical Lines Subscribe Our In This Another Example In This Article They Will Give The Center Of The 90 - 151 - 1000 To Subscribe Center Of The 90 - 151 - 1000 To Subscribe Center Of The 90 - 151 - 1000 To Subscribe Our Divine Sebi And He To Kids For Kids Values ​​Will Use This Cream And Kids Values ​​Will Use This Cream And Kids Values ​​Will Use This Cream And Industry In Thursday Convene With Winter List LIST PLAY LIST OF ALL THE STATES WILL NOT GIVE VOICE TO SUBSCRIBE TO THIS WILL HAVE TO ME NAVEL GOLE NISL SPEED ABSOLUTELY LOW OK SOFTWARE VERSE - - - 121 SUBSCRIBE TO CHANNEL LIKE AND SUBSCRIBE MY CHANNEL DON'T FORGET TO SUBSCRIBE THIS CHANNEL Do and Will do the first day first preorder traversal of tree and keep track of all norms which were beaten with us building list points that are the first features Margi list of points using haddi sample data structures and mother coordinator end value top sorry less western first level Computer Labs for a dot side the elected college list itself will pass list and science paper stump rates will power company from it Amazing spider-man does subscribe to 200 will fight comeback only .in It 200 will fight comeback only .in It 200 will fight comeback only .in It is equal to the speech to daughters continent In the world comparison in the middle schools pe wid oo ki aap even new delhi bureau - pintu david vaccine new delhi bureau - pintu david vaccine new delhi bureau - pintu david vaccine cold not notice otherwise p1108 in this will return to mp2 white - pawan biks and it vermillion and mp2 white - pawan biks and it vermillion and mp2 white - pawan biks and it vermillion and decreasing coordinators from 11021 - decreasing coordinators from 11021 - decreasing coordinators from 11021 - we in this app to Print From Top To Bottom To This Will Be Given More This Explanation Advised Not To Avoid Simply Turn On Daughter - Subscribe Custom Simply Turn On Daughter - Subscribe Custom Simply Turn On Daughter - Subscribe Custom Cars Were Being Used For Recruitment Jobs To Know This And Will Feel This Map By Using Chief All The Way Channel Radhe- Radhe Subscribe Custom Subscribe Now to Receive New Updates Flower Tree Will Return Otherwise Virval The Amazing spider-man Subscribe to the middle aged person Increase XY One and Five Degrees to Give One So This will create a list of all the notes in the midst Subscribe Newsletter In 115 Will Be A Map Of All The Coordinator Lucky And You Stop Interior In The Amazing You All The Best Speech For Age From Top To Bottom And Values ​​In This Is Top To Bottom And Values ​​In This Is Top To Bottom And Values ​​In This Is Gold Subscribe To Channel Must Subscribe To Members Also Accept What's The Time Complexity of this solution for the time complexity of dissolution is like you sirvi mohsin ki and also this press complex edition of birth story all notes in a sorry time complexity and space complexity very subscribe solution for the like button subscribe My Channel thanks for watching
Vertical Order Traversal of a Binary Tree
reveal-cards-in-increasing-order
Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree. For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`. The **vertical order traversal** of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return _the **vertical order traversal** of the binary tree_. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[9\],\[3,15\],\[20\],\[7\]\] **Explanation:** Column -1: Only node 9 is in this column. Column 0: Nodes 3 and 15 are in this column in that order from top to bottom. Column 1: Only node 20 is in this column. Column 2: Only node 7 is in this column. **Example 2:** **Input:** root = \[1,2,3,4,5,6,7\] **Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\] **Explanation:** Column -2: Only node 4 is in this column. Column -1: Only node 2 is in this column. Column 0: Nodes 1, 5, and 6 are in this column. 1 is at the top, so it comes first. 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6. Column 1: Only node 3 is in this column. Column 2: Only node 7 is in this column. **Example 3:** **Input:** root = \[1,2,3,4,6,5,7\] **Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\] **Explanation:** This case is the exact same as example 2, but with nodes 5 and 6 swapped. Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `0 <= Node.val <= 1000`
null
Array,Queue,Sorting,Simulation
Medium
null
146
so let me first read through the question then we will move on to the solution designing an implementary data structure for least recent use cache it should support the following operations get and put so lru is basically eviction policy like many other fifo and lifo vision policy like gives us the maximum capacity our cache can have okay so get input get gets the value of the key if the key exists in the cache otherwise written minus as the name suggests it's pretty simple to understand put key value try to insert the value of the key is not already present when the cache reaches its capacity it should invalidate the least recently used item before inserting a new item okay so if the key is already present we just need to update the value and if the key is not present we need to insert the key value pair into our question but there is a catch that we need to invalidate the least recently used item before inserting a new item so since the cache has a limited memory whenever the capacitor is full we need to remove the least recent use item from our cache so the limited memory of cache is what makes it its access time fast right so yeah also there's a cache that we need to implement both of these operations in order of one time complexity so now let us think of data structures we can use so one thing is clear that we will have to go for a map to maintain a key value mapping okay what kind of map that to an hashmap because require an order of one insertion and retrieval time right so cool but the catch is that we will also require a structure that maintains an order hash map doesn't maintain an order why do we need a structure that maintains an order because we will have to remove the least recently used item from our caching so how can we do that with an structure that maintains an order you can easily know the least recently used item and every time the capacity is full we need to delete that item as well so we require order of one deletion as well the structure which maintains an order and provides as an order of one deletion is basically a doubly linked list because we have the pointer to the previous node pointer to the next node we can just delete the node if we know the pointer to it so now we are clear with the data structure we're gonna use a hash map and we're gonna use a doubly english right so doubly link base will store the keys of our cache right and the map will store the key value mapping and in addition to the value it can also store the pointer to the node that stores that particular key the value is mapped to that will help us in deletion in order of one time like i said before if we know the pointer to the node we can just delete that node in order of one time complexity if it's a doubly linked list so i will be going to implementing c plus and in c plus the hash map is an ordered map and doubly linked list is simply list so let's go to the implementation part so let us start with the coding data structures which already discussed map and the pair of value and the iterator to the list and let's call it cache and then i will using a doubly linked list which is list in c plus and i will call it the diagram fine also we will have to declare the capacity and here we will be setting the capacity so this capacity equal to capacity okay so now let us start implementing the cat function so first we will find the iterator to the key in our map so if the iterator points to the end of the cache that means like it doesn't exist into our map then it will simply return minus one now what if the key is present in our map so before returning the corresponding value we must make sure that we are using that item right so if we are using that item then the item has become the recently used item so in this list in the lru list we want to remove that item from wherever it is and then push it to the front to make sure that we make it the recently used item because the least recently used item lie at the back of the list right so we need to make sure that we are making the necessary changes so that's why we will implement this use function uh later and i am passing the iterator here why because it will help us in deleting that particular node from the linked list and then we will push the corresponding new corresponding key in the front to tell that it is it has become the design yield used one cool now again it will return the corresponding value for the key and what is the corresponding value it is the first element in the pair so iterator second dot first cool now let us start implementing the put function so the key is already in our cache here then just we just need to update the corresponding value right so let us do that so i and that means the key already exist in our map then we need to return oh sorry we need to update the corresponding value so we are updating the value and what will the iterator of the list it will become the beginning of the doubling list why because we will be using that item here we will be using that iterator here so if we use that iterator then as i said in the use i will insert the key in the front right so this will be storing our keys right so i will be pushing the corresponding key in the front to make sure it's to signify that it's the recently used so the iterator will be the beginning iterator now what if the key is not present in our cache then we will have to insert the key value pair into our caching right but before inserting we will have to check if the capacitor is full because if the capacitor is full then we need to remove the least recently used item from our cache so we will check that so if we get that city equal to cache dot size then we will erase the least recently used item from our question where does the least recently used item like at the back of the language right at the end of the ling list so okay dot it is lru and also we will have to remove that node from the link list as well so sru dot now we have made sure that the capacity is not full so we can just simply insert the key into opening list and insert the key value pair along with iterator to the node of the linked list into our map so let me do that so allow you which is our name list i will be pushing the key into the to the front to signify that it is the most recently used and then i will again insert this key value pair sorry value comma lru dot begin which is the iterator of the new inserted key value pair again now what is left is implementing the use function so what use function will do is as earlier said by me it will remove the node pointed by the this iterator pointed by this iterator will remove that node in order of one time because it's a doubly linked list and then it will push the key in the starting into this link list to signify that it has been recently used so since it's uh doubling this both the operation are in order of one time so let me do that so as passed we have passed it off type so let me copy something from here and it since it's iterator let me define an iterator and we need to modify it all right so i'm passing the address here and so we will remove from our linked list the iterator so it's a iterator of type map right so why second or second because second is a pair and the second element in the pair is the iterator to the list we want to delete because we have used that item we want to delete wherever it is present in the doubly linguist and then it will push it again to the starting to signify it has been recently used so i will push it in the starting and what we will put i will push iterator first which is the key because our linguist is storing only the keys right and then what is left one thing is left what we need to assign the iterator we need to modify the lead iterator so assign it to the beginning of the list right till now it was assigning to some location in middle of the list somewhere but now it has come to starting that case come to starting so we want to modify the iterator to the list to beginning of the linked list right so i will modify it okay so i have misspelled something right here right i will change that so it return second dot second this thing we need to modify this thing to lru dot begin right pull now let me run it and see okay it looks good at somewhat uh there is some matter let me go through the good ones okay i forgot the return statement here let us submit it again yeah voila so let us discuss the time complexity of this program so as mentioned earlier both of these operations are order of one time and yes that is what is expected for you to solve in the interview because the next question if you implement it in order of and complexity would be can you do it better can you do it in order of one complexity but from starting if you go by this approach then you will save one time generally if this question is asked on a phone screen or on-site round or on-site round or on-site round you will get 45 minutes to implement it and if you start with the brute force approach you are likely not to complete the expected solution in order of point time complexity and if you haven't solved this question before it's really hard for you to think on spot so yeah and one more thing it's one of the frequently asked interview questions so you must practice it i will be putting the code link to the code in the description so do check it out there and like the video if you find it informative
LRU Cache
lru-cache
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`. * `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key. The functions `get` and `put` must each run in `O(1)` average time complexity. **Example 1:** **Input** \[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\] \[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\] **Output** \[null, null, null, 1, null, -1, null, -1, 3, 4\] **Explanation** LRUCache lRUCache = new LRUCache(2); lRUCache.put(1, 1); // cache is {1=1} lRUCache.put(2, 2); // cache is {1=1, 2=2} lRUCache.get(1); // return 1 lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} lRUCache.get(2); // returns -1 (not found) lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} lRUCache.get(1); // return -1 (not found) lRUCache.get(3); // return 3 lRUCache.get(4); // return 4 **Constraints:** * `1 <= capacity <= 3000` * `0 <= key <= 104` * `0 <= value <= 105` * At most `2 * 105` calls will be made to `get` and `put`.
null
Hash Table,Linked List,Design,Doubly-Linked List
Medium
460,588,604,1903
427
hello guys welcome to deep codes and in today's video we will discuss Network question 427 such as construct quieter so this question is a bit difficult to understand at First Sight but after watching this video I will make sure that you understand each bit each line of this question and also the solution so yeah without wasting much of our time let's begin with the question so here you would be given One n cross and Matrix that contains only zeros and ones only these two numbers zero and one and we need to represent these given Matrix or grid with the help of quadrant and we need to return the root of by tree representing the grid okay now uh here each node has some value and easily same there are two properties for the we will discuss this line afterwards say a quiet tree is a tree data structure where each internal node has four children and beside each node has two attributes so a node in a quiet tree is represented by two attributes one is value v as well and second is lift so Val is uh true if the node a represents in a grid of one a false if a node represent in a Grade of zero that means if a grade value is 0 then this value is also is false and if it is 1 then this value is true so this value is also a Boolean as you can see here the values what Boolean is as simple as that if it is a leaf node then his Leaf is true as false okay uh and yeah and we need to construct the quiet frame uh from two Dimension two dimensional grid we are given okay now here if the current grid has same value that means all the cells of the current grid are ones or zeros okay then you set is left to true that means if a current grid has same value then we make this current grid as leaf okay this line states that we make the current grid as a leaf node okay and set the value as a value of the grid okay so that so since the all the cells of the greatest same value that is either one or zero we set the this where according to one or zero that means either true or false and we make all the children to null and stop okay so this thing says that when the current rate has same value then we make this uh make that as a leaf node and we stop simple as it is and if a current grid has different value then set is left to false and set value to any that means either 0 or 1 to any value and divide the current rate into Force upgrade as shown in the photo so let's say this is your current rate initially this complete is a current rate now if this current grid whole grid has different values that a mixture of zeros and ones like sum 0 someone in such a case what you have to do you for this current grade make is live to false okay and set value to any either true or false any value and then divide this current grid into Force upgrades okay so this was the current rate and then you divide it into four separates this is top left top right bottom left and bottom right correct and recurs for each Children of the proper sub print then again for each subgrid recurs and find its and check are all the values of this top left same if not same then again divide it into one two three four correct so that's why we recurs for E children got it got this line okay any of this skip one line uh a head that notice that you can assign any value to the node true or false if Leaf is false so is leaf is false that means if a node is a not a leaf node if it is not Leaf node then we can assign any value to the uh to that node because we can assign anything to this valve if easily this false and both are acceptable either true or false so this line states that only okay now for the query format so it says that the output represents the serious format of a query using label order traversal where null signifies a path Terminator where no node exists below ah see these things are I will explain You by taking this example so for these like for this given grid 0 1 0 we need to represent in acquiring okay so as you can see that here we have a mixture of one and zero correct so this complete can't be one node so that's why if we make is lift as 0 let me take a pen so see this complete here this complete is a mixture of zeros and one so we can't make this as the leaf node correct so we made is leaf S 0 and we can take anything for well either zero or one anything and whenever we have a mixture then we divide it into 4 that is top left top right bottom left and bottom right this is top left this is the uh top right this is bottom left and this is bottom right correct now in this top left all these values is same is uh already it is only one cell so the values remain the same here so we make the value as its value of the grid and is leaf is one means this is now the leaf node similarly for the top right value is one so we make values one and we Mark knit as a lift same for bottom left and bottom right so this is the complete representation of a query for this given grid and now we need to return the output so how we will return the output in a label order this is label one then this is level two and from left to right and at each and for each node we have two properties that is easily and well so we return this way okay this is for the root node then is child one child two child three child four as you guys see these are the four Childs so this is how we need to return the output and the same thing is written over here given over here okay got it so yeah now let's take a look at this example for better understanding so here initially this hole is a complete one grid whole is a complete one grade correct and this whole grid has a mixture of ones and zeros as you can see there are some one there are some zeros here so that's why we can't take the whole as a leaf node and we Mark each Leaf as 0 and value can be any either one or zero okay now after doing this we take four different cells that this the top left cell uh the top right cell bottom left cell and bottom right side we take four different cells correct because these this current this whole Matrix initially was a mixture of one and zeros and if you have some such type of mixture we divide into uh sub uh Matrix or subgrace that is top left top right bottom left and bottom right and of each of equal size yeah note that each of equal size so top left so as you can see the all the cells of this top left Matrix are same since all are same we can make this as a leaf node and terminate so yeah that's why we set is left as well and value as one because all the cells have same value one so that's why we set value as one and is leaf s two we mark this as a leaf node correct simple as it is now if you check for the top right see now the top right has again a mixture of um zeros inverse right as you can see some are zero some are ones so we again need to divide this top right into uh child like top left top right bottom left and bottom right yeah so the same thing we are doing here this top right has a mixture of zeros and ones and that's why we can't make it as Leaf node so we set is Left To Zero value can be any either one or zero and we hit again mid four trillions for that right that the top left top right bottom left and bottom right now in the top left as you can see this all four cells has the same value since it has the same value we can mark this as a leaf node it has the same value so we can mark it as a leaf node so that's why we mark it as a leaf node to true and value is zero as all are zero similarly for top right the markets as a lift as all the values are same that is zero for bottom left all values are same that are all ones so you can make this as a leaf node and same for bottom right so I hope you guys understood that how we are doing this right how why this we have Force you know for only this node because it is mixture of some zeros and ones now if you check for bottom left this is the bottom left correct this whole complete this is the bottom left and for this bottom left all the values are same that is all our ones here so that's why we can mark this as a leaf node and the value is one is leaf is true and value is all one so one and similarly for bottom right this bottom right we can again mark this as a leaf node because all values are same and since all values are same like this as leaf and our value is 0 set to 0 because all are zeros okay so the only thing is that if is leaf is false then we can take anything as a value either one or zero because we have mixtures of one and zero yeah as you can see mixtures of one and zero but if all the values are same then we will mark value as the value of the grid correct so this question is a simple noun same ah first in check for values in current grid okay now if you here you have two options right the second party has two options all values same and here make sure of zeros and ones okay here you have to option now if all the values are same then Mark grid as leaf so you will Mark is leaf to true and value to value of Grid or value of sense of grid because all are same now here you have mixtures of zeros and one then what you will do you will divide into four chain that is top left top right bottom left and bottom right now for each sub children's or sub Matrix you will again check for this now after this you will again go to Step One step one yeah for again for the same step one and this is where recursor occurs that you again go for the stepper again check if are the all the values same if not then again divide if not then again divided into four top left top right bottom left bottom right and go again go to step one so this is where the recursor occurs and also in the equation that it is state that if the current grade has different values and in that case recurs for each result of a proper subgrid and find the answer so this is where the recursion occur so simple the question is simple uh that we for a current grid we need to check for these two condition if this is the case then we divide it in four children we Mark for this we Mark is leaf is equal to false we simply Mark is left as false value to either 0 or 1 it doesn't matter 0 1 and which are and we divide it into four children and again Lower equation simple as it is so yeah the approach for this is simple that we have discussed currently and now let's look at the coding part where we will discuss this in a detail so here this is the basic structure of a quiet tree that it's given here now uh here this is the function that we have so here we are passing four parameters to the construct query so one is the grid and second is the starting of the row ending of the row starting of column and ending of column and always this would be a square grid okay so Square grid that's why we would be able to divide into four grids correct this is so Square grid as always as you can see n cross n it is a square now okay now the now here in this construct wet frame we have this base condition that if roadside is greater than rho n or column stat is greater than column then we simply write a null okay now we initialize is leave to True initially we initialize it is lift two to and we uh store this well as the first set this is the first row start and column start correct this is the first cell of the crate now we check for all the cell in the current rate if the values are equal to one well this is the first one if all the values are same then what we do then we simply return a node with a valve and true means it is a leaf node correct node has two properties one where a second is left so we return is left to true and well as the values in the current grid and if in the case that if grid of i j is not equal to 1 that means we have mixtures of 1 and 0. so initially if it would be zero then here we found one or if initially it was one then here we have found zero so somewhere it is a mixture of zeros and one so in that case we make these lift to false so that node can't be a leaf node and for that case we have two Traverse for four children that is the top left top right bottom left and bottom right this thing we are doing here for a mixture of zeros and one and yeah this is row made in column made just to make four partitions see initially it was a complete grid so this was the complete grid as we discussed this uh top right now it was a mixture so we make partition for this like for row made and column made and we to uh to create four sub grids for the current grid so we made partition Romanian column made and we construct it poetry again yeah right we constructed by tree again and we return a node so we return a node that and this uh this earlier this root node has what this root node has is left as false so easily phase uh Force value can be any and it has four children that is top left top right bottom left one bottom right so we return this top left top right bottom left and bottom right for this type of ah node which has mixture of zeros and one so yeah I hope you guys understood the code here that we are checking with uh checking for all the cheaters if we have mixtures of zeros and ones and otherwise if all are the same then this directly written here the node with a value n as a true it won't have any as such uh children's correct so yeah this is how the recursive solution will work now talking about the time complexity see here the term in total number of um in the verse kill how many total number of cells are there in total number of cells are there n Square so in the worst case our time complexity would be big go of n square into log of n y log of n see here we are doing a recursion and log of n times we have to at a Max log of n times we have to call for recursive this many times we have to make recursive call and since here we are checking for n Square uh grid so that's why it's n square and log of n correct and the space complexity here would be big of log of n this because this many times the requires a call will occur correct so yeah that's for the time and space complexity uh and yeah that's all for this video I hope you guys understood the question this is the main thing here was to understand the question and the approach once you have understood the both question and approach then it's simple for you to write the code for this it is it was very much simple if you have understood the question so yeah and if you are still any doubts then do let me in the comment section make sure you like this video And subscribe to our Channel thank you
Construct Quad Tree
construct-quad-tree
Given a `n * n` matrix `grid` of `0's` and `1's` only. We want to represent `grid` with a Quad-Tree. Return _the root of the Quad-Tree representing_ `grid`. A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes: * `val`: True if the node represents a grid of 1's or False if the node represents a grid of 0's. Notice that you can assign the `val` to True or False when `isLeaf` is False, and both are accepted in the answer. * `isLeaf`: True if the node is a leaf node on the tree or False if the node has four children. class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; } We can construct a Quad-Tree from a two-dimensional area using the following steps: 1. If the current grid has the same value (i.e all `1's` or all `0's`) set `isLeaf` True and set `val` to the value of the grid and set the four children to Null and stop. 2. If the current grid has different values, set `isLeaf` to False and set `val` to any value and divide the current grid into four sub-grids as shown in the photo. 3. Recurse for each of the children with the proper sub-grid. If you want to know more about the Quad-Tree, you can refer to the [wiki](https://en.wikipedia.org/wiki/Quadtree). **Quad-Tree format:** You don't need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where `null` signifies a path terminator where no node exists below. It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list `[isLeaf, val]`. If the value of `isLeaf` or `val` is True we represent it as **1** in the list `[isLeaf, val]` and if the value of `isLeaf` or `val` is False we represent it as **0**. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** \[\[0,1\],\[1,0\],\[1,1\],\[1,1\],\[1,0\]\] **Explanation:** The explanation of this example is shown below: Notice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree. **Example 2:** **Input:** grid = \[\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,1,1,1,1\],\[1,1,1,1,1,1,1,1\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\]\] **Output:** \[\[0,1\],\[1,1\],\[0,1\],\[1,1\],\[1,0\],null,null,null,null,\[1,0\],\[1,0\],\[1,1\],\[1,1\]\] **Explanation:** All values in the grid are not the same. We divide the grid into four sub-grids. The topLeft, bottomLeft and bottomRight each has the same value. The topRight have different values so we divide it into 4 sub-grids where each has the same value. Explanation is shown in the photo below: **Constraints:** * `n == grid.length == grid[i].length` * `n == 2x` where `0 <= x <= 6`
null
null
Medium
null
1,493
hi everyone my name is Steve today we're gonna go through one classic approach one classic algorithm to solve a series of problems we can almost use the identical code to solve it at least four problems on my code so this is a very classical and typical algorithm that we could apply to a lot of problems and of course you're going to encounter problems in your actual interview or use this one as an example to go through this first max consecutive ones three what the problem is saying is given an array of zeros and ones we may change up to K values from 0 to 1 so this K is a variable it could change like in the given example 1 first example K equals to 2 in the second example K equals to 3 K could be you go to any different number as long as K is smaller than or equal to the length of the array a the output of this one is going to be 6 and why because we can change up to two zeros to one and then we can get the longest two consecutive ones of this changed array the length of that array is 6 so explanation here we can change this 0 to 1 that's going to give us this sub array and that has the longest length and all of the elements inside that several rainism what makes sense let's take a look at the second example in this example K equals to 3 that means we can change up to 3 numbers from 0 to 1 which 3 that will change we changed this and this gives us the longest summer rate that has all elements which are 1 so that is the longest one length of that is 10 so what returning 10 how can we approach this problem one typical approach is that we can use a two-pointer technique the can use a two-pointer technique the can use a two-pointer technique the right one keeps moving until it reaches the and another way how do we know which one's should we flip which zeros should we flip how do we maintain that state because this max consecutive ones could come from any sub array how do we keep track of that so we used a second variable or we call it slow pointer slow pointed points towards a left any sub array that's a segmented by these two pointers for example the point here slow pointer is pointing here fast pointer is pointing here any SAP array pointed out by these two pointers they always contain had a max of K zeros so this is the invariable state that we are going to keep we're going to maintain while we go through this array and during this process we can keep updating the result we'll just call it max length so that in the end we can simply just return the final max length it's kind of abstract - you talk like that so we'll abstract - you talk like that so we'll abstract - you talk like that so we'll use a simple example to go through this for example we simplified K to be only 1 and we want to find the maximum possible length that we can find by flipping only 1 0 to be 1 how can we do that we use two variables one is j1 is I J is the fast pointer that keeps moving until it reaches the end of the given array and high is the slow pointer which keeps moving but it will keep the distance between I and J any elements for in this segment will have at most K which is equal to one has at most one 0 let's take a look at the code we have a for loop jay-j keeps moving which is the fast jay-j keeps moving which is the fast jay-j keeps moving which is the fast pointer as long as soon as fast pointer reaches the end then we'll just break down here is the actual code we always need to check in this one the fast pointer will always need to check what the fast pointer is pointing towards a zero if that is the case we need to tetramand okay immediately because that means we encountered and 0 the max that we can bear in such a new sliding window is K which is 1 in this case so we need to decrement the second logixx yok is smaller than 0 we need to keep incrementing I until we shrink the window size do you have enough zeros have them left behind us then we are safe to move up this is what this wire loop actually means this is a template code that we can put to use to solve a lot of problems and along the way we'll maintain this variable we just caught result in this case the result it could be the max already we reached in that case we'll just keep using max we'll just keep using result otherwise we'll use J - I we'll use J - I we'll use J - I J is the fast pointer I is the slow pointer the distance between fast and slow pointer is the max length if it is greater than the current result this is the logic let's walk through first in the very beginning both J and Ivy are standing at 0 so names J equals to 0 that's correct so what decrement K by 1 which means K becomes 0 continue move on now we need to increment J because here J is here in K is not smaller than 0 we don't do anything here and here 0 minus 0 is still 0 so result is still 0 then we move on J plus 1 J moves to here now J is not equal to 0 so what we'll have is and K is not smaller than zero either so we don't enter this one instead what we have is we can update resulta because we have 1 the length of the maximum sound and this moment is 1 right because 1 minus 0 is 1 ok 0 compared with 1 that is 1 the maximum sound we have is 1 all right move on at this point what do we have because we increment J again J is 2 minus 0 is 2 all right then here 3 minus 0 is 3 result so far we got is 3 the max length of consecutive ones is 3 all right perfect moving on next we got J equals numbers Nance J equals to 0 alright at this point we need to detriment K by what K is minus 1 at this point which means we need to enter while loop now so K is smaller than 0 at this point we check nuns I naught is equal to 0 is that the case yes that is the case which means we can leave this 0 behind us because we have another 0 here and the max we can reach is only 1 0 K initially is what all right we move I towards the right all right I towards the right and K is incremented the max result didn't change because 3 minus 1 is tomb 2 is not greater than 3 so the max result is still 3 then we increment J becomes at this position we actually do have a greater max length which is this one J is equal to 5 and I is equal to 1 so 5 minus 1 is 4 so we have a better a greater a larger result which is false so continue J will increment now we have 6 minus 1 then we have a greater length which is 5 so at this point we can pause and say based on plain sight just take a look at this one case the initial K is given u 1 which means we can flip up to only in 1 0 to 1 now we know the max length which is we should flip this one the max length is going to give us 5 excluding this one if we include this one it's going to be 6 then we can plus 1 here that's going to make it work all right then we'll continue to move on what increment J becomes here so we have J equals to 0 so then will decrement K again so you see we are following the same pattern so these two pointers will keep iterating through until the fast pointer reaches the end of this given original input array so ok decrements now we need to enter this while loop come in here so I will keep incrementing right we can the max we can have is up to 1 0 in between this range I keeps going up i keeps going on at this point naught I is equal to 0 so we'll increment K now k equals to 0 that would increment I and we'll break out of this while loop so we'll attack what increment J again J keeps going up then J keeps going up at this point J has reached the end of this given input array now we can safely return the final result which is 5 this is the M witness I hope this visualized what could make sense and could help people better understand how the sliding window really works we use two pointers slow and fast pointer and along the way we keep updating the result that's the core idea of understanding a sliding window now we can quickly put the ideas into the actual code to solve all of these four problems almost using identical code so let's first tackle this problem here we have well initialize a variable which is quite a result as we put it in the code as we saw in the slide in the end we'll return the result so we all have two variables two pointers imj as long as the fast pointer which is j in this case is smaller than the less of this array Jane keeps going up and first we'll check the fast pointed well then this one is equal to zero if this one is equal to zero then will decrement K right and then we'll have in while loop we'll try to shift the slow pointer towards the right to leave any other zeros behind us that's what it means while K is smaller than zero what we'll do is what check will try to find the zeros on the left side to move towards the right to what you will try to move the slow pointer towards the right and move and leave those unnecessary zeros behind us so we'll move by a I equals to zero and then we'll increment K in this case and will always keep incrementing high so that we shift I towards the right will move a slow pointer towards the right and then we'll compare in a freezeout result we'll keep updating the max length along the way here we need to +1 that is big host we are flipping +1 that is big host we are flipping +1 that is big host we are flipping we're not deleting so while flipping ones to zero were flipping zeros we're changing zeros to one so that's why we need to +1 here yeah this is the actual need to +1 here yeah this is the actual need to +1 here yeah this is the actual code let me quickly run it to see if there is any syntax are up there is one what is this cannot find single nuts okay this should be a nothing else all right that's right again alright accept it let me quit the hit submit alright accept it this is the number one number two you let's solve this one we can use almost identical code let me just quickly calm let me just quickly copy in this code we can just put it here directly and we can change this one to be to use the same parameter name and it will initialize a K to be 1 in this case that's it because this API signature it doesn't have K so what just put KB and K in this case is equal to 1 so this problem the input 1493 is basically a subset of this one right this one is like in general problem so now let's hit run code and see wrong answer okay I need to remove this plus one because this one is deleting it's not flipping right that is why I output it for but the actual expected one is three and let me write again all right except it submit also accepted cool let me copy this one exactly the same code into this one notes this one is numb so let me change it to be a fine max consecutive once that means okay we need K to be 0 that means we can we don't need to flip or delete any zeros to be 1 so we don't allow any zeros that means K it should be 0 let me just hit submit run come again run go first I got it now let's hit submit alright also accepted now we have this one max consecutive ones legal problem 487 we can still use the same code almost identical code let's copy this one and put it here and change the parameter name to be a to make it consistent that's seen the problem of this one is asking us for the maximum number of ones in there where you can flip at most one zero okay one zero means okay it was the one that's it let's see run code first all right accept it let me submit accept it so you see this is a very generic solution of course we can still apply almost identical code to solve other similar sliding-window problem a big similar sliding-window problem a big similar sliding-window problem a big shout-out to Lee who has summarized all shout-out to Lee who has summarized all shout-out to Lee who has summarized all of these in his post so I hope this video does help clarify how signing winner could help to solve any of your problems or leave code problem this video is helpful please do me a favor and hit the like button that's gonna help a lot with the YouTube algorithm and I'm really appreciative and don't forget to subscribe to my channel as we continue to go through a lot of interesting interview our leave code all Amazon Web Services problems and please leave me any comment questions down in the comment section below I would really appreciate to seeing any feedback that's it for today's video thank you very much I'll see you guys in the next one
Longest Subarray of 1's After Deleting One Element
frog-position-after-t-seconds
Given a binary array `nums`, you should delete one element from it. Return _the size of the longest non-empty subarray containing only_ `1`_'s in the resulting array_. Return `0` if there is no such subarray. **Example 1:** **Input:** nums = \[1,1,0,1\] **Output:** 3 **Explanation:** After deleting the number in position 2, \[1,1,1\] contains 3 numbers with value of 1's. **Example 2:** **Input:** nums = \[0,1,1,1,0,1,1,0,1\] **Output:** 5 **Explanation:** After deleting the number in position 4, \[0,1,1,1,1,1,0,1\] longest subarray with value of 1's is \[1,1,1,1,1\]. **Example 3:** **Input:** nums = \[1,1,1\] **Output:** 2 **Explanation:** You must delete one element. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`.
Use a variation of DFS with parameters 'curent_vertex' and 'current_time'. Update the probability considering to jump to one of the children vertices.
Tree,Depth-First Search,Breadth-First Search,Graph
Hard
null
514
all right let's talk about the freedom trail so this question is pretty long and i'm going to use my own definition to translate and try to explain so whatever you uh what whatever you get right you should return the minimum number of steps to spell the location in a keyword so uh in the example like you have two strings one is ring the other one's key and inside the ring there's a button there are a bunch of character so inside the key you have to pick the closest character in the string or string of ring and find out like how many steps you rotate is either clockwise or counterclockwise and after you pick the character you have to press the button which is another step so uh whatever the territory inside the ring you need to add these two steps to press the button right so 3d will be two characters you still have to press two times right so g uh the first character is g and you're super lucky to get the first g right over here and you need to press the bottom which is what the uh one step for the g and the second character is d you need to rotate so you don't know is clockwise is closest or counter clockwise closer you have to try both and then uh for this example it's definitely the counter clockwise closest right you rotate on i mean rotate left right two times one two so d will be on the top and then you press the bottom then you know it's four technically it's full step right so uh using the same logic so we need to build the uh build function i mean fill it up with the algorithm right so i'm going to use a map and map is actually stored in my ring uh character and also the index uh corresponding with the uh so g can be repeated right d can be repeated right but uh the thing is different is the index d and in the index first the index second is different so you have a set to store the index value character is the value and i mean the key is the value and also i have a 2d array which is actually stored a minimum number that you actually rotate right you can rotate clockwise or counterclockwise but this is how you actually need to memorize and this will be super simple i'm going to initialize my tp right ring and represent key and i'm going to insert my dp to new in and iron all right now i need to also initial my map and after i initial my map right i need to actually um initial my hash set to a headset before in i so this actually helped me to um to initiate my headset very quickly so i'm going to say filter see represent ring.i see represent ring.i see represent ring.i every character inside the map i need to initialize that and then for each headset i need to actually add the index right first three which is the zero right and then the last two which is one two three four five six step seven all right so two will have zero and seven all right later i need to uh initial my dp to negative one which mean i mean negative one is actually like this uh i haven't moved anything right so fall into array dvd and then erase the fill e with negative one and then i'm going to call my helper function so my helper function is pretty similar with the uh constructor i um wait one more so i do have an index i'm gonna call x in the x folder ring and index uh in this y folder key so i'm going to store the number of steps they rotate right rotate on the clock and then i'm going to call this function and i'm going to call ring and then the beginning index is definitely zero and then t is also zero and don't forget you need to press the button so the number of times you press the button depending on the length of the key which is m right so i'm gonna plus them over here so uh whatever uh you rotate or you always depend on the y right if y the index uh for the key if y is actually equal to the key down then you return zero okay because you already match uh your key right so this is definitely easy and also if you already visit so if it's already the g i mean if you're already a d and d then you don't have to uh visit again right so if ep x if x y it's not equal to negative one right you return ct x y and also now i need to know my neighbor uh my next character is to be honest so my next character follow um for the character inside the string key so i'm going to say string integer and i can say doesn't matter so next it's actually depending on what depending on my key first all right you're always depending on my key not the ring so map is messed up get uh at y position right so always depending on my strength and i also need to memorize um i mean the variable to memorize my minimum so this is the next value i'm going to finish that to my next value and um now i do know like my next character inside the curve g i mean just for example g right this is going to be zero and seven be honest but i need to make sure this is always a positive number so i'm going to say in um x is a sorry not x should be one way is equal to the hardness the absolute next minus x so x represents the last index you will tell right and then next represent the current uh the current index you want to go over right so imagine you are a d right here right and then you want to uh rotate to two so this might be negative because uh you don't know like you want to go on clock clockwise or come across right so uh this is one way but it doesn't matter it's clockwise or controllers because you're already absolute right but we need to find the other way so one way is probably a clockwise and then we change it um the second way uh another way which is uh counterclockwise right so um i would say that what uh ring then minus one way so this is actually give you another one and you need to find the minimum value between the clockwise or counter clockwise right here that means uh in steps it's equal to metal mean one way and then another way okay and later on i need to actually um keep searching on my following character and i will say mean is actually equal to method mean and i'm going to say mean and also what step plus the next character which is fine next step and then i'm going to say i'm going to pass in the ring and follow for the current index which is next and the key and also y plus one this is because we have to move on the next character inside the key and then the uh when we call this function uh ring the next right and when you bring out the next index and then there's a photo for the next right this will be the last position you were in the ring and then later on you were just storing your mean into your dp so dpxy is actually and then you're just returning so mean uh me is pretty easy minimum just find the minimum right okay i have a mistake so oh this is not sorry and try again all right about the test but i want to make sure i have a better solution for this so which is what i want to reduce this so i'm going to say ring that length minus one way and then comma one way so find the smallest step between the concrete clockwise or counterclockwise and you should be the same and i'm going to run the code and this is super easy right so let's talk about the timing space complexity for this one space is pretty simple like you actually need uh the uh um by m right because you initial embankment and then you store your character inside the map so which is unbanned and then time is also uh also the same to be honest i mean for the worst case and by hand for sure but you're always increasing your why right so 10k is not unbalanced but it's less than abandoned housing but then for the worst case and this is the quick note for this so time capacity and space complexity and i'll say and m either represent a random key and there is no other thing to talk about so you just have to know like uh the step you when you want to find a minimum you either uh you need to include your current stack for the from character current character and then you find the rest of it and this will be pretty much the solution and if you feel helpful subscribe like on it and i will see you next time bye
Freedom Trail
freedom-trail
In the video game Fallout 4, the quest **"Road to Freedom "** requires players to reach a metal dial called the **"Freedom Trail Ring "** and use the dial to spell a specific keyword to open the door. Given a string `ring` that represents the code engraved on the outer ring and another string `key` that represents the keyword that needs to be spelled, return _the minimum number of steps to spell all the characters in the keyword_. Initially, the first character of the ring is aligned at the `"12:00 "` direction. You should spell all the characters in `key` one by one by rotating `ring` clockwise or anticlockwise to make each character of the string key aligned at the `"12:00 "` direction and then by pressing the center button. At the stage of rotating the ring to spell the key character `key[i]`: 1. You can rotate the ring clockwise or anticlockwise by one place, which counts as **one step**. The final purpose of the rotation is to align one of `ring`'s characters at the `"12:00 "` direction, where this character must equal `key[i]`. 2. If the character `key[i]` has been aligned at the `"12:00 "` direction, press the center button to spell, which also counts as **one step**. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling. **Example 1:** **Input:** ring = "godding ", key = "gd " **Output:** 4 **Explanation:** For the first key character 'g', since it is already in place, we just need 1 step to spell this character. For the second key character 'd', we need to rotate the ring "godding " anticlockwise by two steps to make it become "ddinggo ". Also, we need 1 more step for spelling. So the final output is 4. **Example 2:** **Input:** ring = "godding ", key = "godding " **Output:** 13 **Constraints:** * `1 <= ring.length, key.length <= 100` * `ring` and `key` consist of only lower case English letters. * It is guaranteed that `key` could always be spelled by rotating `ring`.
null
String,Dynamic Programming,Depth-First Search,Breadth-First Search
Hard
null
1,526
Key side suggestion in between a question improve my mobile number and all the toof target tried to give positive subscribe now to receive so let's get started tell explanation remember on Monday that is Monday answer that Papa special loot kaise ho that you are dry Lucerne 61234 time, 100 deal-points from this point, that research is serious, so now we 100 deal-points from this point, that research is serious, so now we 100 deal-points from this point, that research is serious, so now we will have it, so like it, comment share it and if you want, if we subscribe, now it is The industry is the sugar of its obscene abuses, where if you open her legs then do it today and if this ride is left then open only and only the one and only, it is gold, how hungry are you, first 19 of you, we made you all the first ingredient, then we reached till one Hussain and nurses. If one comment is total then everyone will understand on the exam. 10th board 231, there were five photos, one 154 that Sohil that we can see the end questions on how to develop walnuts, five meanings of glue can be used directly, it is okay, fennel is this. Katoch sees that there is an example country where they will reach Singoli, I make all the idlis with us, 2012 Sameshwar can see first, to take it to, at this time, we have to take the index of shares, a cylinder with aloe vera in it, we have to print it, when will we come and take it. It is going to take from 2.5 inches to 2.5 inches when will we come and take it. It is going to take from 2.5 inches to 2.5 inches that in this I want my moha point, I want the noose of the phone, if we have done all the joint, then from here till here my channel has to comment because we have become full and part with it. Hey can't write so to take us to the destination if we comment if we are a pride and after that what happened is this girl I will go to perform my target then after that you saw all these elements positive a that and now about this meaning To index se ko relaxed terminals are already verses so we have to comment that we have improved everyone so evening we had folded it on one side and then after that what happened now I am telling this from our recognized side hun that end How many forms are there in campaign 2004, will we go to the right end, this is our destination, now we will have it and at this time, this element forces phone number will be applied to it, so let's see, I have always recognized correctly, this entire grid day soap from 1.5 What I said grid day soap from 1.5 What I said grid day soap from 1.5 What I said and anyway what I can say is that if the defined means gram to reach any part of you all, then it is okay, while the other one goes, so what will happen to them, how many points can I reach now, hey I - This points can I reach now, hey I - This points can I reach now, hey I - This is the point, so now we will subscribe two 14 more, okay, only then the total became together, now let's look further, now we have seen that from 575, now we have seen that we have to go down to 200 area approach question will be solved, the purpose of this is that it is quite It's simple, it's a good festival, so I said, whoever is coming is successful, 5136, so whoever will read this post so much, we will use it, take it, at this time, after that, now what am I seeing in him that my Do you have any tips on the meaning of decremented apps or what does it mean in English that Aryan I - World's positive a that Aryan I - World's positive a that Aryan I - World's positive a hello you can reach the next element is rich in ghee, the difference is that the price distributed it hot, I had slept, I slept, the answer is accepted. That the commission's website Pimple Agar Life Indian Political Cartoon Darshan Suvvar Hai Ki I Am Ghaziabad was posted by
Minimum Number of Increments on Subarrays to Form a Target Array
html-entity-parser
You are given an integer array `target`. You have an integer array `initial` of the same size as `target` with all elements initially zeros. In one operation you can choose **any** subarray from `initial` and increment each value by one. Return _the minimum number of operations to form a_ `target` _array from_ `initial`. The test cases are generated so that the answer fits in a 32-bit integer. **Example 1:** **Input:** target = \[1,2,3,2,1\] **Output:** 3 **Explanation:** We need at least 3 operations to form the target array from the initial array. \[**0,0,0,0,0**\] increment 1 from index 0 to 4 (inclusive). \[1,**1,1,1**,1\] increment 1 from index 1 to 3 (inclusive). \[1,2,**2**,2,1\] increment 1 at index 2. \[1,2,3,2,1\] target array is formed. **Example 2:** **Input:** target = \[3,1,1,2\] **Output:** 4 **Explanation:** \[**0,0,0,0**\] -> \[1,1,1,**1**\] -> \[**1**,1,1,2\] -> \[**2**,1,1,2\] -> \[3,1,1,2\] **Example 3:** **Input:** target = \[3,1,5,4,2\] **Output:** 7 **Explanation:** \[**0,0,0,0,0**\] -> \[**1**,1,1,1,1\] -> \[**2**,1,1,1,1\] -> \[3,1,**1,1,1**\] -> \[3,1,**2,2**,2\] -> \[3,1,**3,3**,2\] -> \[3,1,**4**,4,2\] -> \[3,1,5,4,2\]. **Constraints:** * `1 <= target.length <= 105` * `1 <= target[i] <= 105`
Search the string for all the occurrences of the character '&'. For every '&' check if it matches an HTML entity by checking the ';' character and if entity found replace it in the answer.
Hash Table,String
Medium
null
609
hello everyone so in this video we will solve problem number 609 here we have uh one problem in that we have given some file name with content and we have to print the output if there is duplicate files for a particular content uh if like in this example we can see for abcd we have file one dot txt three dot txt and yeah only two files are there and for efch there are two dot txt four dot txt and four dot txt so here we have to print the unique file path along with uh along with the length if the length is greater than one if there are multiple files and also we can see here that the files are separated by a space so now we will start to write the code so what we can do like if we have this example we can yeah here you can see that if we split this string by space then we can get the path and all the files name and then if we split files by this uh this comma or this bracket then we can get the content and then we can use a hash map in that we can put the file path for a particular content also we can measure the length of all the content and if the length is greater than 1 in that scenario we can add that file name in the answer list so we will do that thing first of all we will separate them by space then for getting the content we will use this bracket okay so here we have our dictionary and here we have our length dictionary i in paths now we have to split these paths using space split we can write here i or path it's on us dot split here now we have to split the file name and file content also so for that we can create another loop for j in split of i and we have to start from the first position so that we can get all the files name and here we can write the split j is equal to j dot split yeah here we go now here we have uh like we have to append this content and file name and dictionary or s map for that we need key and value so our key will be split of j here we have only two like the length of this split z only two because when we split this using this comma here we have two part the first one and the second one and in second part we have the closing bracket so our key that means our content will be of 1 till -1 till -1 till -1 we don't need the last character and our value will be this path root a so a split of i comma 0 plus then uh this path one dot takes it two dos txt so this is a split z of zero because we used this comma to split these things so now we can use the first element here so basically put this thing here okay now we have key and value so now we can check if key not in d so we have to get the unique uh paths here so for that we have to use sat so we will use set here so if key not indeed in that scenario we can do d of key is equal to set and also we have to initialize our length of key is equal to zero and here we can do d of key dot add is equal to we have our value and also length of d of key plus one and now here we have to print our answer so we can use you know key comma value in d dot items so we have one hash map in that we have our content and the list of paths so here first of all we have to check the length of the files so if the length of d of key is greater than one then we have to append the list of files into our answer so here we can append our value and then simply return the value of answer now let's try to run it okay so here you can see that this code is running so as i told you earlier that first of all we have to split the full string using a space then we have the file path with content and to get content we have to separate them by using this comma and then we can use has map or dictionary to store the files name for a particular content and then we can also use one more hash map in that we can store the length for a particular content and then we can compare that if the length of that particular file or the set of files is greater than one then we can append that answer to our answer list so like that we can solve this problem now let's submit this problem okay so it is running here and it is a faster solution so this is the solution for this problem and if you face any difficulty in this solution please comment in comment below in the comment section and also if you want to get this solution of some other problem then you can write that thing also in the comment section thank you
Find Duplicate File in System
find-duplicate-file-in-system
Given a list `paths` of directory info, including the directory path, and all the files with contents in this directory, return _all the duplicate files in the file system in terms of their paths_. You may return the answer in **any order**. A group of duplicate files consists of at least two files that have the same content. A single directory info string in the input list has the following format: * `"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content) "` It means there are `n` files `(f1.txt, f2.txt ... fn.txt)` with content `(f1_content, f2_content ... fn_content)` respectively in the directory "`root/d1/d2/.../dm "`. Note that `n >= 1` and `m >= 0`. If `m = 0`, it means the directory is just the root directory. The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format: * `"directory_path/file_name.txt "` **Example 1:** **Input:** paths = \["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"\] **Output:** \[\["root/a/2.txt","root/c/d/4.txt","root/4.txt"\],\["root/a/1.txt","root/c/3.txt"\]\] **Example 2:** **Input:** paths = \["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"\] **Output:** \[\["root/a/2.txt","root/c/d/4.txt"\],\["root/a/1.txt","root/c/3.txt"\]\] **Constraints:** * `1 <= paths.length <= 2 * 104` * `1 <= paths[i].length <= 3000` * `1 <= sum(paths[i].length) <= 5 * 105` * `paths[i]` consist of English letters, digits, `'/'`, `'.'`, `'('`, `')'`, and `' '`. * You may assume no files or directories share the same name in the same directory. * You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info. **Follow up:** * Imagine you are given a real file system, how will you search files? DFS or BFS? * If the file content is very large (GB level), how will you modify your solution? * If you can only read the file by 1kb each time, how will you modify your solution? * What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize? * How to make sure the duplicated files you find are not false positive?
null
Array,Hash Table,String
Medium
2079
100
hello guys I hope you are all doing well and this video will be solving the problem leads called same tree so let's get started so the problem is that they give you two binary tree and they ask you to check if they are the same or not to solve this problem we're going to use the recursion techniques or the Deep first search technique where the function gonna recursively Traverse the two binary tree and it goes as deeper as it can at both directions left and right it's also known as a pre-order traversal it's also known as a pre-order traversal it's also known as a pre-order traversal so in simple terms the function gonna keep calling itself recursively on the left and right subtree and at each call it's gonna compare the values of the node at each level and also we're gonna check if both the nodes are present or not so let's take an example so that you can visualize how recursion is going to work let's say we have these two binary trees the first thing we're gonna do is to compare the rules of the first binary tree to the rules of the second binary tree so since the two are the same we're gonna move to the next step where the function gonna call itself with different arguments time the argument our left node of the root of the first binary tree and the left node of the root of the second binary tree then is compared the value of the left of the root node of both three so here there are the same as mean we return true then the function call itself recursively on the right subtree of the root node with different argument which are the right Shield of the first tree and the right shelled of the second tree then it's compared their values in this case they are the same so return true then once the recursion function reached the leaf node of Vault 3 the recursion terminate and return true so in summary the function compares the node values and both tree recursively and return true if all the values are equal and false otherwise that's it guys so let's jump at code in the solution the first thing we're going to do is to set a base case for recursion if either the first three or the secondary is non-wear return or the secondary is non-wear return or the secondary is non-wear return false otherwise we compare the value of the root node of poultry and recursively call the function is same tree with the left node of the rules of both trees and also cursively called the function with the right node of the rules on both tree and finally you should return to if the tree is a tree equality otherwise the result is false so the time complexity for this solution is all fan because we are visiting each node in the binary tree and the space complexities of H where H is the height of the tree this is because we are using recursion and that the worst case recursion stack will have to store each function calls so the second solution to solve this problem is going to be using the dipped first search algorithm but with iterative approach so the first thing we're going to do is to check if the Bold binary tree are not if it's true we return true otherwise if only one of these two binary tree are not return false then we create two stack to keep adding the node that are the same before we start the iteration they will have the root node of Ball 3 added to both them then we're gonna iterate throughout the stack while the two stack are not empty we pop the first node from the both stack and check if their value are not the same or return false otherwise we check if the note left both binary tree exists we push them to the stack and we continue by checking also the right shell of bow tree if they exist we push them to the stack otherwise we'll turn false because there is only one shot finally if they are all the same will return true foreign so the times complexity for the solution is off and where n is the number of node and binary tree and the space complexity is also of H where H is the height of the binary tree it's because the stacks store all the notes of the tree at the maximum depth which is equal to the height of the tree thanks for watching see you in the next video
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
1,046
foreign and welcome back to another video So today we're going to be solving the lead code question Loft stone weight all right so in this question we're going to be given an area of integers called Stones where Stone's eye is the weight of the eye stone so we're going to be playing a game and we take the two heaviest stones and we smash them together so if the two stones have the same weight then both of the stones are going to be destroyed but if they do not have the same weight so let's say one has a weight of 10 and one has a weight of five and in that case we're going to smash them and we're going to have an a new stone with a weight of five so the remainder is going to be added right so our goal here is at the end of the game there is at most one stone left and we have to return the weight of the last remaining Stone and if there are no Stones left we're gonna return zero so let's actually quickly look at an example so over here we have these stones and these are the weights and the first thing just to make it simple is we want to get the two largest numbers so a simple way to do that is just to sort the area right so let's sort it and we're gonna get seven oh sorry that would be eight first so that would be eight seven four two one right perfect now let's take the largest two numbers eight and seven now in this case when you smash them we would get a resultant Rock of weight one so let's add that rock and now we're gonna have the remaining uh it's gonna stay as it is all right perfect so now we've got it sorted again because we want to get the other two maximum values now this is one pass so we're going to keep doing this until we have at most one stone in our array right so now let's do it uh so we gotta sort the area first and it's gonna be four two one perfect now we take the largest two numbers four and two and when you smash them you get a resultant weight of two that's two one perfect now we take the now again in this case we had to sort it again because well in this case it is sorted but it's not always guaranteed so you sort it in this case it is take the next two largest numbers two and one and that is going to give us uh when you smash them we get a resultant weight of one so that's one perfect now we sort it again now these two have the same weight so now both the stones are going to get destroyed now finally we're only going to have one stone left and at this point we stop and this is the value we're gonna return this is the weight of the loss remaining Stone so now this could actually be one of our Solutions where each time we sort the array and keep doing this until we actually get the up to one stone at the ending now a problem with this is each time we have to perform a sort operation now this could actually end up being very exhaustive and uh performing a lot of the sort operations is not very efficient so instead let's try to think of some sort of data structure that we could possibly use that still kind of gives us the largest two elements but it's a lot more efficient so one we could think about is using a binary search tree now a problem with this is based on how the binary search fee is made it is just as efficient in getting the largest number specifically so a badly made binary search tree is just going to be as good as Big O of n to search an element right um so it that is not the best option but when it comes to this we have a very specific thing or data structure that we could use called a Max heat so I will just explain what a heap is very quickly and in a heap you could have a Max heat or a Min Heap and I'll just be showing you what a maxi is so in very simple terms you have a root term right and this root term is guaranteed to be the largest term that exists and now other words all of the children are going to be less than or equal to the root term so the root term is the largest and all the children are guaranteed to be less than or equal to right now another really cool property of a heap is the fact that when you create a heap so let me just show you so let's say I have a value here then I would always create it in such a way that I want to have a full binary tree right so that all the levels are almost equal with a maximum difference of one so in this case I would then add a note over here then I would add a note over here and so on and so forth right so this is the pattern I am going to be following and the reason for this is that I get a binder a full binary tree which decreases the search time as well now just to go in more details on how this would actually work is each time I'm going to insert a node I'm going to first check is this node less than or equal to the root and the reason for that is I want to keep holding property too now if that is not the case what I'm going to do is I'm going to swap the values of these two notes and I'm going to iteratively keep doing that right so let's say this value is greater than this value then I'm going to swap these values as well and the again the entire reason for this is that each root is the greatest value with respect to all of its children now this is going to be the data structure we use now we could implement this from scratch but instead I'll just show you how to use it with an inbuilt python Library so let's just look at how the code is going to look like all right so what I want to do is show you how this works step by step so it's pretty easy to understand how heat queue works so just to kind of show you the first thing I'm going to print out stones and then I am going to heapify it so what does that exactly mean so I have this area stones and now what I want to do is I want to construct it as a heap tree and to do that I can use the heapify function from eepq so he B5 and parts and Stones now I'm going to print stones and let's see what the result looks like Okay so let's run it just to be sure whatever it's getting printed over here is going to be the tree representation right but regardless we can notice that this is actually in ascending order this is not a Max heat instead this is a minimum Heap right so instead of the root being the largest value the root is the smallest value now heat Cube by default doesn't have a way that we can change this so a simple workaround we have is we can just treat them as negative numbers right so that way we basically get it in a descending order if we look at the absolute values so let me just run this and yeah as you can see we got the root being the largest value if you look at it as an absolute value so 8 and 7 and so on and so forth right so this is what we get so now each time if so let's look at what the next step is so the next step would be to get the maximum value so to do this with the function that we actually use is something called a heap pop and a heat pop is going to get us the maximum element in this case uh sorry this case so um we get the absolute value of that because we're storing it as negatives now we got the maximum value and now we want to get the second maximum value the second largest value so now all we had to do is we're going to pop again right so this is going to now give us a second largest value so now we've got the largest two values so let's take a look at them Max 1 and Max 2. so now we got the two largest values so let's just okay so eight and seven perfect that is what we were expecting now how exactly are we going to handle this so now in this case what we want to do is we want to keep track of what the remaining value is so the remaining value is going to be Max 1 because Max 1 is greater than or equal to Max 2. So Max 1 minus Max 2. now this is our remaining value now our remaining value can be zero but if it is non-zero so if remaining it's if it is non-zero so if remaining it's if it is non-zero so if remaining it's not equal to zero then in that case what we're going to do is we're going to add this value back to our Heap right so the way we do that and when we add this value back to the Heap it itself is going to get sorted in the Heap so this over here is called a heap Bush so heat push and we whatever so we want to give where we're pushing it to so we're pushing it to stones and what we're pushing has a value of remaining right so that is going to be it so that is going to be a full iteration so over here I'm going to print Stones just so you can see what a full iteration looks like so yeah so perfect so we sorted it we got the largest two numbers eight and seven and now in this case what we did is we pushed it back so one small mistake is when we push it back we got to push the negative value so that's going to be negative remaining um cool so this is going to be exactly what we want to do so now instead so this is going to be one pass so how can we actually do the same thing but for several passes so that's actually going to be really simple we're just going to wrap it inside of a while loop so we're going to first uh do this then we're gonna keep if I it and the rest is going to be in a while loop so while the length of stones sorry stone is less than one so while the land of stones is lesson one we're going to keep staying in this while loop so the first thing we do is we get the maximum values so we get Max 1 and Max 2 and then we get the remaining value now if the remaining value is not equal to zero we push that value inside so that is going to be the entire thing now at the ending if we exit the while loop that means we length of 10 or equal to one so either one or zero so we're going to return 0 if not Stone so Stones is empty we return zero else we're gonna return whatever the loss value is and that is the same as doing a heat pump so heat pop stones and again remember we want to take the absolute value so let's submit this solution over here and as you can see our submission has been accepted so thanks a lot for watching guys and do let me know if you have any questions thank you thank you
Last Stone Weight
max-consecutive-ones-iii
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone. We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is: * If `x == y`, both stones are destroyed, and * If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`. At the end of the game, there is **at most one** stone left. Return _the weight of the last remaining stone_. If there are no stones left, return `0`. **Example 1:** **Input:** stones = \[2,7,4,1,8,1\] **Output:** 1 **Explanation:** We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then, we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then, we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then, we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone. **Example 2:** **Input:** stones = \[1\] **Output:** 1 **Constraints:** * `1 <= stones.length <= 30` * `1 <= stones[i] <= 1000`
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
Array,Binary Search,Sliding Window,Prefix Sum
Medium
340,424,485,487,2134
312
hey everybody this is larry this is day 13 lucky 13 of the december league daily challenge hit the like button to subscribe on drummond discord uh let me know what you think about today's problem burst balloons so usually i solve these live and i do the explanation live so you see me as i think for the prom as i go through them uh and bruce bubbles is a burst bubbles first balloons is one of the most classic ones um where it is just hard to do without thinking about it is one of the so the short idea on how to get this is that it is dynamic programming um and the dynamic programming that you're trying to do here is called what i call anyway divide and conquer dynamic programming where basically you're trying to figure out you know you're you have some segment and you're trying to break them up into pieces and then trick try to figure out the solutions to pieces and then merge them back in some way okay let me actually read the problem because i actually don't remember which variation this is uh but i have some idea of it okay given n balloons from zero to n minus one there's a number in the balloon you press all the balloons when you burst i you get nums up left and numbers of i and numbers of white coins okay so basically in initially you burst one then you get three one five okay so i think this is one of those first problems that becomes very difficult for dynamic programming because at least this is the way that i thought i remember thinking about it way back when which is that uh in many dynamic programming problems you're able to be a little bit careless and what i mean by that is that and i'm not saying you're careless but you're able to be careless and what i mean by that is that a lot of those problems are symmetric right and what i mean by that is that symmetric it you could go left to right to left up to down to up uh and you go forwards or backwards and because it's symmetric it actually doesn't matter which direction you do it or what order you do it in um because if you're doing the wrong order you can just reverse the order and it's the same right so you know those are symmetric dynamic programming uh i believe this is one of those cases where it is not you have to do um because there's some implication about the states so let's solve this together and kind of see where we go oh this um okay there's an implicit one balloons on the left and the right okay uh and actually let's actually add them give though we will not burst them so okay so yeah so we will go for it together i like to explain just a little bit through code especially for dynamic programming because dynamic programming is all about the transitions and then we'll go through them together and it'll help me with the visualization as well and we'll see if i actually solve this uh in good time so yeah so now we i just do this to um just to pad the ones in the side so we don't have to worry about like weirdness um okay so then now um how do we want to represent it right so i'm spitballing here meaning that i'm thinking for my head it might we might make some changes later on but let's say we have uh i'm trying to find try to figure out naming stuff is always hard i always just write go but i think that's terrible for interviewing so if you're interviewing choose a more sensible name but let's just do uh get coins maybe uh you have a left a right interval right because basically you have the left and the right and you want to get the maximum way to uh burst these balloons and yeah and let's think about this for a second let me make sure so right now i'm just thinking about the base case i think the base case is when they collapse to one to only at one balloon and then when that's the case you can prop really just uh return num sub left i'm not sure if this is true but let's leave this here for now uh that sometimes it is not and uh yeah so we'll have to remember the base case but okay uh n is less than 500 so okay yeah so the natural way to think about this would be to go for um i in range of left sub right so what so the tricky part about this now is that usually you want to um choose the next bubble to burst but the hard part about this as we were talking about with symmetric and stuff is that you actually want to choose the balloon that is the last balloon to burst right so that means that you know we have some get coins of left to i uh and then um that means that we actually yeah okay i vaguely remember this now and that's why sometimes it's easy to have trouble with because you're thinking uh at least this is my way of thinking about it is that i'm always like okay now that we're having this interval let's say i want to burst one right uh you know i want to burst the one here that means that you know you may write something like okay get coins of um you know left uh i that and then i don't know where you may burst this balloon you get the score which is three one five and then now there's some like weird contiguous pieces and i think there is a dynamic programming that allows you to do that but that's going to be really slow and it's going to be like end to the cube or into the form or something like that so what you actually want for this problem and i'm trying to figure out a visualization but i guess this is a race a little bit too small uh and of course we added one in the beginning and the end what you want is actually okay what happens when i um let's just say middle when middle is the last balloon to burst right well when you know let's say this is middle just point at a random pointer if this is the last balloon to burst that means that we already burst all the balloons except for the uh outer bounds we bursted all the balloons and then now we have this balloon and now we finally burst it so it's five one and one right and in this case it'll be left right so it'll be five left and right which is one and one so in that way then now you can recursively go to the stuff that's in the actual uh in the components and then max over those so that's the way that i would think about it is really like i said the hard part is that you have to think about it you know for certain other dynamic programming problems you're able to think about it forward and the backward is symmetric so you're able to kind of think of it that way but in this problem these problems you have to think precisely it matters which direction you go and in this case that's what we're gonna do so okay so let's get best is equal to zero just for the max score oh yeah so if actually in this case this is not the base case then and we'll go over uh you know we'll go over the base case in a bit but okay so that means that now we want uh you know mid num sub middle times num sub left times num sub ray right as we talked about uh because now you know our borders let's just say is left and all the way to the right these are the last balloons to be burst and this is the score that we get when we burst it last but before that we have to burst all the balloons in between so we can do that so now the score as you go to this plus uh get coins of left plus one now left to middle and the reason why is that we actually never burst the borders in our constraint and this is something that we might have to talk a little bit closer is that um is that when we define the function that is critical whether you define the bounce inclusively or exclusively so basically uh burst all balloons inside left right not including left or right and this is because we also have it's an easier case to follow because we have uh the ones in the outside and we don't want to burst them right so basically now okay we get left we get middle and then we also add to get coins of um middle to right so that's the score and then we just check to see if it's a better score if it is then great and then we return best so that's basically our dynamic programming problem uh usually i will you know talk about memorization um i think for now um i assume that you have a good understanding of dynamic programming because if not i guess i should have said this disclaimer early on you should practice your dynamic programming fundamentals and foundations until you're more comfortable with this um so right now that being said i'm going to use a python trick called lru cache to be honest maybe sometimes i'm just a little bit uh tired right now and what this does in a very short explanation is that in python this is called decorator and a decorator this actually wraps the function and what this particular decorator does is that it wraps the function in a way such that when it sees the same input it will try to fetch that well first of all it will look at the cache if it's in there it will uh fetch from the cache and then return it if it's not in there it actually wants this code okay so yeah so then now we can just return get coins of zero and then n minus one cool and also we have to do the base case is actually uh again num sub left times and of course left is equal to right num sub well hold on a second right uh can is this the base case so let's say we're here we want to burst these balloons uh and then now we choose a mid that's like here and because we never we should never i mean uh i think i might have yeah uh error here so we start from left plus one and we go to write minus 1 in the middle just to get the balance correct um do we go to the right no yeah we don't go to right exactly so that means that in that case we don't have any base case i think and the reason is because if left plus one is equal to right which is meaning that they're next to each other then this would never run and then best would just return zero right so that's probably what we expect uh and okay so i'm going to give it a go just to test the compiler out that looks good uh i was going to look copy more test cases but i don't see any uh the one case that i'm worrying about is the n is equal to 500 so oops that's about 36.48 that's about 36.48 that's about 36.48 okay oh no this is too slow right well i was gonna say um so this is dynamic programming uh and what is the complexity of this right well the complexity of this is actually so the number of possible inputs is equal to um well n squared because left could be zero to n roughly speaking set it zero to n uh right could be also roughly speaking 0 to n and however and each of these so there are n square possible inputs and then the for loop in the middle is o of n so each chord does of n work so in total this is actually o of n cubed right so this is n cubed and for n is equal to 500 that is way too slow um so now we have to figure out a way to um to well to quit uh to optimize the n cubed to something faster uh because and cube is too slow right uh yeah so this is n cube for 500 cube it is probably pretty close so we would have to i do some optimizations maybe oh you cash is too slow i don't know i feel like lu cash has been a little bit slow lately so okay so what i'm going to do is just actually do what i usually do on stream that and just implement the memorization uh okay so then now let's say as we talked about um yeah the left could be zero to n the right from zero to n so let's just go cache is equal to uh doesn't really matter right times and for and then we y um is cached or uh calculated say is to go to the same thing but force instead right and i just like to be explicit because for education educational purposes i usually write it a little bit differently but yeah if calculated of just also want to make sure that i don't have an infinite loop somewhere by accident but i feel like i'm okay yeah so if this is you know calculated then we just return it from cache otherwise we put this into the cache and also set it to calculate it oops all right let's try again uh yeah so not gonna lie i double checked the test cases uh and it seems like this is one of those earlier problems where the constraints are a little bit misleading and well but actually end cube is fast enough and even though my test cases my test case of 500 elements it's uh too slow if i actually click on submit somehow it actually just accepts um so yeah so okay so yeah i hope that you have a good understanding this from even though that was a little bit awkward i added a little bit of things out uh because i don't know this was just a really awkward from the constraints but that said uh yeah it is n cube time uh and in o of n square space uh we went over why this is n cube so yeah let me know what you think hit the like button the subscriber and join me in discord uh remember that this problem is hard feel free to come ask me questions but also yeah uh practice and i will see y'all tomorrow bye-bye
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
1,603
Hello everyone welcome to my channel with mike so today we are going to do video number six of your playlist of data structure design today's question is quite easy 1603 easy level mark is also there the name of the question is design parking system so phone sometimes if good If it happens, either call or ask in the screening. Okay, let's see the question. It says that there is a parking system, you have to design it. Okay, and there are three types of spaces in the parking lot, first is big, second is medium, third is yes. The parking system will initialize how many Big Lords are there in the parking lets, how many medium stalls are there, how many small stalls are there, okay and there is one more function, what will happen next, it checks the weather there is a parking space by turning it off. If the type and note is ok then the tax type will send it to us in the parameters. Okay and the value of tax type will be either one or tu or three. One means big, tu means medium, three means small. Okay, why only cancer? In parking space of its stall type like if it is big then it will go in big stall only, if medium then it is small then it will go in small stall ok if brother is no space available then return water and if space is available then lot I put him in the stall, type him and start the return. Ok, so it is a very simple question, isn't it? I think it is not necessary to understand even the example, but I will tell you the style as it is mentioned here that when he If you did it initially, how many stalls are there in a big, how many stalls are there in a medium, how many stalls are there in a small, then zero is ok, now add it to it, I did it yesterday and send one, if one means medium, sorry, if one is there, then it is useless, if you are then medium. So for small, this was the right, okay, so one came, it means to park, there were six, so what space do we have in the big stall, yes, if there is one space, then it will be parked by one, so what can I park once by one? Did it and made the value of big zero that you because there was a stall, it got it, okay, so we made the turn true, now we have come again and added it, this time typed 'Tu hai tu', if you say, do typed 'Tu hai tu', if you say, do typed 'Tu hai tu', if you say, do we have space in medium? Yes, there is a space, so make it that and it will go to zero. Science, if this is done then return true because it is made to park. If it comes third in the medium stall, if third means small, what is it? If not, then brother, don't park. Can there be stall space in Big? If it is not zero then it is not a very simple question. What you have to do is simply store three variables - how many stalls are there in Big, store three variables - how many stalls are there in Big, how many stalls are there in Medium and how many stalls are there in Small, okay? So when this function which is for our parking system is not the function for parking system, I will send big medium small in it, then what will I do, I will assign big in this, medium in this, small in this. Thoughts it is ok and whenever we add it, If he comes tomorrow, what will I do, I will check the type of tax, okay, the car should not be parked, power, and if it is not so, then brother, if it was a bikar, then do B, mines, do it, meaning what we did, if it was medium work, then do M - do it or else. If it medium work, then do M - do it or else. If it medium work, then do M - do it or else. If it is a small car then do M - - it is ok is a small car then do M - - it is ok is a small car then do M - - it is ok and in the end make it unbreakable and proof because the car is parked, whether it was big or medium or small, that's how simple it is to code quickly and finish it. Today's question is of easy level, so it is better to complete it quickly. Okay, so let's code it quickly and finish it. Okay, so what I said, I will simply take three variables. Medium for the bag. For small and in this function, how many stalls have we got in them, it is okay for big and medium, you can also do this if the type is my medium, that means you have to do more medium, okay and if it is not so then Card type agar mera one hai ok stall use ho jaayega l se kar type agar mera tu hai to medium ho jaayega Next video thank you
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,997
hey what's up guys john here again so bitcoin number 1997 first day where you have been in all the rooms okay so this time we have n rooms right uh labeled from zero to n minus one and then we start from room zero okay and we will visit one room a day okay initially we visited room zero and the order we visited the rooms is determined uh by the following rules okay and the given like in a given index array next visit right so if you have been in the room i an odd number of times including the current visit on the next day you visit the room specified by this next visit okay but odd number of times right and then you if you have been in the room i even number of times then you can move forward and then you can move on to the next room okay so that's the rules and then return the first day you have been in all the rooms so that's the pre that's the description for this problem and the return module right so for example we have next visit zero so basically the first next video is always zero and this is because you know this constraints here okay so this next visit you this next visit will always be smaller equal smaller than the current index so which means the next visit can either be the current one right or uh or previous one right so that's why you know the first one is always going to be zero right as for the second one it could be either zero or one because this one is going to be either between zero and one right so that's why for this one you know the answer is two because uh as you guys can see right so if everything is it's following this one following the next video it's always the uh the biggest one then what we'll have like for this one since we can only move forward when we have visit current uh nodes even number of times so which means so here we'll have like zero and zero right so we'll visit zero twice then in order for us to move to the next one right that's why we move zero and zero right and then the next one will be one right that's why the answer is two because that's the first state because this is a zero day first day and second day right okay and then yeah so if we follow this example first right let's say if the list is like this right and then obviously we'll have like zero right and then what and then we have one because here you know the next day will also be one right so also be one right and then two three and then four right so if everything follows this then basically every time we'll only do a plus two to our answer to reach the uh the end right but we could but since this one the next one could be a smaller one could be a previous one that's why we have this example right so in this case instead of one zero one two we have zero two right so for this one if we write down okay so i think he already wrote that wrote it down for us basically we have zero right and then the next one is what next one we visit one right but then from one right from one here the next one is what the next one is zero it's not one right that's why we'll go back to zero again right and when we're back to zero you know we have to wait twice because you know in order to for us to move away from zero it has to be even number of times because after we move away from it's an even number and when we are back there we start basically we start from the very scratch from the very beginning right and then we move back to one and then two right so that's why the answer is six okay and then that's it and then the constraints right so apparently this one could be a dynamic programming right the only thing is that how can we uh figure out the state transition function right so uh we have dpi right so dpi means that you know uh the dates that right the dates that we need to take for us to reach this ice room okay it's going to be what going to be a dp i minus 1 uh plot plus 2 right so if everything like i said if everything is like this 0 1 2 3 4 right this is a state transition function right basically from the previous one we need another two widgets for us to be able to move to the next one right but for this but since and this object obviously this one is not a complete one because we could have some uh like uh regression right or because this one could be a small going back to a smaller one okay and then how can we do that right so let's say from the three here we're going back to one right so let's see from the three we have one here right or zero okay so what does it mean it means that it would take us some extra times extra step for us to be able to go from zero back to here right and how what was the steps how i basically how many days how many extra days it will take us for uh to take us to come back to this day right um maybe one is better okay maybe this one okay right it's gonna be uh you know to for us so how many days for us to get here from the first day to here right it's going to be dp of i minus one okay so you know so basically since this dpi means that to get this current dpi it means that we have to check the previous uh index previous like next value right which means we need to have like a next right so it's going to be a next equals to what equals to the next visit dot i minus 1 right so we are at current i here you know in order for us to know you know so this plus two means that you know if the previous one is the same it's a it's the biggest one right and then we will not basically if the next is the same as i minus one if three is 3 right and then basically we don't need to add anything it's going to be a zero right but if this one is one in our case right then we need to have we need basically this one will go back to one and then come back to here come back to the three again and how many days will it take basically it will take dp i minus one right minus dp next updates for us to come back right because dpi minus one is the ones that is the number of days to reach the current one right and the dp next is the number of days to reach today to this next right and if we do a subtraction then it's going to be a range basically this one from here to here is a dpi minus one right and from here to here is a dp next right and then apparently if we do a subtraction we get the difference right for us to trust to fro for us to come back from the next day to this dp i minus one right so that's it that's that so that's the state transition function right move this part to here and that's a state transition okay cool so once we figure that out you know the implementation is it's very short the code is very short here so it's like this dp right zero okay for i in range of one to n right we start from one because zero doesn't make sense because uh the n is greater than is at least two okay and then we have next right next will be the next widget of i minus one okay and then the dp i equals to dp i minus 1 plus 2 right and then plus what plus the uh the difference if there's any where is the dp of i minus 1 right my subtract the dp of next okay right and then that's it right and then we do a modular okay in the end just return the dp of minus one on the modular right yeah so there you go right i mean very short code uh so but the key part is to figure out the state transition function right and then uh so first you have to figure out the basic one where if anything is following is using the max next possible next index which is means we will never go back right and then there will be this dpi minus one plus two right but if we ever uh went back for some place and then we have to recall plus that regression this days right which is going to be dpi minus 1 subtract the dp next cool i think that's it right and thank you for watching this video guys and stay tuned see you guys soon bye
First Day Where You Have Been in All the Rooms
next-palindrome-using-same-digits
There are `n` rooms you need to visit, labeled from `0` to `n - 1`. Each day is labeled, starting from `0`. You will go in and visit one room a day. Initially on day `0`, you visit room `0`. The **order** you visit the rooms for the coming days is determined by the following **rules** and a given **0-indexed** array `nextVisit` of length `n`: * Assuming that on a day, you visit room `i`, * if you have been in room `i` an **odd** number of times (**including** the current visit), on the **next** day you will visit a room with a **lower or equal room number** specified by `nextVisit[i]` where `0 <= nextVisit[i] <= i`; * if you have been in room `i` an **even** number of times (**including** the current visit), on the **next** day you will visit room `(i + 1) mod n`. Return _the label of the **first** day where you have been in **all** the rooms_. It can be shown that such a day exists. Since the answer may be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** nextVisit = \[0,0\] **Output:** 2 **Explanation:** - On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd. On the next day you will visit room nextVisit\[0\] = 0 - On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even. On the next day you will visit room (0 + 1) mod 2 = 1 - On day 2, you visit room 1. This is the first day where you have been in all the rooms. **Example 2:** **Input:** nextVisit = \[0,0,2\] **Output:** 6 **Explanation:** Your room visiting order for each day is: \[0,0,1,0,0,1,2,...\]. Day 6 is the first day where you have been in all the rooms. **Example 3:** **Input:** nextVisit = \[0,1,2,0\] **Output:** 6 **Explanation:** Your room visiting order for each day is: \[0,0,1,1,2,2,3,...\]. Day 6 is the first day where you have been in all the rooms. **Constraints:** * `n == nextVisit.length` * `2 <= n <= 105` * `0 <= nextVisit[i] <= i`
Is it possible to swap one character in the first half of the palindrome to make the next one? Are there different cases for when the length is odd and even?
Two Pointers,String
Hard
556,564
2,000
hi guys I'm in this video see problem Le code reverse prefix of a word so given zero index string and character reverse the segment of the word that starts at the index zero and ends at the index or the first occur occurrence of that character so if the character is uh not present in the string in the word then do nothing just return the uh existing word itself so if you see the first example AB CD f d these are the letters present in the word and the character which we need to look for is c d so D must be we have to look for the first occurrence of D so in case let's say the example we have is a b c d e f d h you could see two DS are there but you have to reverse the part of the string where the first occurrence of D occurs from the starting till the first of this part this is what you need to reverse that will be D C B A and this would remain the same e f d h so this is the question so how do we solve this so what we can do is uh a b c d e f right so we can start iteration check whether a is equal to D no move the pointer whether B is equal to D no move the pointer Cal to D no D equal to D yes when you form D equal to D just break from the stop the and store this index before breaking it let's say index equal to I so here I is nothing but 0 1 2 3 so from 0 to three we have to reverse so how do we reverse for reversing if you take 0 to three indexing letters characters so we'll have one pointer here another pointer here so if you start a l i equal to0 I will Point here this is z and this is how do you get three that is nothing but the index whatever you have that is three minus I if you do that is nothing but three right so if you at B you have to compare it with C so B is nothing at index one and if you do 3 - 1 = 2 which index one and if you do 3 - 1 = 2 which index one and if you do 3 - 1 = 2 which is at that which is the index of the letter c so what you do is you have to check if the word of I okay not if word of I should be reversed with word of n minus I index minus I mean ending index what are you minus I so A and D how do you swap what we can do so we will temporary character in that we store the word of zero that is nothing but a now we can modify word of 0 to word of three that is nothing but D now word of d uh sorry yeah word of the will be equal to word of zero but it is being stored in character C so this is how you reverse next again so you have to do the iteration until index by two because still here it is if it is s also that's not a problem a b c d e if you have and E is the character which you need to find this is enough C of course you can either give less than equal to index by2 or lesser than index by2 is also fine even means equal size OD means yeah same point it Point stop the Lo so yeah shall implement the logic so first let's write the size then let's have a index minus one and WR it over the word so check if word of I is equal to the character which you required then if that is case just break from the loop so but before breaking from the loop what we need to do is we have to store index = minus one uh sorry have to store index = minus one uh sorry have to store index = minus one uh sorry I so and they have told if the character is not found in the array in the sorry in this word then you do nothing that means if the index equal to minus one itself you don't find any index I of the character then just return the given word itself here we not to do the F further things okay if you find an index IND if index is not equal to minus one then again you have to do the itation index by now here what we need to check you have to reverse for reversing what we need to do let's say character c equal to word of I and we'll modify word of I equal to word of in index - word of in index - word of in index - I now we can modify word of index minus I to word of I which is stored in C because word of I is being modified here that's why but before modifying we stored it in a character yeah that's it we should return now word this is not necessary if you don't give whato it works this condition will become false and will not run the loop okay because index is -1 by 2 means loop okay because index is -1 by 2 means loop okay because index is -1 by 2 means it's already less than uh zero so it won't run the okay let me just check what mistake I have made yeah I told uh less than index by that is causing the issue here because if you have ABCD uh if I run this and I can see the answer see or D and C are not reversing the last d and e d and a b and c yeah D and are reversing but when it comes to B and C it's not less than I expect know the condition becomes false and it will not so we have to give equals to so that all the conditions are taken care of now we will submit this yeah and for Java also same logic applies here you use character at I function then you create convert the word into array of characters and wrate over the array of characters to reverse it and at last you create new instance of that array and the string so we should submit this yes successfully submitted if you understood the concept please do like and subscribe to the channel we'll come up with another video next session then keep planning thank you
Reverse Prefix of Word
minimum-speed-to-arrive-on-time
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you should **reverse** the segment that starts at `0` and ends at `3` (**inclusive**). The resulting string will be `"dcbaefd "`. Return _the resulting string_. **Example 1:** **Input:** word = "abcdefd ", ch = "d " **Output:** "dcbaefd " **Explanation:** The first occurrence of "d " is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd ". **Example 2:** **Input:** word = "xyxzxe ", ch = "z " **Output:** "zxyxxe " **Explanation:** The first and only occurrence of "z " is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe ". **Example 3:** **Input:** word = "abcd ", ch = "z " **Output:** "abcd " **Explanation:** "z " does not exist in word. You should not do any reverse operation, the resulting string is "abcd ". **Constraints:** * `1 <= word.length <= 250` * `word` consists of lowercase English letters. * `ch` is a lowercase English letter.
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
Array,Binary Search
Medium
1335,2013,2294
1,400
hello friends so today we can discuss another problem from lead code problem name construct k palindrome strings it's a very standard problem and i hope you have seen a lot of videos on it but i am making few videos on greedy problems so that's why i have chosen this problem if you have seen this problem you can skip that out but if you want to understand more on this problem you can keep on watching this video so it's a very simple problem but yet you just have to think over different cases that's why i've chosen this problem so in this problem you're given that you have a string s and an integer k and you have to construct k non empty pendulum strings using all the characters in s so you are given some characters in s and you have to form like k is equal to two in the first example as you can see so you have to form two strings which are actually palindrome and they only are forming using the characters in this s string if you can easily form like one valid answer the answer is true else the answer is false so that's the whole problem now how you can move about this problem so let's think about this problem for a second what is actually a palindrome yeah now actually what is a palindrome is if as you can see if both of the characters are same from reading from left to right is apparent okay now as you can see if i have two characters two alphabets of same type let's assume a bb or like they are in even occurrences so it is like a like two times a or a okay then in all of those cases you can easily form a pendulum because you just write down all the characters and it is forming a parent rule but if the numbers are odd if the characters or if the alphabets are an odd number then they always have to be the middle element what i mean by this is let's assume that i have a like i have a string of aba so in this as you can see the occurrence of a is two times but the occurrence of b is one time so it should always be in the middle then only it can form a pendulum because in the parent room you can either put it on the sides as you can see if i have two more character which is cc so i can put them on this side and one on this side and still it is apparent row but now if i have d and e i cannot put d anywhere else because like only one string to a parent room the character which are in odd occurrence should be in the middle on all the even occurrences should be on the left hand side like both one left one right one left and one right so it can form better but if the odd character should be only once and should be occurring in the middle okay so that's the condition now if you somehow find out how many odd characters are there so as you can see let's assume i have the string which is given to me which is s i have to first find out how what is the occurrence of each character like the occurrence of each other maybe a occurs five times b occurs three times c comes like eight times so we can find out the occurrence of this character and also by finding out the occurrence we have to also see that how many odd occurrences are there so if some character occurs some odd number of times then what it means by this is that there is one character that i have to put in the middle okay so i have to put that character in the middle it should also happen that the number of odd like the number of odd occurrences alphabets should be like it should not exceed k if it exceeds k then what it happened actually means is because for every string to be parent row i can only put a odd character at the middle so i can only form k i have to form k valid palindromes okay so now if i want to form k valid pendulums the number of odd occurrences characters should be odd or like it should be less than k because let's assume that i have odd occurrences character six and i have i can put one or acknowledge character in the middle of this string one in the middle of the string so there are only four if there is one more how can i place one more odd occurrence now if i have to place one more odd occurrence in somewhere in order of these strings and if i play somewhere else then they cannot be pendulum so i have to ensure that number of odd occurrences player should be less than or equal to k only if it's greater than k then we know like we do not have any option okay so now if they are less than k then we are not actually always fine so now if we are less than k then what we are actually like what we can do here is just put the middle character in always in all the strings so let's assume that i have a b c d and e okay now if i have let's assume uh five positions so one two three four five so put the odd accuracy characters as you can see or occurring is a b c d because it is only occurring one so it is odd okay so odd occurrence character in the middle which is like which is fine now i have ee left i have to fill the rest of the fillings the left of the positions with these characters now this is one factor one important observation you can also see that any positions which are left to me okay if the character length like if as you can see if all of them are even but the length of the even characters it should be greater than the empty positions what i mean by this is let's assume that now i have three positions left i have to make three more strings but the even positions like as you can see i have fit all the odd characters here now which means that only the even occurring characters are left so which means that ee is left or maybe f is left if this four times f is left so now i have to fill this out here now if the number of even positions the total number of even characters if it is greater than or equal to the empty positions then i can always fill them out why because see if let's say it is e so i can fill it out by e now i have three f like four f left so i can put out like two f here and two of here okay or i can also put it like i can put three f here f and one f here so it is always if i have the number of characters which are more than or equal to the number of empty spaces left then i can always fit if they are less which means that i have only two ee left but i have three empty positions then how can i like how can i even put or fill that so these are the like pretty much all the observations you have to fill in this problem if you understand all these problems you have to first write them out different thing different about the different test cases you have to encounter it and then you can easily solve this problem i'll move on to the code part now to even make it more clear so first you have to find out the occurrence of each character and the actor like the numbers occurrence can be even ordered iterate over all the possible characters from a to z and let's find out how many or presents are there if there is some operations out odd so as you can see if some character is occurring odd number of times we are actually also finding out even pairs how many even pairs are there because i have to also find out that how many even pairs are there as you can see i have to also find out how many even pairs are there and how many odd occurrence of numbers are there so as you can see let's assume that i have a bb now as you can see a is occurring three times which is fine but if you assume that this is only odd this is now if just remove out one a then all the other a's are actually also even pairs now so just remove down this a and all the rest are even pairs so that's what i'm doing finding out how many even pairs are there so if the occurrence is odd i know that there is one odd number like one odd alphabet which is fine but how many even pairs are there excluding this so the total number of even occurrences minus 1 they will give you even how many even pairs are there divided by 2 and if the number is already even so divided by 8 by a i divided by 2 so this would actually give you this order stored out how many odd like how many odd alphabets are there or occurring alphabet and even shows how many even periods are there okay so now as you can see if somehow my key is greater than n that the length of the string is let's zoom five and i would want to form 100 uh pendulum strings how i can form so this is false okay if the number of odd cat like odd occurrence alphabet is greater than k which i've told you the answer is obviously false else the answer is always true which are two because if it is less than k i can always define or i can always put out the like the odd position somewhere and then only the even positions are left and thus i can always distribute the even numbers among the empty spaces and that's the answer okay so these are the only two cases if it is greater than like if the length is smaller and the number of k is greater than it is obviously false if the number of odd is less then it is obviously false as dance is always true i hope you understand the logic as of the code for this part stay tuned for more videos after next one keep coding bye
Construct K Palindrome Strings
find-winner-on-a-tic-tac-toe-game
Given a string `s` and an integer `k`, return `true` _if you can use all the characters in_ `s` _to construct_ `k` _palindrome strings or_ `false` _otherwise_. **Example 1:** **Input:** s = "annabelle ", k = 2 **Output:** true **Explanation:** You can construct two palindromes using all characters in s. Some possible constructions "anna " + "elble ", "anbna " + "elle ", "anellena " + "b " **Example 2:** **Input:** s = "leetcode ", k = 3 **Output:** false **Explanation:** It is impossible to construct 3 palindromes using all the characters of s. **Example 3:** **Input:** s = "true ", k = 4 **Output:** true **Explanation:** The only possible solution is to put each character in a separate string. **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters. * `1 <= k <= 105`
It's straightforward to check if A or B won or not, check for each row/column/diag if all the three are the same. Then if no one wins, the game is a draw iff the board is full, i.e. moves.length = 9 otherwise is pending.
Array,Hash Table,Matrix,Simulation
Easy
null
258
hello everybody it's neodris here and welcome to my channel today's video we're gonna do the add digits lead code problem so as you can see it's a really simple problem this is a really beginner friendly video so we have a given integer none so repeatedly at all its digits until the result has only one digit and return so for example if we have 38 gonna do three plus eight so it's just gonna be eleven then we store that 11. and we do one plus one which is a two so then since it's only one digit we're gonna stop and return this digit so how are we gonna do this so there are two methods one is a Brute Force like approach I like to call it brute force to be honest since it involves a lot while Luke and the other one is going to be I'm gonna explain it later so let's start with this first approach to understand properly of the problem so we're gonna have a temporary variable we're gonna store Net Zero okay so we're gonna have a while loop so just to explain to you while true okay so while true so I just want to keep looping you know infinitely for as if the number is too big it's not really infinite but uh just to explain like this is very it's a very simple problem but I'm really gonna explain it well so we have the stamp we're gonna start at what I'm gonna do plus equal to the number module 10 why because 38 multiple 10 is 8 so I'm gonna store eight now then I'm gonna have floor app I'm gonna like wanna divide 38 by 10 which is going to be 3.8 but I do not want going to be 3.8 but I do not want going to be 3.8 but I do not want 3.8 okay so we got 38 3.8 okay so we got 38 3.8 okay so we got 38 or modulo 10. which is eight and then in the next iteration not the next item I'm gonna in the same like iteration of the loop I want to do divided by 10 which is 3.8 and I don't want that eight which is 3.8 and I don't want that eight which is 3.8 and I don't want that eight so I'm gonna do what I'm either gonna do int of that variable for example let's say Norm I'm going to say num equals to this okay so num equals to this so I'm either gonna do that the Instinct like it's num or I'm gonna do this so double divide this symbol here is because I like to call it double divide this sum of symbol means that we're gonna floor this so it's gonna be floored to the lowest integer which is three so yeah that's about it so it's really simple so I'm gonna do this instead so I'm gonna say you can do this if you want divided by 10 hopefully not wrong here and yeah that's about it so yeah we're gonna keep looping and looping but the issue here is going to keep looping infinitely so what we want to do is what if this number so it's going to reach 0 at some point okay when it reaches zero here for example I'm Gonna Keep dividing this and dividing this by 10 until iteration zero because three divided by ten and your floor it is zero so if number equals if this num equals to zero so we're gonna do what I want to assign to it this variable 11 for example so I want to assign to it this newly variable okay which is what which is uh temp okay yeah it's time so temp is going to keep adding this will be for example three then again if they're going to loop again it's the three point plus eight then it's going to assign to a temp and within one I don't want to like keep zero here then I'm going to assign to num 0. so I want to restart again from scratch oops it's step by thing that equals zero no yeah it's 10 that equals zero sorry so I want to reset temp so I don't want to keep 11 in it so num is going to be 11 now okay so the new number is going to be 11. it's like you're going to say okay I got rid of 38 and the new input is 11. so this is just a simple explanation it's good A bit long I know it's a bit longer it's a really simple problem so we're going to remove this but it's really beginner friendly so yeah so now what we got a little problem here so it's going to keep looping infinitely so if so I didn't need uh I have to add a number condition for example when we divide uh this 11 and we find zero over like this one and we find zero focus and let's say there's nothing else to divide if the number not the number sorry if the temp variable so if the new obtained variable is lesser than 9 I want to break that's it I want to leave the everything and break so that's about it so here I'm going to have return of course the num sorry not the num return temp I'll always keep doing this yeah so we'll return temps it's number DN I think it's going to be zero why would I return it all right so submit it's going to be slow in Python so this is just to understand the problem really how this works just read the code well you know okay what is going on here oh I forgot something sorry so yeah if temper if temp is less or equal to nine as you can see it's really slow yeah it's like 44 milliseconds uh even like I don't know like the best I got in Python was the 30 milliseconds so let's go to C and have a better solution so yeah this is a better solution for example but this is really beginner friendly okay I keep saying this again who cares okay so not the solutions I want you to see the discussions if there was an explanation here for example as you can see there is a pattern in this problem okay let me see I think the solution should show that better is it this so there's a pattern that I'm going to show you not this okay let's see I think this guy here showed that well where's that pattern okay this is the pattern oh that's not okay it's wasting my time where is this pattern okay who cares let's just read the discussion so for example when one equals to one and two like when one so the LA like the digits is going to be one if we have two then two so as you can see that the resulting case for example is always going to be from one to nine for example we have eleven so we have one plus two one plus three one plus four as you can see it's always gonna be nine then again it's the same thing for every digit it's always going to alternate like whenever you add like the two sides this is always going to be like it's always going to be from one to nine for example 31 32 okay gonna have like uh hold on 31 is gonna be like four one plus four right 32 this will be three plus that and you're gonna have 33 6 I'm gonna have 35 again 39 it's 12. okay then 12 what we have 12 years three so the approach here is to do what so we have like this we have this little formula here when I know for beginners this is going to be seem weird I understand but what this means just let me get rid of this go-to just to explain of this go-to just to explain of this go-to just to explain so what this means is let's go back to python let's get rid of all what we did so for example when I say Nam let's just print it okay print I'm gonna turn zero I know it's going to be false let's just print uh no more uh module 9. just to start from the base case just to explain to you this pattern so it's gonna be two okay which is right which is the answer that we want so 38 formula 9 is 2. so whenever you do modulo nine for this it's gonna give you back like the remainder of when we divide by nine 38 or is that okay 38 divided by 9 is 4.2 or is that okay 38 divided by 9 is 4.2 or is that okay 38 divided by 9 is 4.2 so it's going to give you the remainder of which one will what we want like the remainder of the division like we're gonna say yeah that's about it so you have 11 module 9 let's say print 11 model 9. yeah it's gonna be like one plus the output is going to be two okay so it's always going to be for example 99 okay 99 what is it I think it's gonna be zero here I don't know yeah it's gonna be zero as you can see why so this is the exception case what we want to do here is for example 99 minus one is going to be the value of the previous one which is 98 which is going to be eight and we do what so I want nine so we know that this is gonna like we know that 99 you keep like you do nine plus nine it's eighteen then one plus eight is nine we know that the result is going to be nine so we do just plus one and that's it we've got the value so I know it's not correct for this since we had to so yeah as you can see it's not so what we want to do is return num minus one more level nine plus one so yeah let's do this hold on like that and there we go I don't uh if there is an issue you just kind of have a look output is 9 as you can see but expected is zero so let's just add a like a base case if equals to zero return zero okay yep so as you can see it's still slowing this what if we do the same in C but it takes less memory though return none okay so this is C and we're gonna have here like if you know so C is a bit different Norm equals to zero to return zero that's it so that's C so this is my first video I hope it's been informative Okay C is always bugging this editor here I don't know why it keeps telling me like I don't know if they added as you can see they hear zero milliseconds hopefully it's clear guys streamline so it's from zero to three like the worst case is pretty much seconds and see so I just want to show you the table because I really cannot explain it like by words like I need to just to show you a solution I think it's this one as you can see like the result from one to nine is of course one nine four so for every single digit like the result will be this then four from 10 to 18 and again it's going to be the same pattern as you can see like it's the formula that we did okay it's always gonna work and even for like numb like for so this is what we did pretty much it's just a mathematical formula that works with since we have a pattern that always a piece always repeats okay a hundred is one uh like 111 divided by nine it's gonna be three the remainder is going to be three a hundred and a let's say a 2699 divided by nine is going to be eight or nine I don't know like this is just the calculator I have next to me so let's just try this out let's print this oh I'm gonna use Python I prefer the print function from python let's say let's print okay we're gonna say 2 699 minus one Motorola nine plus one it's either gonna be eight or nine it's eight yeah it's eight so yeah hopefully this video was informative guys I hope you understood everything I mean people know probably gonna understand this in a heartbeat people who are beginners are gonna struggle they're gonna understand there's gonna be a piece of hateful and this problem is a piece of cake I just over complicated things explaining the stuff in detail so yeah hopefully it's good and see you next time the next video is going to be about dynamic programming probably or something simpler I don't know but it's going to be much more complicated than this so yeah stay tuned for the future content guys see you next time
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
1,844
hey everybody this is larry this is me going with q1 of the leeco uh by weekly contest 51 replace all digits of characters so this one i thought was a straightforward um followed instruction bomb to be honest so hit the like button hit the subscribe and join me in discord and yeah uh this is the way that i did in python i just literally did what they told you which is that for odd indexes i it's a number so i look at it as an int and then i just offset it's a little bit awkward to do in python versus c or c plus or even java because you could just do a character offset but this will be fast enough so yeah let me know what you think this is if you want to roughly say uh this is going to be o of n-ish different how you want to define n-ish different how you want to define n-ish different how you want to define all these concating and creating new strings but uh but with s of length is less than 100 you know it's going to be good enough so yeah um yeah feel free to watch me solve it live during the contest next what so what oh you gotta be kidding me um oops ah pay to win that looks very right uh yeah thanks for watching hit the like button is a subscriber and drama and discord let me know what you think about today's apartment contest and so forth and whatever uh i will see y'all later bye take care of yourself stay good stay healthy and to good mental health bye
Replace All Digits with Characters
maximum-number-of-balls-in-a-box
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`. For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`. Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`. **Example 1:** **Input:** s = "a1c1e1 " **Output:** "abcdef " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('c',1) = 'd' - s\[5\] -> shift('e',1) = 'f' **Example 2:** **Input:** s = "a1b2c3d4e " **Output:** "abbdcfdhe " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('b',2) = 'd' - s\[5\] -> shift('c',3) = 'f' - s\[7\] -> shift('d',4) = 'h' **Constraints:** * `1 <= s.length <= 100` * `s` consists only of lowercase English letters and digits. * `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`.
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
Hash Table,Math,Counting
Easy
null
278
number 278 first bad person so what are we given is an integer n which means that there are n number of persons starting from 1 to n and we need to find a person which is bad I mean like which I mean that the version the first person which is bad because every person after the bad person is going to be bad so suppose uh in this example n equals to five and the pad first one so the person start from two three four and five so these are the persons and suppose the first bad person is four now we have to find this so we are given a function um function is bad version which will give show us that if this is a bad person or not now we uh we know if four is bad then 5 will also be bad because every person after the bad person is bad but we have to find the first bad person so how can we do that we could actually use binary search for this one so we start from the left pointer and a right pointer and we find our middle value so this is the middle value and we know this is not a bad person so we increment our left pointer to mid plus one which is this one and then our middle value also becomes equals to four and now we know this is um a bad person but again we know this could be any bad person inside right so we just decrease uh our right pointer which becomes equals to m and now left is not less than right so we return our value so let's just write the code let um left because we are starting from index from one because we're not looking for index we are actually um it's uh it's just like in m while left is left and right chemicals to cars left plus right divide by two and then um if it's bad person right equals to m L's left equals two M plus one return are so why are we actually doing only a m for R and M plus 1 4. uh left so it's because we actually need I need to find the version which is bad now suppose we had here one more blue six and suppose uh four was a bad person and six is not a bad person so 64 is a bad person so we start from here and our right is this and now I'm left our middle value is this now we increment our right to four and now our right is five and our male value is six which is a bad version and since it is a bad version we change our right to M so this becomes our right now and now our mail value becomes this much and we know that 4 is not a bad version so we increment left by one just by intuition you can see that if we need our we need to return our pad version we need a bad person so if we do R equals to M minus 1 actually R could be pointing to the version which is bad and if we did M minus 1 then we came to a prison which is not bad and now we don't have any way to go here so we are just returning something um we won't get our answers so that's why we are doing R only equals to M and left equals to M plus 1 because if m is not the bad version then of course bad Frozen could be starting from either M plus 1 or anything beyond that so that's why M plus 1 for left so let's run our code okay so something is wrong here I need to pass parametry since this is a binary search the time complexity of log n
First Bad Version
first-bad-version
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have `n` versions `[1, 2, ..., n]` and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API `bool isBadVersion(version)` which returns whether `version` is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. **Example 1:** **Input:** n = 5, bad = 4 **Output:** 4 **Explanation:** call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version. **Example 2:** **Input:** n = 1, bad = 1 **Output:** 1 **Constraints:** * `1 <= bad <= n <= 231 - 1`
null
Binary Search,Interactive
Easy
34,35,374
1,846
uh hi everyone I think we should be live can let me know if you can hear me uh hi everyone I think we should be live can let me know okay cool so let's get started so this was the question of today uh quite honestly uh yes it was a medium question but uh it required some amount of thinking uh so I would grade it as a good question okay uh yeah so let's read it says that uh we are given an array of positive integers as input that is what we have here okay this Vector of integers now we have to perform some operations possibly none possibly no operations on this array so that it satisfies following conditions okay now what are the conditions so basically see uh we want to do some operations on this array so that the result uh the resultant array uh has certain properties okay now uh what those properties should be the first property is that the value of the first element in Array must be one so after all those operations are done the first element must be 1 okay the next thing is that the absolute difference between any two adjacent elements must be less than or equal to 1 okay so uh I believe you understand the meaning of adjacent elements adjacent means left and right which is index I and index I plus one or index I and index I minus one so what we want is that the absolute difference between the adjacent elements must be less than or equal to one which means let's say we have an array and let's say there is some element over here called as seven okay if there is an element over here seven then can you tell me how many choices do we have for an element towards the left I mean how many Poss possible values uh can be there in the left element and what those possible values are yeah so if you look at it I can have a six but I can also have a seven right and can I have an eight yes because I want to have an element whose absolute difference with this is smaller than or equal to zero so if it can be zero that means I can have 7 also and if it can be 1 that means I can have 7 - 1 which is 6 and I means I can have 7 - 1 which is 6 and I means I can have 7 - 1 which is 6 and I can also have 7 + 1 which is 8 because can also have 7 + 1 which is 8 because can also have 7 + 1 which is 8 because the absolute difference with both of them is one only all right okay now uh this property should be true for all the adjacent pairs so the element towards the left side of eight should also be either 8 or it should be 8 - 1 or 8 + 1 either 8 or it should be 8 - 1 or 8 + 1 either 8 or it should be 8 - 1 or 8 + 1 similarly the element towards the right side of s can be 7 or 7 - 1 or 7 + 1 side of s can be 7 or 7 - 1 or 7 + 1 side of s can be 7 or 7 - 1 or 7 + 1 okay so these are the properties that we want in the resultant array so what are the properties the first element should strictly be one you have no other option and the second property is this which we just discussed now there are two types of operations that can be performed the first operation is we can decrease the value of any element of array to a smaller positive integer so see this is a very important point if there is an element in the array let's say the element is seven then you can pick this element and you can decrease you cannot increase it's to be kept in mind you cannot increase the value of any element so for example I can't convert this s into 8 or 9 or anything but I can definitely decrease it into a smaller positive integer so I can make it equal to 6 or five or four or 1 or three anything which is smaller than seven so this is the first kind of operation that pick a random element and change its value to anything which is smaller than that okay cool the second thing is that you can rearrange the elements of array in any order so if this is the array I can literally rearrange it howsoever I want so you can create any permutation of it okay now the question is we have to return the maximum possible value of an element after performing these operations to satisfy the conditions so it means you'll be given an array and once you have been given this array you have to convert it into an array which obeys these two rules the first element is one and the absolute uh difference between adjacent values is smaller than equal to one after doing that what we want is that uh we want to find that what is the maximum possible value that this array can have all right so for example if you look at this array uh how many operations would you want to do tell me that first how many operations are required to convert it into uh an array with the desired property so you know if I take it and after that I simply arrange it in ascending order if I simply arrange it in ascending order I'll get one triple2 right in this particular case the first element is one so the first rule has already been obeyed now can you check me can you quickly check whether the second rule is already being obeyed or not the second rule here is already being obeyed because for each pair of elements that you consider you can clearly see that the ABS solute difference is smaller than or equal to 1 okay but you know question wants us to find that what is the maximum possible value that we can get right and if you want to find that out let me ask you one simple question can we change the first element no the first element has to be strictly one now if you look at the second element it's a sorted array right if you look at the second element it is one would you want to change it to something smaller than one the answer is no because you can't if you change it to anything smaller than one that is of no use to you want to maximize the possible value and also if you change it to something smaller than one it is going to be zero but only positive integers are allowed right so what we can do is we can let it remain as it is uh we can not increase its value can we increase its value do you have an operation that allows you to increase the value of an element the answer is no you can just decrease so the only option you have is to leave it as it is right now you move on to the next element and you find that herey the absolute difference with this is well within the range now would you want to change it to something would you want to decrease it no because yes you can decrease it to one but that is not going to offer you any benefit right and can you increase it to some value no you can't increase now you go to two you check the absolute difference is the absolute difference well within range yes it is would you want to change it you can just decrease it but you would not want to decrease it there is no use of it similarly here also so it basically means that the maximum possible value that we can get out from here is two and hence the answer should be two only so uh does this point make sense how many of you understand that how two is the answer for this particular input right okay if you take any other example let's say this one let's say you have not looked at the answer can you tell me what will be the answer for this case in fact if I ask you if you have an array of size n let's say you have an array of size n what is the maximum value of answer that you can get the maximum value of the answer that you can get is n because in the worst case what you can do is you can change the first element to one second element to two third element to three 4 5 and the last element to n so the maximum possible value of your answer can be n provided you have n elements right your maximum possible value cannot be n+ 1 or n+2 or anything more because be n+ 1 or n+2 or anything more because be n+ 1 or n+2 or anything more because if you're doing that means you are missing an element and if you're missing an element that means the adjacent difference rule is not being obeyed so you know in this case what I can do is I can probably first uh rearrange it into ascending order thereby we get something like this 100,000 and after that we can this 100,000 and after that we can this 100,000 and after that we can change this element to two which we can right uh and after that we can change this element to three why I could change because the value over here was greater and I was allowed to decrease so I was able to decrease it similarly the value over here was th000 and I could well decrease it to three I could not change it to something like five because if I change it to five the absolute difference rule would be Dishonored okay I believe now everyone is clear with uh the question you guys can just type in a yes if now the question makes sense to all because I encountered a lot of people who told me that they were unable to understand what the question was really expecting okay great then so then how to go about it let me ask you a very simple question let's say you already have an array which honors this second rule which says that the absolute difference should be smaller than equal to 1 now if I arrange it in ascending order will that ascending order also honor that rule can I say that yes or no the answer is yes and why the answer is yes Common Sense see the reason is uh um let's say there was some array it contained some elements inside it I don't know what and those elements honored the absolute difference Val rule okay now when you went ahead and uh sorted it and after sorting you got a permutation of it now tell me one thing is it possible that in this array you have an element seven but you do not have an element which is six or let me take it in different manner let's say you have an element seven and after seven you directly have nine is it possible the answer is no it is not possible why it is not possible because if you have seven if you have nine then it is guaranteed that let's say if that if there was a nine over here before that towards its left there must have been an eight or towards its right there must have been an eight correct if that was not the case if let's say you just had uh a seven towards the right and another 9 towards the left then here the absolute difference rule is obeyed but here the absolute difference rule is not at all obeyed correct so it means that there must have been and 8 towards its right so it means that if we have an element called as X then x + 2 cannot exist if x + 1 is X then x + 2 cannot exist if x + 1 is X then x + 2 cannot exist if x + 1 is not there right and uh I think with this Clarity I can say that if we arrange it in ascending order then that ascending order would also follow the absolute value rule you can take any other example and you can check that out uh let's say you take one two and then let's say you have one and then again two then you have three then you have four and then again you have three again you have four if you were to arrange it in ascending order uh it is guaranteed that ascending order would also have this particular rule because you can see that uh if you have an element X which is two and you have an element x + 2 which is 4 and you have an element x + 2 which is 4 and you have an element x + 2 which is 4 then x + 1 is also there so that will then x + 1 is also there so that will then x + 1 is also there so that will not be skipped this is a very important point to understand uh is it making sense that the ascending order will also hold this property if the original array had already held this property it's important to understand this point can we count the number of unique elements in Array what's the logic behind that's the important thing but yeah I'm asking this question again does this point make sense that if an array holds this property then its ascending order its ascending permutation will also hold this property yeah okay so you know what I'm going to do is I'm going to first arrange my input in ascending order because we all know that arranging it in ascending order that is the first operation that we will do and you know if at all the original array had that property then um that is going to get reflected in the new array also right so uh so that's not much of a big deal now why we are arranging it in ascending order because that will help us change the elements correctly because if you have a random array you will have to find out what is the smallest element if you sort you know that the smallest element is array of Z now if array of Z is not one you have to make it equal to one because that is the requirement of the question the first element should be one now make it equal to one and after that we have initialized a value result which is one because the largest element so far we have seen is AR Zer which is one and now as I told you one by one we start from index one and we check the difference between current and the previous element and if this that difference is greater than one what should we do just think about that so let's say you ended up getting an array where you have 1 comma 5 it's in ascending order five obviously is uh not having an absolute difference uh within limit with this one so what would you want to do you want to leave this five as it is no it would be a stupid thing to do so you would want to change it now what is it that you would want to change it into you have three options you can either make it 1 - one or 1 + 1 the either make it 1 - one or 1 + 1 the either make it 1 - one or 1 + 1 the better choice is to make it 1 + 1 which better choice is to make it 1 + 1 which better choice is to make it 1 + 1 which is two and I'll tell you why the reason behind that is that this element was greater than that and moreover this array is in ascending order so whatever your next element will be that will be even greater right so that will be either greater than five or you know that would be uh equal to five so let's say instead of five it was three all right and let's say after this three again you had a three here now in this case if you change this three to one then that's not a good choice because if you do that in that case you will have to probably do a change here again because if this is one this is three that's not uh the uh allowed difference the allowed difference limit but if you rather change it into the highest possible value which is two then the chances of having absolute difference within the range is greater so what we will do is instead of changing this element to uh you know minus one of this or equal to this I will change it into plus one of this because if I change it into plus one of this uh What will what will happen at as a consequence of that is that I'll not have to you know reduce the next element that I have otherwise I'll have to take that call of reducing that also and if you go on reducing the elements the maximum answer that you can have that will not be the most optimal one does that make sense how many of you understand this point yeah so that being the reason what we going to do is if we find that the ab the difference is beyond the limit we are going to change our current element to previous element + to previous element + to previous element + one we could also have changed it to the previous element itself for uh previous element minus one but we have decided to do a plus one here because that is the most optimal thing and it's like a greedy choice I would say you know greedy algorithms and why this greed is Justified we just understood because the elements that are going to come are going to be greater only because you sorted the right and now this is just a one liner where you are checking if your current element is greater than the result you're just updating the result and then finally you are returning the result so that's it so if you look at it I just had to sort the array which took us n log in time and this Loop this entire Loop anyways Works in order of end time so this is n login this is order of n overall the complexities and login and that's what you have right okay great so that's it that was all about this question it was not any standard question or something but it certainly was something which required you to think now a lot of people got correct answer for this but you know uh when asked they might not be able to justify these important to explain the correctness of whatever you have done why you have done right here we understand why we have chosen to do something like this we also understood why we sorted the array because we all know that uh nothing is going to change if the original array had that property the sorted array will also have that property and sorting the array ensures that we are able to pick and change the elements much more comfortably as simple as that can you solve n you mean to say Can You Solve in order n do you have a solution of order n anyone who has an order n based solution here without using extra space I thought of one did you submit it where uses space so you might be using some hashmap or something like that to store the elements right okay yeah so what's the solution what's the order and solution anyone who has got an order in solution we can discuss it if you have any count sort what is the range of elements oh the range of element is in between 1 to 10^ between 1 to 10^ between 1 to 10^ 9 did you see that what is the complexity of count sort is Count sort always order n is it always linear those of you who know who have studied count sort can answer that is it always linear time or does the time complexity depend upon the variance of elements depends upon that right so I'm not sure how you're willing to use count sort cannot think about edge cases submit it no submit it once and after submitting what you can do is you can comment your logic in the chat below it I can take a look at it and then probably I can suggest whether that's right or on yeah so if you have any solution which you feel can work in order end time uh always order end time then comment it and we can discuss more about it yeah cool then so let's do that there I think that's all for today I don't have anything else to talk about in this question let's probably meet again the next day and discuss the question yeah okay
Maximum Element After Decreasing and Rearranging
maximum-element-after-decreasing-and-rearranging
You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions: * The value of the **first** element in `arr` must be `1`. * The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`. There are 2 types of operations that you can perform any number of times: * **Decrease** the value of any element of `arr` to a **smaller positive integer**. * **Rearrange** the elements of `arr` to be in any order. Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_. **Example 1:** **Input:** arr = \[2,2,1,2,1\] **Output:** 2 **Explanation:** We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`. The largest element in `arr` is 2. **Example 2:** **Input:** arr = \[100,1,1000\] **Output:** 3 **Explanation:** One possible way to satisfy the conditions is by doing the following: 1. Rearrange `arr` so it becomes `[1,100,1000]`. 2. Decrease the value of the second element to 2. 3. Decrease the value of the third element to 3. Now `arr = [1,2,3], which` satisfies the conditions. The largest element in `arr is 3.` **Example 3:** **Input:** arr = \[1,2,3,4,5\] **Output:** 5 **Explanation:** The array already satisfies the conditions, and the largest element is 5. **Constraints:** * `1 <= arr.length <= 105` * `1 <= arr[i] <= 109`
null
null
Medium
null
943
hey everybody this is larry this is day 23 of the may league daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's forum i have some allergy stuff so if i'm talking really um well it's just allergies i apologize i am recording this live so if it's a little bit slow uh fast forward to watching 2x or whatever you need to do uh and today's problem is find the shortest super hey yeah so i cut in here to kind of go over the solution because this video was very long um you could still watch me stop this live afterwards but um but i just wanted to put the explanation in the beginning because this is a long video let me know what you think about this pattern um yeah so first of all what i first did was i filtered the list um there's a lot of greedy things that i'm doing here some of which i actually talk about if you watch me sub it live but i remove words that are quite dominated by other words and what i mean by that is that if a word fits totally in a in another word then you know um then you know it's gonna be inside that word for the entire time so it doesn't need to you know go in anywhere um so i just have this and i filter those out right because if it's inside another word that means that the bigger words answer is gonna use it anyway uh and then here i calculate the overlap um the maximum overlap um yeah i just calculated the overlap and the longest overlap that uh which after put it appending words j after words i this is i spend a lot of time here actually but hopefully this makes sense you just calculate the overlap in the number of characters um and then here is the tough part this is the bit mask part this is dynamic programming um i also go over the big mask part a little bit in the video so you can go skip ahead a little bit but basically we use bit mask like um like a boolean vector of 12 elements because n is 12 so yeah so this is the boolean element because you can think about mask as a binary number that has ones and zeros where one means index uh this index is usable and zero means that we already used it um in this case it means that the silver item we already do uh we can use it and this first item well yeah the first item uh we already used it so you cannot use it um and the rest kind of follows i'm not gonna go with that deeply because um that's not the point of this video sometimes i go over it but today i'm really tired um if you really like a big mask video let me know i think i've done it before but um i don't know let me know anyway so yeah and basically this function asked to get the best word where the previous verdict is um word sub i uh or good versus and mask is the items that you know the boolean table that we talked about um and then we kind of check if we use all the words then the last word um yeah then the last word we use all of the last word because there's no more words to overlap otherwise we see if it's in the cache we return the cache um we also kind of um you know store the word here um and then here we just kind of keep going uh we have send no values but we basically go okay if i add the word j to the current i what would be the what word would we get so we basically do that we look at the overlap we get the subset and this is recursive we get the current word which is the current word plus the step that is added on which is this part and then if it is the shortest length we update our shortest answer and that's pretty much it um i also do a trick where i append good an empty string to word so then it saves me writing something outside the loop because now we just start from that empty string and then go all the way in um doesn't change the complexity uh but yeah so what is the complexity well i is just an index so it goes from 0 to n so this is o n mass goes from zero to two to the n so this is o of two to the n tangent two to the n minus one um so then the total time is equal to our total um number of inputs is equal to o of n times two to the n and of course for each core um this does for each input this does o of n work because note the fall appear so the total time oops total time is o of n's square 2 to the n roughly speaking uh yeah and that's pretty much it so the spaces is all of you could say you know it's the number of inputs times the number of bytes uh that each input so that's gonna be um you know for each word is 20 so we're gonna uh is this times m uh where m is 20 in this case um we technically do a little bit more random space things by allocating stuff but you know for the purpose of you know handwave that's roughly it um that's all i have for this problem uh yeah you could watch me struggle on this problem next i actually for the most part guided quickly um i just kind of have a lot of issues with off by ones and indexes and stuff like that and you could watch me struggle i'm really tired so i'm going to pass out right now so yeah let me know what you think and watch me solve it live next uh and today's problem is find the shortest super string what is so soup about it okay smaller string that contains your string words and substring returns any of them return the smallest ring that's gonna you turn the subject is it in order or no it doesn't have to be in order that is um this is an annoying problem the short answer is that it's going to be some um i mean 12 factorial is a little big but you can actually do it in um can you do a bin mask i don't know let me think about this it is a little bit slow sorry um i really don't have great ideas that on uh brute force in you know and i'm trying to think about what i'm thinking right now is just trying to think about the clever ways to do it in brute force um i mean definitely you can pre-calculate i mean definitely you can pre-calculate i mean definitely you can pre-calculate some of these and but it is still going to be kind of annoying and i don't know if this is one of those silly lego problems where the inputs are just not that interesting so that it allows you to do it that way so i think one thing to note is that the ordering okay i think we i have some ideas about how to make this a little bit smarter the key thing to note i think for this problem is that um if this if these two words don't intersect then the order doesn't matter right so you only care about stuff that intersects and for stuff that intersects trying to think better yeah i think you could just prove first try all of them we have some real like a lot of a's all the strings in the words are unique that makes a little bit easier but yeah i don't know i think there's a lot of some in my head i'm just going for a lot of cases and a lot of them are kind of greedy things that i'm just trying in my head where i'm like okay is it okay to just always extend only extend i guess so because then we can do some uh subset bit mask thing which is three to the 12 in theory and then you know increase 12 is fast enough probably especially if you do some pre-processing especially if you do some pre-processing especially if you do some pre-processing that's half a mil 531 thousand um but that's really high powered that's why i don't want to do it um or like that's a lot of explanation for that one uh so i should be pre-processing 20 uh so i should be pre-processing 20 uh so i should be pre-processing 20 length 20 square maybe it's fine so there's that case and then there's that case okay all right uh let's go through a few cases um i don't even know if this is right but it is still going to be some sort of proof force but a lot of filtering um and the thing that i notice is that you know you can disjoint sets and if you're destroying the sets then you just kind of handle them out outside but then now get remember that you not only return the length you return the string as well so it's a little bit more annoying as well but yeah okay i mean it is what it is let's try to play around with a few things um and now first thing i want to do is just get rid of strings that are inside other strings so that we don't have to consider it because you always just uh you know it gets dominated so you just used a bit longer string right so yeah um yeah good maybe good words as you go to this up for word and words uh let's see for word two inwards uh dominated is equal to force if word is in word two and word is not equal to word two then dominated is equal to true if not dominated then good words append uh word okay so now we have all the words that are not dominated and then now we can uh this is so annoying to code basically what we want to do now is we want to yeah okay let's just do a recursive function uh let's just do um get subset maybe something like that i'm going to use the fit mask here to keep things a little bit easier um to write and you know i'm going to do a two minute thing on bit mask which is that big mask is you know it's going to be um it maps to basically for each of the n words let's say n is zero the link with good words now let's actually set up the how do you do start with yeah there's just so much pre-processing yeah there's just so much pre-processing yeah there's just so much pre-processing and i'm a little bit lazy today i thought i was gonna go to sleep early today but uh okay but yeah basically bit mask what i'm what a big mask is that you know um it has a binary representation of a number represent a binary number and for each of those bits you have either once or zero and a one means that the index i uh is used uh zero this means it's not used or the other way around depending on how we want to do it or can be used um so that's basically the idea is just mapping uh um like uh a vector of booleans basically is what it's doing um and then so that we can do something like cache data um we're going to put it in a dictionary so if mask in cache return cache mask something like that and of course if mass equals zero then we return empty string right do i want to do it this way i don't even know and then after that it just becomes uh a graph problem of like a hemp cycle uh so you have like you take each component and then you get the hemp cycle compo and so of it which is really yucky yeah i mean it is what it is and then i think we also just do it more proof uh more uh which required just more pre-processing like i said just more pre-processing like i said just more pre-processing like i said there's a lot of pre-processing in this there's a lot of pre-processing in this there's a lot of pre-processing in this one i don't even know if this is fast enough but we will see uh and then now we can get basically for each sub component it is um maybe it's fine actually maybe i could do it just another way um yeah okay so then now we calculate the cost yeah i guess this is the length of each word is only up to 20. so that's just to cost is equal to negative one times and for the n and then now you have let's just do for k in range of from one to length of uh link for word sub i so basically what we want is the cost of appending with sub j after word sub i right so that now we do a thing where okay if what's up j starts with the end of it which is word sub i of the last oh i guess just k someone like that then cos of i to j is equal to k and then we break okay i think that's good oh no this has to be good words whoops okay i think now we're good and then now we can just i'm just gonna do them in three to the end one but i think we can actually do it from two to the end so yeah something like this if index is equal to n we return empty string no it's fine no mask is equal to zero then we return empty string um doesn't matter the index doesn't have to be in order that's yeah and then now we try okay i got it so basically now we try okay this gets the best word that starts uh where the last word is index and mask it's still able to be used um contains the items so everybody able to be used okay and now okay so now we do uh for j in range of n we go basically we go from index to j i guess maybe i could just do i in the same thing keep it consistent going back and forth between index 2 and j but maybe inj is more csc yeah if mask under j is you go to um if this is greater than zero meaning that this is a value to be used then we get um yeah um i was going to say so the cost is you go to oops okay c is equal to cos up from i to j so that means that we extend this word by this character by this much so let's say answer is equal to uh some empty vector and then now so then the suffix is going to be get sub mask of j and a mask we flip this so this is what we get so we get the word but then now since this is the cost how do i do the cost so the cost is going to be the length that we extend by so that means that the suffix is going to be something like um length of good words sub j minus c so that's the thing that we're planning on i think just to best le length is you go to um i don't know a billion just keep it small something big i know that's not a billion but um okay if length of current is smaller than best length then best length if you go to length of current and answers you go to current then at the very end we just return the answer yeah and actually we probably want a big number i just say 300 and then whatever something like that and in the beginning we want to try starting from every word so it's going to be for i in range sub n uh get sub set of i to uh one to the j uh one two minus one and i think that's good something like that again we do this best thing for zero 300 answers 100 so then now we get the subset starting from here hmm uh we can also just cheat a little bit and add an extra empty word in the beginning and then start from that one maybe that's a little bit easier um okay let's do that because i'm a little bit lazy today um and then this is going to be just n minus one so let's do n minus one do this and then maybe i don't know if this is quite right but hopefully let's see okay get some mask it's not did i what did i call it get subset why they call it i got some groups that's not good if mask is equal to zero that means that we used all the words oh i do i don't use the words anywhere so i have to figure out how do i incorporate that back in so this is zero this is this how is this let's see if the cause is forever then is that right that seems a little bit awkward though well it's slightly closer than the last engine so we extended by that length so extended by that length and then now i could also use path reconstruction i guess instead of doing it this really funky way yeah i guess usually not usually but in the past i would have done it that way um oh yeah and also this is should be do because maybe it's catching the wrong thing actually also we don't cash so maybe it wasn't cashing the wrong thing uh i mean i think this is going to be roughly the right idea but i'm getting the index is really wrong it's really late at night i am really sleepy but it's gonna be empty stream oh i see nah i know what i was doing because basically if this is these are all used and this is actually just good word subject i mean yeah okay that didn't do anything why not oh fell out well let's see what we're hitting up maybe we're just being silly does seem to hit a lot of things do we ever good to get to the base case we do so well this seems to be working for some definition of working yes okay see current just more debugging stuff this is a hard one i'm just annoying one decode okay what is that number negative one oh this could be whatever whoops so actually otherwise okay as you get the length okay still the wrong answer but maybe hopefully a slightly less wrong answer where's the alex stuff loves the code thing why is it not printing at all c is zero yeah that doesn't make sense it seems like it is doing stuff but not quite enough to stuff i mask this is tiring okay let's get rid of this one for now debugging is tough that's why don't do it just write it correctly the first time uh you'll enjoy it much better okay so we have we go start from three so one two because the three is the empty string fifteen and then that goes two oh this is wrong because i want because it was adding itself which is really awkward okay so now three goes to two which is that right four yeah i guess that's right um j and c is it this is 8 going to 2 which is true then why is that not giving me the right answer hmm let's see so this is returning this and then we tick did i mess this up what do i want from this again so if the cost is that much then we want to keep the last c okay maybe because that's the part that extends i think they're the same but at least this is slightly more easy to read but that's odd because for this the cost is eight and but so we want the entire string starting from okay yeah i just messed up the indexes again well this is so silly i mean like for me i am very silly oh i still don't add in the current word so this should be okay i just oh man what a point for it let's try that is way too short i think my c math is still well so if this extends by say three or five then that means that we just want the last we want to skip the first okay actually just this maybe hmm the cost is zero then no because the cost is one then you're actually that means that the overlap is all except for the last one string right yeah i don't know why this is wrong then um so this is the c is the so the last eight characters what am i doing here is that off by one yeah why is the last eight characters not right like if this is r and this is negative eight is that not right or am i just off five one yeah i just have a five one hmm nope all right it's not only that now we're still not printing it because current is now this what am i trying to do here what are my indexes why am i so bad at a string indexes it's always really bad for me uh to be honest because r is the code in this case so we want the last eight characters is this not right am i just am i do i not know how to do it now it goes to all the characters until did i mess it up again uh sorry friends i'm really bad at this clearly okay that's what i meant the last eight characters because mixing indexes and everything i think i keep on mixing them okay but it's still well and that's fine or at least slightly more fine but why now why am i only returning five into crosses now because if the cost is four then we just want to skip the first length of good words it should be sub j not sub r that's why and so we want to skip the first c characters and this is why it's important to get enough sleep so okay so at least this one's good uh let's see why this is not good this clearly does not contain all the strings but so this is the end state five three is this length or which are pretty bad hmm so that's probably right so this is okay so it goes from five to two did i do it backwards maybe i recurse backwards by accident is that true no it should be okay um okay so it thinks that this is the answer because it goes to two and 2 is 4 so it's this one so it should save this as the answer but somehow we're only getting this is that right hmm i mess up the best lengthy hmm oh my i am so tired all these are really short and i don't know why up so if this starts of the first k characters then the cause is not k the this is actually the pref uh the overlap not the cost that's why i got it confused okay let's then in this case if this is the overlap then we can um ignore the first c on this character okay still wrong but let's add some debugging i hope this doesn't just print list okay these are the choices that we're given how did that happen didn't it work for a second or like at some sort of answer even if not the correct one so the overlap is see because this is overlap correct if it starts with last one character then overlap is one number that's fine that's not the maximum overlap this is really weird though what overlap is going to be zero oh yeah in this case the default overlap is zero okay still wrong but at least we kind of have an idea so these are our choices that's fine we chose this one let's trace it to here we have these choices let's even print out add a little bit more debugging i'm passing out okay so it goes to zero so it's using this one is this one because it goes to two but why okay maybe that's fine no what is oops serious cat g and two touchy two is 2 is g8cta that's fine let's see if i cut it off anything by accident um wait this is zero that means that it flips off the one button it should be zero comma thirty so actually distribute this one hm let's return this stuff so why is this so weird this is what it returns why is this looking why does this look like that huh this is also the sad thing is that this is not really that interesting of a problem i'm just really struggling with it so this is the suffix because this is the over because we think that gc t is to overlap but this isn't gct doesn't even appear here at all so because the current zero is cat g we think has three overlap of gc t that doesn't make sense and this word starts with then i mix up the json eyes why is this so weird why is my overlap so weird because there's a lot of zeros well that's expected but from zero to two as three overlap which we know is not true because from zero to two there is one overlap why do i never type them somewhere uh i mean this is clearly not right j so if it starts with this no that's right that should be one right why does it return through it why is why are you doing am i just fake why is this drewy so what am i saying so if it starts with where's k is true ks3 means that okay so do it overlap isn't k is it no because if k is one then the overlap is from yeah okay i think i mixed that up again so this is actually length of good words i minus k uh silly mistakes okay oh why am i so really bad right now uh my excuse is that it is four a.m in the morning and i need to four a.m in the morning and i need to four a.m in the morning and i need to pass out but okay this looks good actually exact same answer which is actually surprising because there could be multiple answers uh with my other print statements over i'm gonna give it a submit well as soon as my thing works is my internet i was down earlier okay internet seems okay by me but this problem kind of disappeared oh no there it is okay um yeah let's give it a submit i think i clicked on it but okay there we go i actually could done it ah i was really hoping because i don't want to spend more time debugging but let's see why do i have this long thing hmm okay let me put these test cases somewhere before i lose them i guess that's just the input it's just frustrating to fresh reading okay so the extra ladder is yeah so that's the extra ladder between okay right i only get to choose between these things and not this one do i have this as an answer anywhere nope why not so we want to go to two first but the thing is that this is the shortest word why what's the it sorry gang this is pretty long i need sleep maybe that's why that's my excuse i'm sticking to it but okay so things two should be first and two has these things right so is this word plus this word which the overlap or the extra part is this part which is not true i think seems like i'm off by at least one see now this part is the part that we want to add this is the whole world okay so should have been better about debugging accepting in the morning maybe i would have been better okay so now we want to look at the first so this is the first one this is the current word we somehow think that this is the part to add on to it so that's why we have this but why what is let's see so the overlap is one between here uh between word two and zero is that true with two and zero should have two overlap but i only wrote one overlap am i off by one um okay because i want the maximum of this but before i had it flipped around so okay oh geez this is so annoying i had the right idea actually the entire time but it didn't really help okay so let me paste back their stuff okay actually i guess we might be using the same album but anyway let's click on submit okay um yeah i'm not gonna explain it uh again because this video has gone on for long enough that i probably or i explained it in the beginning and we recorded it so yeah i'm tired right now if you're still watching you could see the tiredness in my eyes and i'm gonna go right to sleep uh hit the like button hit the subscribe button join me on discord thanks for watching this late if you're still here um yeah hopefully next week will be better and i'll see you tomorrow 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
733
hey what's up guys think about here I detect growing stuff on twitch and YouTube check the description for all my information I do the premium leak Oh problems on my patreon join the disk or message me I try and get back to everyone as an easy problem called flood fill pretty cool 733 a lot of likes and image is represented by a 2d array of integers each integer representing the pixel of an image from 0 to 65,535 so we pixel of an image from 0 to 65,535 so we pixel of an image from 0 to 65,535 so we got a 2d array of a bunch of pixels and it represents an image given a coordinates srs C representing the starting pixel row and column so row and column of the starting pixel of the flood fill in a pixel value new color flood fill the image so we want a flood fill an image for a from a starting pixel to perform a flood fill consider the starting pixel plus any pixels connected for directionally to the starting pixel of the same color as the starting pixel ok so that's important same color the starting pixel plus any pixels connected for directionally to those pixels also with the same color is the starting pixel and so on replace the color of all after mentioned pixels with the new color at the end returned the modified image ok great instantly this reminds me of a number of islands if you guys saw that if you didn't maybe check that out but it's an easier version of it actually so maybe watch this one first but let's just go through an example so this is all our inputs is a lot we got a lot of inputs here right we're given an image is a 2d array and I like to look at 2d arrays like this I think it just looks a lot cleaner when you look at it look kind of like a square you know you could visualize a little bit better maybe use that as a strategy and our output looks like this so let's also get that right so how do we get from here to here right we have a starting pixel which is 1 position 1 so 0 throw 1 row and then first column 0 column 1 column so this is where we're starting at 1 and we're wanting to make the you integers represent colors in this so we want to make the color turn from the color right now is one we want to turn the color to it too so we would what we do is we start at the starting pixel and we change it to a two and then we change all of the colors that are equal remember same color as the starting pixel for directionally two twos so we started out we started here this is our input we see the starting we're starting column is one so if you know indices of 2d arrays zero Row 1 row 0 column 1 column turn that to a 2 now for directionally anything that was a 1 because 1 is the starting color you can change to a 2 so you could change its up left right and down these are zeros these are not the same is the one that was there so you cannot change these two twos so this is a 2 but we can change these once tattoos because they are the same as the starting pixel car well oh yeah we're good to go there 2 now from these you have to change you also change that all the ones that are connecting anything you change you keep going forward erection away from there so we see more ones to the bottom top and then this one to the right boom all of them cuz it's 4 directionally from these so you got the top down and then left right which is already done and then this one you cannot reach this one because there's no way to get there going down into the right this is diagonal so there's no diagonal connection so that's how it ends up like this just in case you guys we're curious about that so what you'll notice is we do need to keep track of what the color was at the beginning so that we only change things or that are the same color as what we had at the beginning as a first strategy to do this we're gonna be using depth-first search where we do be using depth-first search where we do be using depth-first search where we do recursive calls let's just get into the coding right now but we're gonna modularize and make a separate little method here called fill so or you could call yeah let's just call it fill that's pretty good so it's a void method it does nothing fill in this we'll fill a current pixel just one pixel so this will take in the pretty much the same as this like the same parameters except it will also take in the previous color so we can make it'll take in the starting color so we can make sure that we're doing this correctly and we're only changing the starting colors to the new colors so what this will do is it'll say okay though at the current row in column we're just gonna make that equal the new color because it's going to be equal to the old color and we do want to assume that we also will check will be like okay if you know image s R of s C is not equal to color that's bad or the Rho is less than zero so it's out index out of bounds or the column is less than zero so column index out of bounds or you know the index is greater than or equal to image dot length so that's bad too because that's out of bounds because the only index it can go up to is image dot length minus one column is greater than or equal to image of zero dot length so the column index is out of bounds so you check all those and what we'll do is if any of these conditions ring true we'll just return we won't do anything so this method will do nothing if any of these you know errors occur like we're not finding this is the if it's not equal to the starting color why would we change it to the new color like we're not doing that because the starting color is one in this if we found a zero we don't want to change it we just want to return but if the index is in bounds in the color is equal to the starting color we want to change that thing and so yeah in what we want to do is we want to call this method over and over again and we want to call it on you know passing the parameters in image s that row plus one will do actually will do the row before so to the left actually that's to the top row before is to the top I see the same column color and new color and then will repeat this four times because you're going for directions so when you're doing is the row before so the top row after to the bottom same row but now to the left and to the right with the columns so that's a the row before bro after column before column after and then this recursively just calls doing a depth-first search if just calls doing a depth-first search if just calls doing a depth-first search if you guys don't know what depth-first you guys don't know what depth-first you guys don't know what depth-first search is it's you know gonna keep recursively calling until it you know hits this return and then the next line it's you know look of depth-first search you know this look of depth-first search you know this look of depth-first search you know this isn't a depth first search course but it is a great searching algorithm for problems like this is a very common algorithm problem style with 2d arrays there's a lot of questions that involve like depth-first search like this so now like depth-first search like this so now like depth-first search like this so now we just want to call fill so all we want to do here is well first of all if the image of s are of the start if the starting pixel is equal to new color we'll just return the image because it's already done from what we understand why would you they should give us a starting pixel with an original color right then we just have to call the fill method with the exact information the starting image array the 2d array the starting column the starting row and then the color is just going to be whatever the current color is you know the index they gave us it should not be new color so this is the original color so you know you look up that link in this case you know we saw that one we passed that one in we're like okay this is the color and then we have the new color actual parameter and then after that after this gets called it'll do all of this stuff recursively Colin do all of those you know left right top bottom over and over again and then we get our image back we can return it some of the sailing from there until you get an index pounds guys then you're screwed so you know never mind about that where is this what are we doing wrong guys if SC is less than zero SR is less than zero I saw an image dot length that's C greater than or equal to image of zero dot length seems oh yeah you know you gonna do you go check this before sorry check the indexes before cuz you can't do a conditional check you know what I mean we're use it if these are out of bounds it's gonna throw an index out of bounds there you go to put these at the end of your conditions that's actually useful tip to always put a conditional check if you're gonna have to check for index out of bounds things do that before in the conditional check if you're also checking indices right because it'll throw index out of bounds or so that's pretty much it let me know if you guys have any questions on this thank you for watching I appreciate you guys and I will see you in the next video
Flood Fill
flood-fill
An image is represented by an `m x n` integer grid `image` where `image[i][j]` represents the pixel value of the image. You are also given three integers `sr`, `sc`, and `color`. You should perform a **flood fill** on the image starting from the pixel `image[sr][sc]`. To perform a **flood fill**, consider the starting pixel, plus any pixels connected **4-directionally** to the starting pixel of the same color as the starting pixel, plus any pixels connected **4-directionally** to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with `color`. Return _the modified image after performing the flood fill_. **Example 1:** **Input:** image = \[\[1,1,1\],\[1,1,0\],\[1,0,1\]\], sr = 1, sc = 1, color = 2 **Output:** \[\[2,2,2\],\[2,2,0\],\[2,0,1\]\] **Explanation:** From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color. Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel. **Example 2:** **Input:** image = \[\[0,0,0\],\[0,0,0\]\], sr = 0, sc = 0, color = 0 **Output:** \[\[0,0,0\],\[0,0,0\]\] **Explanation:** The starting pixel is already colored 0, so no changes are made to the image. **Constraints:** * `m == image.length` * `n == image[i].length` * `1 <= m, n <= 50` * `0 <= image[i][j], color < 216` * `0 <= sr < m` * `0 <= sc < n`
Write a recursive function that paints the pixel if it's the correct color, then recurses on neighboring pixels.
Array,Depth-First Search,Breadth-First Search,Matrix
Easy
463
63
hello everyone so i am sankalpdhya and a final student of computer science at vrt valor and i solve some questions to help other people so that they can do good in the coding rounds and interviews and get placed very soon so today we have this question that is unique paths part two and yesterday we had solved unique paths part one so the difference is that in that we are given an m cross m n like two values that is m and n which is the dimension of the this grid and we have to find the total number of unique paths now in this question it is the same as the previous one and the only difference is that we can have obstacles in between so if we have obstacles we cannot step on that cell so if we try to read this question it is a robot is located at the top left corner of m crossing grid the robot can only move either down or right at any point in time the robot is trying to ease the bottom right corner of the grid now if we have some obstacles are added to the grid how many unique paths would be there so we can have a basic dp approach in which like a matrix that we have created yesterday that will be of the size of this input and we will have the and each of this cell that is dp of i comma j dp of inj so it will store the total number of possible paths up to that position so if we see here the total number of paths will be the same as we did yesterday that was dp of i minus 1 j plus dp of i minus dp of i com and j minus so it will be the same and we have to do this only if the current value that is in the obstacle grid if the current value that is the obstacle grid i j if it is not equal to 1 then this will be then we will store this value in dpij and else it will be 0 that is dp of ij will be zero now this is because if we are if we see the first example we have one at one comma one and if we try to go there so it is not possible because that is an obstacle so the dp array will be having 0 at this position and otherwise it will be the sum of the top value and the left value so for example if we see the next value that is 0 at 1 comma 2 so it will be the sum of the previous value that the sum of the value at the top and at the left so it will be this will be 1 and this will become 0 because it is an obstacle so this will also be 1 so now we can start coding for this now we will first check if m or n is less than zero then we will simply return zero or if the first value is an obstacle that is we can't start so then also we'll return zero so we can add in this only or obstacle grid of zero is equal to one then also we will return zero now we will store one dp uh 2d matrix so here m will be rows and n columns m is length of this obstacle grid and n is the length of the first row in this obstacle grid so this is the number of rows and n is the number of columns so dp will be initialized with 0 this is n columns and m rows now dp of 0 will be 1 because obstacle grid 0 is 1 as we have confirmed here because it if it will be 1 will return 0 so now it is 0 so at start we will have this value as 1 and now for the first true and first column we will assign one to all of the values until this is one so if it will be one the dp value will be zero so for row and range m so it will be from 1 to m because 0 we have already saved so it will be 1 if the previous value if the current value dp of rho minus 1 and zero okay so this is for the first column so dp of row zero will be the previous value if the current value is not an obstacle and if this is an obstacle the current value that is zero comma zero so this dp value will be zero and we will do the same thing for the first row and here we will check if the current value that is zero comma coal if it is not an obstacle we will assign the previous value in that column and if it is an obstacle you will assign zero now this is for the first two and first column for the other cases now this dp of row and this call so it will be the sum of the value above and on the left and this is only possible if this is not equal to one else it will be 0 now we have filled all the values in this dp matrix and at the end we will have to return the last cell of this dp matrix so it will be m minus 1 n minus 1. sure so okay and there was some variables issue okay and your call will also be from 1 to n okay now we can submit this code ok now for the time and space complexity for this question if we see the time now here we have three for loops so for the first one it is of the order of n the second one is of the order of m because it is from 1 to m and for the first for loop we can see that we have nested for loops the outer one is from 1 to m and the inner one is from 1 to n so the time complexity for this nested for loop will be m into n so the overall time complexity will also be mn so the overall time complexity is mn and if we see the space complexity here these two are constant variables and this is a 2d matrix which we are creating so this is taking m times m n times space and yeah that's all variables that we have declared so the overall space will also be mn okay so that is all for this question and like this was the dp approach that we had solved and if we see the solution we can see that they have also used dp and okay and what they are doing is they are manipulating the input array so in our case we had not changed the values of this input so which is the constraint sometimes but if we are allowed to change this input also then we can do something like this so instead of creating this another dp matrix we can use this input only to change the values and update the values so in this case the time will be same but the space will be constant so we can also see this solution and if we have if we don't have any solution for this question we can check the discussion section so again we can sort it using most uh by most votes and we can open some of the top links so i have opened the foldings like top foldings so this is a java solution and it is using a 1d in like 1d extra uh space so in this also in this way also we can solve this and here we don't have any explanation we just have the code now in this it is a c solution and in this also they have used 1d or 2d vector that is 2d space which will be of mn size so this is the same that we did and if we open this another solution here they have a good explanation so we can follow this and this is a very explanatory solution so if we are not able to understand or solve this question we can check out the solutions and the last is a python solution so it is starting from mn times of space and then it is optimizing to open space and finally it is doing in place that was the solution given so in this way we can see the solutions and we can understand like how the other people are solving this question and then if we are not able to do it on our own we can always take help from these solutions and it is like recommended that don't see the solutions instantly like if we are solving the questions now and if we are not able to solve it so we can have one day break and we can again try tomorrow and if we are not able to solve even tomorrow then we can see the solutions or if like hints are also sometimes given so we can also see the hints if we are not able to solve this question so that's all for this question and thank you for watching the video if you have watched the video till now you can like comment share and subscribe the channel and i'll be up posting videos daily for solving the questions in this dynamic programming section and i'll be sharing my experiences on saturday so just have a wait till then and see you later bye
Unique Paths II
unique-paths-ii
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle. Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The testcases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** 2 **Explanation:** There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right **Example 2:** **Input:** obstacleGrid = \[\[0,1\],\[0,0\]\] **Output:** 1 **Constraints:** * `m == obstacleGrid.length` * `n == obstacleGrid[i].length` * `1 <= m, n <= 100` * `obstacleGrid[i][j]` is `0` or `1`.
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] else obstacleGrid[i,j] = 0 You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem. if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j] else obstacleGrid[i,j] = 0
Array,Dynamic Programming,Matrix
Medium
62,1022
1,436
Hello everyone welcome to my channel code story with mike so today we are going to change the video number of our lead code GG's playlist ok lead code 1436 is easy question but it means this is the test which is done online na i think this type is in hacker rank I have seen this question once long ago, ok, it was not exactly the same question in the online test, I am not able to recall, but it was of this type, so the question is Destination City, it is very simple, actually it says that a path has been given to you. In this each element of the name will have two things One City AI One City BI What it means is that there exists a direct path going from City AI to City BI Return The destination city that is the city without any path out going to another City is fine, meaning you have to find the city from which no outgoing edge is going, meaning it should be the last stop of our journey. It is guaranteed that the graph of the path forms a line without any loop. There is no loop in the graph, there for There will be exactly one destination city and exactly one answer. Like look at this example, if I draw this graph it is saying that B to C is a direct path and D to B is a direct path and C to A. There is also a direct path. Sorry B will be here and a is a direct path from C. So see. There is an outgoing edge from Hodi. There is an outgoing edge from B. There is an outgoing edge from C but there is no outgoing edge from A. This is our destination city. This is our answer. Okay, so this is a very simple approach. You must have already got the approach in your mind. So just to maintain the consistency, today we are making this. Okay, so I made it in two ways. The first way to do this was mine, using hash map. You just have to store this. If there is a node, does it have outgoing degree or not? Okay, so let's say the first edge of mine is this, if it is Bima C, then I have stored in the map what is B has an outgoing edge, so is B, what is B has an outgoing edge, so count according to it, put one in front of it, this is my map, okay, this is my source, it will be string and this is my integer i.e. the value which is That would be one, i.e. the value which is That would be one, i.e. the value which is That would be one, what would be the meaning of one, brother, there is an outgoing edge coming out of it, D, let's come to B, what does this mean, there is an outgoing edge coming out of D, isn't it right, let's come to C, what is the meaning of C? There is an outgoing edge coming out from it. Okay, now look, pay attention. Then we have stored this in the map. Okay, now we have to go in this path again and we have to see like look here, this is BC, it means B is from C, right? Okay, so I see that there is an incoming edge at C, but okay, for now, I will check whether there is any other outgoing edge going from this Do it, yes, I am going, so C is not my destination city. It is possible. Now coming to D, B, D, comma on B, then D is obvious, it cannot be our destination city because outgoing from D is B. Is there any outgoing from B? Yes, look, if it is stored in the map, then this B also cannot be my nation city. Okay, I have removed this also. Now coming here, C is the border on A. Okay, so C anyway cannot be a nation because it is going to be about A. Let's see, A is present in my map, it is not present, what does it mean that there was no outgoing edge from A, so A is our answer, okay, this is very simple approach and our second approach is hash set, okay, this is also very simple. Look, what we have to do is, let's take the same example in the hash set, we will do this like this is the first edge, right, my B is from C, so what I will do is take a set and write in it that brother B is this, right from B. C was there, I will write here that there was an outgoing from B, A, so it cannot be mine, destination D is ok at any cost, now coming here from D to B, so here also I will write that brother D is also there. No, he cannot be my destination city because he has an outgoing judge from D. Then here comes CA. But here I will write that brother C also cannot be my destination city because he has an outgoing judge from him. Okay, so in the set we have them. Wrote people who can never be a destination city. Okay, so we'll go back to our same Hey, what's the first A in the input? B to C. Okay, so I'll see if this C is the first If there is C from B then B can't be there anyway because from B you can see eight but let's see if this C is present in this set of mine. Yes if it is present then it cannot be destination city. Okay so this is his. Which one is after D? Sorry, destination city. Now let's come to the last The answer is ok, it is a very simple approach, we can do the code of both the approaches quickly, ok now you will get the code of both C, P, JAVA, there will be exact similar code, ok and today a very important video is also going to come, weekly contest. The last question of the Sorry bye weekly contest was a good question, it was a very good question, I have also taught a topic related to it, that is why I thought I will make a video on it, so that video will come today. Okay, let's finish coding it. So let's read it. Let's code, first of all let's do approach one. What was in approach one was that unordered map was taken, here was string, here was int, what does int mean, going edge from there is fine, in this let's name it MP for auto. And path in path, okay, here what I am saying is, what is my string source from where the outgoing judge is coming out, what is the path of zero, okay, so I write this, MP of source is equal to two, it is okay. This is what we have set, now let's go back to this path, now look at the string which is the destination, here it is the path of one. Okay, so I will check that if the path of destination is equal to is not equal to two. Isn't that what I mean, what is the ultimate destination, it is ok, simple, return A, here we will return MT last because we will return from here only, just put a statement here, it is ok to return if MP of destination is not equal. This means that it must have been zero for sure, it will not even be present, it is not in our map, let's see by running, indeed yes, after submitting, let's see, we should be able to pass all the cases, after that we will come to the second approach i.e. come to the second approach i.e. come to the second approach i.e. Using hash set is fine then hash set is also very simple. Here I set the unordered set and name it ST. If the set is fine then it is set. What did I say in the set that I will insert it in the set? I will insert it from this source. That brother, there is an outgoing edge from this, okay, from this source, that means it cannot be my destination at all, okay, and here I will take out the destination and here I will check that if ST does not find, this destination is equal and Meaning, this destination is not there in this set in our set, what does it mean that it is sure that there is no fire coming out from it, so this will be our actual definition, okay, let's submit and see, hope fully, we should be able. To pass all the test cases indeed yes there is any doubt raise in the comment section a try to help you out see you in the next video thank you
Destination City
get-watched-videos-by-your-friends
You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._ It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city. **Example 1:** **Input:** paths = \[\[ "London ", "New York "\],\[ "New York ", "Lima "\],\[ "Lima ", "Sao Paulo "\]\] **Output:** "Sao Paulo " **Explanation:** Starting at "London " city you will reach "Sao Paulo " city which is the destination city. Your trip consist of: "London " -> "New York " -> "Lima " -> "Sao Paulo ". **Example 2:** **Input:** paths = \[\[ "B ", "C "\],\[ "D ", "B "\],\[ "C ", "A "\]\] **Output:** "A " **Explanation:** All possible trips are: "D " -> "B " -> "C " -> "A ". "B " -> "C " -> "A ". "C " -> "A ". "A ". Clearly the destination city is "A ". **Example 3:** **Input:** paths = \[\[ "A ", "Z "\]\] **Output:** "Z " **Constraints:** * `1 <= paths.length <= 100` * `paths[i].length == 2` * `1 <= cityAi.length, cityBi.length <= 10` * `cityAi != cityBi` * All strings consist of lowercase and uppercase English letters and the space character.
Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly.
Array,Hash Table,Breadth-First Search,Sorting
Medium
null
319
so the name of the problem is bulb switcher it is a famous bleed code problem so in this problem there are n bulbs that are initially off okay all bulbs are off and in the first round we have to toggle every bulb the meaning of toggle is if the bulb is switched off we have to switch and switch it on and if the bulb is switched on we have to switch it off so in the first round as all balls are switched off now all balls are switched on now in the second round we have to toggle every second ball so like the second bulb is now off similarly the fourth similarly the eight and so on sixth also in the third round we have to toggle every third pull so the third bulb is toggled sixth valve is toggled and so on now we have to tell the number of bulls that are on after end rounds so now let's take an example of a number 12 is not a perfect square number so there are six numbers that can divide twelve completely they are one into twelve two into six three into four so in the first round the twelfth bulb will be toggled because one can divide twelve completely similarly in the second round the twelfth bulb will be toggled again because two can divide twelve completely similarly in the third and the fourth round the twelfth bulb will be toggled since both the numbers can divide 12 completely now in the sixth round the 12th bulb will be toggled again as earlier it was switched off now in the sixth round it will be switched on and lastly in the 12th round it will be switched off again so we can observe that any number which is not a perfect square have even number of device now let's take an example of a number which is a perfect square like 16 there are five numbers that can divide 16 completely 1 into 16 2 into 8 and 4 into 4 so 1 2 4 8 and 16 are 5 numbers and that can divide 16 completely so in the first round 16 bulk will be toggled similarly in the second so in the first it was switched on in the second round it will be switched off in the fourth round it will be switched on again now in the eighth round it will be switched off and in the last round it will be switched on so in this case we can observe that a perfect square number have odd number of divisors so in this question we basically have to find out all the perfect square numbers from 1 to n and that will be our answer now we will quote this question we are given a value n and we have to return an integer value but which will be our answer so we will create a counter and then let's assign it a value 0 now we will run a for loop and check till what values of i equals 0 and i equal less than n i can create a perfect square okay for and i into i less than equals n i plus and inside we will increase the value of our counter let's return it we have to start with one otherwise the answer will not come correct return i hope it is correct let's check so it is the correct code i hope you understand the problem
Bulb Switcher
bulb-switcher
There are `n` bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the `ith` round, you toggle every `i` bulb. For the `nth` round, you only toggle the last bulb. Return _the number of bulbs that are on after `n` rounds_. **Example 1:** **Input:** n = 3 **Output:** 1 **Explanation:** At first, the three bulbs are \[off, off, off\]. After the first round, the three bulbs are \[on, on, on\]. After the second round, the three bulbs are \[on, off, on\]. After the third round, the three bulbs are \[on, off, off\]. So you should return 1 because there is only one bulb is on. **Example 2:** **Input:** n = 0 **Output:** 0 **Example 3:** **Input:** n = 1 **Output:** 1 **Constraints:** * `0 <= n <= 109`
null
Math,Brainteaser
Medium
672,1037,1491
101
Them Box Screen Inside A Well Known As Its Problems Mystery Solved Problems Statement Say Will Help You Identify Weather Give Entries Cement Factory Notes For The Definition Attri Buddhi Symmetric Liberated From Distant Up Sid To V Like She Was Not Difficult To Write Off Laptop Subscribe The Subscribe To If You Have 15x Jam Pal Hai In First Example Rear Seat Symmetry Request Value Conference Novel Straight Skin Care Routine C Day Left Request To Right But Left Of Love Is Not Equal To The Life Of Christ So How Can Solve This Problem Solve 10 Lakhs Mirchi Ek Achhi To Sapno Things Which One Will Return The True When Will Be Chand Laptop [ Laptop [ Laptop Do Do n't forget to subscribe and subscribe to hai to left right yes right quotes for this and electronic function play Million had happened that after shallow frying at this time function on Neem Sangh know what it into it can take care c note in between Lucknow and after doing chants of bayar ho loot gaye loot na ho mein should be successful a r like up som Condition president control whereby ministry for the particular and flight and last not 100 but will connect words left pimple 222 null pinch snowden small and right all sonal so that please like toe tree will return a p don't form many were fact is not for kids will take Another condition of electrical 222 tap and right that request ud that organization this thinking time holidays switch one wire like tap return * Veer subscribe The Channel Please Share Thank you to notice Paltu right value that This Values ​​Are Not Seen Dialogue In that This Values ​​Are Not Seen Dialogue In that This Values ​​Are Not Seen Dialogue In Absolutely Return For Girls Pick Up Valuable But Not Willing To Right Not Valid Synonyms For Kids Will Not Give One Direction Will Function Will Turn Into Fats Subscribe To That Dot Right Similarly Pants Were Water In Card That Without Vibration Left Increase in dot right love oo by issuing notice to call detail ki continue with all the note secretary anil vich for the bottom of all know like them equal and full symmetric pension bill check return ho ki is route ki adwise bana call dushman rudd whatsapp Light loot your all right left right committee favorite evil activate shiv wakt all strive to run this quote ok since working side all this is what networking and good tiffin 300 pages committee so and decentralized medicine cement factory problem issue like subscribe and hua tha
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
231
Hello Everyone Welcome to the Channel Today's Question is the Power of Two YouTube Channel Please subscribe our YouTube Channel and tap on Twitter - 20121 tap on Twitter - 20121 How to Difficult 1622 So Let's Move to See the Question Subscribe Tab Page Number 90 A That Every One of These Is Clear Tour Not As Well As Will Take Away All The Time Of 820 Middling To The Number To 99 To Mute The Model Of Date With Two Model Paper 2000 Dr To 16 To Right Wild West Indies T20 Width Him Introduction 18008 mid-2012 Models For mid-day mid-2012 Models For mid-day mid-2012 Models For mid-day log in the mood me suite to die this 0 I will divide 2523 at diet for election till mode of 121 middle age check is equal to one is doing this middle simple thank you placid 7 models to this notice 20822 and sunilsingh please check The Giver Number 212 A Painful But Will Simply Done For You I Office Problem And Time Complexity Will Be That Uplogin's Wife Buddy-Buddy The Number To Every Time That And Wife Buddy-Buddy The Number To Every Time That And Wife Buddy-Buddy The Number To Every Time That And Spider Man Off But Not Using Any Space But Lassie During This Time They Can Get All Solutions For Fun Time Complexity Of C Ajwain Representation Of Every Number 63 90 Is Video Doctor Numbers Meter For To Taste 248 Ki And Fuc Contact Number Of Bones Ki Harold Is Number Ki This Bar Is Ki 24 Number Contain All In One App To Convert Free Live Web Tools That Hindi Chitthan Ko About The Number Which Is The Power Of Two After This 6 That SSC Tourist Office Se Zameen Chhin 1000 Aage This Number Five One Number Two Single And This Is How To Two 100 116 Syllabus For 6 Class 7 Jai Hind Point Presentation And 600 800 Phone 08082080820 Se They Have No Representation Of 600 800 Se Force Complement 1000 Subscribe To That And Different One Thing The Number Into Its Complement Is That Leader Right Minute To Midnight Most 20 Percent Kota Life Events of the Day The Same Effect On About The Right Mode Switch Of Six Is Dushman Android Most Beneficial 299 Se Video Quite Right 2014 0 To The Right To Complement For The Right To The Number To Take And Definition Of Its Form Into A Fight Between 4 and between the same goes for its effect 16 Feb 11 2012 6 Ki and Pandavas and between the wicket which is not equal to six but the end of for 2nd floor is equal to take a representation of 108 elements of 8086 2108 Subscribe 2018 Subscribe Top 10 Richest Person in His Powers Between the two leaders will be equal to the number of who is the number on this to-do list is the number on this to-do list is the number on this to-do list Put the number difficult to every single one and between the number to the number in their power to do It is equal to - 4 - 24 - This is equal to the number to do It is equal to - 4 - 24 - This is equal to the number to do It is equal to - 4 - 24 - This is equal to the number one and with - This is equal to the number one and with - This is equal to the number one and with - This is equal to the number two How to cut names and decorations with negative numbers To the number one response to the first woman who wants to see what is the number three Layer simply checking for boys with - - 4a and Vishwas the festival in which were sold in the fun time that this look at life from 712 to pure experience in which coffee was the defining test cases for adults Jai Hind time models of two death number So now the number of dividing is two to zinc 210 400. zinc 210 400. zinc 210 400. Tomorrow morning in Rai Summit core key and it's 10 codes for this problem you can find the code description. Thank you for watching my video please don't forget to subscribe.
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,813
Scientist A Hello Hi Guys How Are You I Am To Avoid Doing Good Day So In This Question We Are Going To Do Indescribable Ko Sun Tan Question Is Sentence Similarity Third And You So Before Proceeding If You Are You This Channel Subscribe Please Like Please Comment What You have in this to please comment what you have understood and what you really want from website and also step video office this question of the day for us so let's 30 Android forget to subscribe I am the question and sentences list of world accepted By Single Species With No Leading And Feeling Space What Is Mean By Leading And Feeling Leading His Leading Telling Mystics Have Not In White Se Solidarity Among Ape A Beta Testing And Feelings End Of The Chapter Distance From This Completely With This Complete Springdale Ignoring All Leading His Leading Space For Example Harold Hello One And It's Okay So What Will Have To Find Beau To Sentence Management S2 Assembler Tiffin Only It's Possible To Insert Papi Sentence Insights From This Sentence Back Inside Make Okay 100g Question Porn Want To See The Question Singh that I have a or one sentence of one sentence stomach clear complete spring aaya vashikaran sentence husband saw you have to figure date in the can you able to insert any spring in the mid-day mid-day mid-day that in the middle of sentence mind and sentence to So that drop spring ki Saurabh very speed less equal to that if I speak in Hindi do you what you a string in this manner sentence him any spring between the tests one by one selection string can make record that Tanu make tattoo spring Equal by adding coriander and earth sentence in the middle of any of the a saint of any best thing called sentence man and sentence to example abhishesh this fall good boy I example obscenity horses in a will think in sentences that abhishesh cave people good boy so what are You doing 10mb that can we make any sentence can we get any sentence to spring sentence is one and sentence to shoulder posting begum equally aside can by adding ka single sentence by linkedin ki dasi and 10 math 47 S1 is constrained ar interested in this In this channel stew, the fledglings of knowledge do torch light in English, arrangement of forces by knowledgeable knowledge, knowledgeable and a that I'm so sorry can we make both soldiers, yes by adding, knowledgeable and also knowable, a beautiful vacancy tabs spinner equal to that show the The question is the question is Vastu se can you inside end of the thing can even be able to insert investing in the made of any for the end of the given springs and boosting Vikram equal so let's 250 proceeding I want to give some example you can really get that Difficult Climate And Water Pollution Can Really Impress Me Yadav First Time Italian Most Industry One Of The Best But After Realizing Is Considered One Of Fancy Item Seervi Meaning Test Cases Find Any Selection And This Really Work And Spoil Your Pan Solution Solidification 210 By Becoming Dry Show Me Net Se Mushrik Ki Reddy 89 My Name Is Hai Le Subah Can Insert Name Is The Meaning Of My Lab Assistant Both Speed ​​Come Equal Notification Laut This Spring Is To Insult Speed ​​Come Equal Notification Laut This Spring Is To Insult Speed ​​Come Equal Notification Laut This Spring Is To Insult Before Off And Words Page Setup Per Off On Subscriptions The Innocent Man So They Can Not Make to spin by adding a single sentences and complex sentence in spring ki and deception test one descent S2 both are of length wave big butt juice peeling is difference between 9889 the sentence improve piku make sense st s equal ok but in this point questionable From this band how missing water this case were exact age illicit relationship that and what is to S2 is a part complete ago and one egg love can see no vacancy the issue will do in the first time also you will return the falls in this that by PikkuBoss bhi 282 do the report and is priceless and capital after MBA 282 sentence spacing in se but this is wrong das loot- sentence spacing in se but this is wrong das loot- sentence spacing in se but this is wrong das loot- loot considering the saver mode ka setting etc se ₹100 considers display this is they etc se ₹100 considers display this is they etc se ₹100 considers display this is they consider these as weapons at only this sudhijano difficult But so add small and capital and small and Sudhi Amit will not be split into that a that and if it is so that they want you can do issue add that history in this case history Maulik Sonu matter where you are asking weather you R considering I this piece and small hair solitaire amazon river casting this and mix it by vikas kisi seating s way did you happy add this complete spring and display in the spring hindi S1 ​​needle can display in the spring hindi S1 ​​needle can display in the spring hindi S1 ​​needle can not make both physically and jobs tomorrow morning tube will do What is the date of birth appearing to appear for that they will remove first from the last from the middle will see the weather they are able to remove from the stars from the last for the first position as well as will remove from the last Ki Subah Will Be No One Comes To A Greater Noida Medium Activity and Antonyms Chapter 11 Take Egg And E Cannot Be Removed Ki And E Cannot Be Removed From You End Of The Letter From This Is Play Store Do Hai Sonth Vacancy Plane Se Person Hai Pramukh Tak Man element and vr left with ashok management department speed this transition element to original string maximize the day e want over here remove from the last okay this t-20 team vikram equal to this t-20 team vikram equal to this t-20 team vikram equal to that this new the spring begum null yet mp 10 Ameer Bhi Hai Prabuddh Komal Element And Now We Are Left With Anupam Element In This Period The Element To Be Seen Is With A Small Screen And Small Sentence Date Will Welcome Equal To The Long Sentence Increase In Store Sheet Arrangement Example Lipstick Example EE Want window will remove from last ok but not able to remove from last ok so what will do e will remove from the first world will move from the first show will remove back and will remove hair from right knowledge and what we can See a difference and you have vanished in the Lord Buddha Komal element from both of the king and chief villain Komal element is peth ke daman ko management a 104 Lord ko mili mein speed element with a smile Spring day very few in the camera and yes So yes very Vikram equal new vacancy hai the history vitamin E two not have to do anything just being removed from the last this to be removed from the beginning speed from the in your best ringtones MP3 I river cancer here pr urine less limit and will examine them All Elements Piano Double To Make Any Interesting Facts End Of The Spring And Sentence Empty Debit BMW Udhar Of Management Example Hai That Is Vansh Abhishet Abhi Ki Is Of Good Boy And Selected Complete Abhi A Good Day Ab To Itne Namo Phanda Laash Dhobi Andar Mohan Gala Battery Saver Mode On The First Abhi Bikaner Mode Is Off But They Can't Move And Off The Is Sent Off The Sentence Of But Good Angry Birds Common But They Can't Because Of Vikas's Teaching Them And They Can't Mode Internet Benefit From S one of the two is convenient for having specific instructions here specific NCVT N Seshan it is not possible to make any of Baroda's notification limit for B and family members in the red button for removing switch provided pizza bread is that sa good ok but And for wedding is but won't have a say in for wedding gifts from the back side it's bread boy and so they don't have so the can see a traffic note in our residential school a slash comment and that's lipstick and brute force split S P N B T C is so inferior that this realization and equal festival in this equation but this business has sting in common and absolutely this string that he returns to relax on the sight was return forms and for the very ball of this length of That is Vansh Sudhir Ranjan and Staff that and every month till it will not find lasting sign request you can see the is sentence of fifth form bharna pure not equal to sentence of two - In this where equal to sentence of two - In this where equal to sentence of two - In this where traveling from last k subah will do sentence hotspot will You for the last 24 years of ignominiy of you have already known to everybody familiar with this should be able to remove from glass sure will remove channel which channel is interested in 409 mit is complete show and specifically to complete this a note via liquid S1 S2 and Were removed from the start s well s hua hai a solid smooth from the first hai main hoon na bhaymukt all check if this sentence that this sentence inside sentence 204 length and sentence 108 misbehavin udhar komal element and a leg with anupam element ki city not Possible were the return forms jai ho om income tax return hai honey singh tax eros length of spin were and his showing its speed and peanuts bewildered my know what will support and scene is sentence one popcorn that his sorry bhaiya ko remove worth of the way Of birth e will be to soft element 3D full moon episode and commitment vhp just old age a look on the results will movie tv set this and have done that films this akhilesh bhaiya after various purposes can we do not your exact films against the adversary That n I am here tomorrow morning it is play list complex text send a prop devgan ki pake khayal centers maine sentence to high school the saint explain in sentence to recall a view to return to for beer prc in the dept ok that is and It is super hit here this year Venus acts that maybe testing struts2 this sentence Vansh a small sentence for two someone has become this sentence one sandesh2pun a lip directly report what is after removing all the elements can also be removed Vigraha Murthy Sa This Sentence - 1929 202 A's Suspicious William Hunter Last morning app will remove that because your a that his sorry man moving from the last salute morning 2.0 morning 2.0 from last salute morning 2.0 morning 2.0 from last salute morning 2.0 morning 2.0 from Africa to be removed from the starting given not movie FROM BOTTOM MITHYA NOT EVEN LAST SO YOU HAVE TO RETURN MEETING IT WAS NOT ABLE TO CLEAR ALL THE WEIRD YOU WERE BEING MADE THEM STAND 100 DAYS AFTER DEFEATING YOU CAN JUST WRITE END SEWAGE LINE BY LINE THE POINT OUT WHAT HOTSPOT of TV live without you have any mistake ok and soothing this is the quality representing bad feeling And Function Morning Gilur What We Can Do And You Can Do You Will Just Special Guest Figure Singh 's Nav Vihg Rivers Is Show You Know Time For The 's Nav Vihg Rivers Is Show You Know Time For The 's Nav Vihg Rivers Is Show You Know Time For The Last University After Starting Behavior Benefits Systematic Testing That Way The Things Which Have Interesting No Dear Editor In Link and vote for the letter and 10 sentences where there is no demon in front of the sentence loot remove from starting you can remove from the in because I have just been worshiping and you can supply department condition notice issued on are butter read this And Because Vikas Here You Are And Doing Or Fan Page Here You Have Done Bhigo Function Graph And Time Of Beef And Take Off But Can't Hear Of Her Wedding Picture Of A Good Thing In The Morning But You Are Not Good So What We Can Do Institute Of Nursing 30 Big Will Cost You When You Can Remove That Crop Iment Not Soak Fun Time You Can Check The Is Usd Your Starting Practical They Immediately Starting Value Of The Skin Spelling I Safe Guys Thank You For Watching My Video Have Lived A Content Aayog I Am Able To Main Stood And Please Like This YouTube Channel Subscribe Skment Maze Pe Zameen Adhura And Thanks For Watching And Subscribe And Don't Like And Don't Forget To Like To Thank You Will Meet You In Next Video Bye-Bye Take Care You In Next Video Bye-Bye Take Care You In Next Video Bye-Bye Take Care Tips that it has happened
Sentence Similarity III
maximum-erasure-value
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, `"Hello World "`, `"HELLO "`, `"hello world hello world "` are all sentences. Words consist of **only** uppercase and lowercase English letters. Two sentences `sentence1` and `sentence2` are **similar** if it is possible to insert an arbitrary sentence **(possibly empty)** inside one of these sentences such that the two sentences become equal. For example, `sentence1 = "Hello my name is Jane "` and `sentence2 = "Hello Jane "` can be made equal by inserting `"my name is "` between `"Hello "` and `"Jane "` in `sentence2`. Given two sentences `sentence1` and `sentence2`, return `true` _if_ `sentence1` _and_ `sentence2` _are similar._ Otherwise, return `false`. **Example 1:** **Input:** sentence1 = "My name is Haley ", sentence2 = "My Haley " **Output:** true **Explanation:** sentence2 can be turned to sentence1 by inserting "name is " between "My " and "Haley ". **Example 2:** **Input:** sentence1 = "of ", sentence2 = "A lot of words " **Output:** false **Explanation:** No single sentence can be inserted inside one of the sentences to make it equal to the other. **Example 3:** **Input:** sentence1 = "Eating right now ", sentence2 = "Eating " **Output:** true **Explanation:** sentence2 can be turned to sentence1 by inserting "right now " at the end of the sentence. **Constraints:** * `1 <= sentence1.length, sentence2.length <= 100` * `sentence1` and `sentence2` consist of lowercase and uppercase English letters and spaces. * The words in `sentence1` and `sentence2` are separated by a single space.
The main point here is for the subarray to contain unique elements for each index. Only the first subarrays starting from that index have unique elements. This can be solved using the two pointers technique
Array,Hash Table,Sliding Window
Medium
3
792
hello all welcome to code hub let us solve the today's lead score daily challenge the question is number of matching subsequences uh given a string yes and an array of string words return the number of words of i that is a subsequence of yes a subsequence of a string is a new string generated from the original string with some characters deleted without changing the relative order of the remaining string characters for example if a c is the string that we should check for whether it is a subsequence of abcde yes it is a subsequence because a appears before c and e and c appears before e and e appears he appears at the last so this is this string is a subsequence it is not a substring sub string means it should be contiguous but uh this they are asked to whether we should check it is a subsequence or not so it can be either contiguous or not contiguous so we have to check whether this ace string is a subsequence so a c and e so this is a true so a c is a subsequence similarly a similar way we can take this word we have to check they are given an array of words whether we have to check whether these are the subsequences so we can check first j as we know that a is a subsequence we can check b is not a subsequence because while traversing by passing the string b is a b is present here and then there is no second b there is no b with the second occurrence so this is not a subsequence then for the word acd a appears here and then c appears and then d appears so this is a subsequence this versus sub sequence and a c a appears and c appears and e appears so this is the subsequence so uh let us write a function first if we give two words to that function uh we that function should say that whether it is a subsequence or not that is we can have a boot first we can write we can directly code so that it will be easy to get understanding with this so we'll have a function bool is subsequence sub sequence passing the two strings string s1 and string s2 how i will pass this string s1 will be this word and string s2 will be the word from this uh containers so s1 is the main word we should check whether the s2 is a subsequence or not we should take whether s2 is subsequence or not that's what we have to check so how we can check so given to what's a b c d e and this body acd how we can check what we can do is we can have an i pointer here and we can have a j pointer here if this two matches if i the character at i and j matches then we can what we can do is we can just uh we can just increment both the pointers or else if this is not matching if b and c is not matching we can just move the i pointer if this is matching we can just move both the pointers a i and j and since d and d is matching you can move the both the pointers but the pointers whenever the j reaches the end we can say that this second string can form a subsequence of this first string so that's what we are going to implement for this function so we will have i equal to 0 and j equals to 0. and we can get the sizes as n1 equal to s1 dot size and similarly n2 equal to s2 dot size we can say i check whether while i is less than n1 and j is less than n2 if this is right then what we can say is if i and j is valid it is inside the boundary of that s1 and s2 then i have to check whether s1 of i is equal to s2 of j if this is equal what i will be doing is i will be incrementing j plus and i plus anyway we are going to increment i plus so i will have inside i will have outside this if condition so we have uh done the subsequence then what we have to just run is we have to return whether this j has reached the size of the second string n2 if this j is reached at the end of the string then definitely this is going to be a subsequence else it is not going to be subsequence so we have uh having a function uh for this we have having a function if we call this function it will make uh our job easier so what we will be doing is we will be traversing for all the words auto yes auto word in my words if is subsequence if a subsequence of this yes and word if this is uh done then we what we will be doing is just uh we will be incrementing our counter plus and finally we are just returning the count in count equals to zero so we will be just running our code it gets uh it gives a correct output but what if uh two strings what if a string is present already in our map let us uh give a test case like this a c d again it is a cd again it is acd and again this acd if this is our input then for each and every string i will be checking whether it is a subsequence other again i will be checking whether it is a subsequence and again i will be checking whether it is a subsequence so if i'm checking for each and every word whether it is a subsequence then it will be uh it will be very costly so we have to reduce our time complexity so what we can do is we can have a map an order not an order map where we will be saying string in bar will be saying if this is going to be a subsequence then what i will be doing is i will just put that word into my map equals to 1. else what i'll be doing is i'll be putting that just i'll just put the word into i'll just put the word mp of word equal to zero so if this is going to be a subsequence then i will be compute i'll be putting the mp of what is that the word is present in my map and i will be just incrementing the count and if this mp of word is zero if already it is not as a subsequence then i will put mp of word is zero so whenever we come inside the say for loop we have to check whether mp of mp.find of word is not equal to mp.n that is if this is not equal to mp.n that is if this is not equal to mp.n that is if this word is already present or not if this word is already present then what we can do is we can just add to our word account plus equal to mp of word count equal to mp of word then we can just continue what i'm doing here is if my word is already present in my map that is i will be calculating the cacd and it is a subsequent so i will be putting mpf word as one then for next iteration uh this acd is already present in my map so what i will be doing is i will be just counting the that word yeah account plus equal to mpf board itself so i will be getting one or zero if it is not a subsequence i will be getting zero so it is not going to affect then i will just continue so this is what i am going to do so that it will we don't want to recompute each and every time so we will just run our code ok what will be the time complexity here we are going for each and every word yeah in the consider we are having n words if we are having n words in our word sorry and we are going to traverse for average of m length for maximum length of one word that is m we can say so uh we will be traversing uh n into m times for each and every word we are going to call this subsequence this is going to traverse for minimum length of s1 and s2 so that's what we are going to do here so it will be a time complexity of m into n and we are using a map to store the redundancy so it will be a space complexity of order of m also so we'll just submit our code so it got accepted so hope you like this video and uh the let us see in tomorrow's lead code daily challenge if you have any comments let me know and if i can improve or anything let me know in my in the comments so let us all solve the tomorrow's record challenge and keep hustling until then bye
Number of Matching Subsequences
binary-search
Given a string `s` and an array of strings `words`, return _the number of_ `words[i]` _that is a subsequence of_ `s`. A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. * For example, `"ace "` is a subsequence of `"abcde "`. **Example 1:** **Input:** s = "abcde ", words = \[ "a ", "bb ", "acd ", "ace "\] **Output:** 3 **Explanation:** There are three strings in words that are a subsequence of s: "a ", "acd ", "ace ". **Example 2:** **Input:** s = "dsahjpjauf ", words = \[ "ahjpjau ", "ja ", "ahbwzgqnuk ", "tnmlanowax "\] **Output:** 2 **Constraints:** * `1 <= s.length <= 5 * 104` * `1 <= words.length <= 5000` * `1 <= words[i].length <= 50` * `s` and `words[i]` consist of only lowercase English letters.
null
Array,Binary Search
Easy
786
137
Hello gas I am Lalita Agarwal welcome you on your on coding channel trick made by you on that date cold problem today's late problem what is the problem saying good before moving towards the problem na 1 minute par dose jino ko a problem achhe What you have understood is that you have to try it yourself. Look, this question is literally a very easy question. Here you have two methods to solve it because here in the question, it contains the whole error story of Puri. Isn't it, there are only two things in life, either there is a number life which will always be present three times or there is a number life which will be present only one time. These are the only two conditions, so what are you doing here now? You can do this, here you have the power to create both conditions that either you return a number which is present exactly one time or you return a number which is not present three times, the same thing will happen. Yes, it is the same thing, but with that you got the condition of another broad way that you can build the algorithm from the story also. Literally, this question is very much, think a little in its bigger picture and literally this will happen to you here. What is this thing, we have to pay a lot of attention to that there should be run time complexity and there should be constant expression. Line time complexity means only this that if our Erica size was earlier 4 and then Suppose it becomes 10, then here your time complexity is linear, meaning, suppose that when it was at size and at the point of time being it, if your time was taking four seconds, then when your size was 10, it was taking time at the time of second only. This should not happen. She was eating food on time and as soon as it was 10 it reached 400. No, there should not be that much difference. There should not be any expansion. It should be okay. I understand that there should be linear time complexity further. Well, there should be constant extra space in front, what do you mean by constant exercise space, if you are thinking of map method then don't think, don't do it with the first method, there you will not be able to get constant exercise, yes brother, we are all. Let's count, do n't think about who is the method, don't think about the method, it's okay, the problem is that they have not understood, there is no need to take tension, first of all they are going to understand very easily, he is going with questions and then later. We will bill its approach and give the final bill, move versus implementation. Look, understand, say question here, what was six, here was 0, if you take it completely, then what did you do to it. If you have to write in sorted way, it is okay for once, then zero. Comma zero comma zero is okay then after this one comma one and nine is okay but you have to understand but understand. I had this Eric Jeevan, my country has been sorted and written, fusion, there was nothing to shorten it, now you will understand, he said, okay, now see what you had to do in this Re, this is the surety of this thing, do you have only and There will be only two types of numbers, there will be one number in all of them, which will be repeating three times, but sir, it will be happening not only three times, but it will be happening 5 times, no, bla, bill beat will be happening only three times. So yes brother, the one which is zero has come three times, the one which has come three times, then either there will be numbers of this type or there will be numbers of another type which will come exactly only once and such a number will also be only This is also a sure thing, there will be only one number in the entire area, which must have been exactly once only, it's a simple thing, okay, simple thing, it's a simple thing, okay, so you have only two ways in the entire area. There are numbers of one way, the name of your three times, there are numbers of one way which are repeated only and only once and this one is a simple thing, so what to return to yourself, there is nothing, there is no return from you. You have to get it done exactly one time. Okay, now see how this question becomes very easy because the things he has said are exactly true for every year, there will be no exceptions like this and this. It will also not happen that only and only the numbers having 3 are present, that means such numbers are present which are being repeated three times, only the same number having 1 is present, it will not happen that this condition will always remain true that it will always have Two types of numbers are present, that is Sir, now there can be any number of them, these numbers which are being repeated three times can be any number of times, like here there is zero, one has gone, 32 can also happen. Which is repeated three times, 3 can also be there because there are free time repeaters and so on, otherwise any number of such numbers can be there, but this soldier and there will also be a number which will be repeating only once, okay. Have you understood? There should not be any doubt in the question. I was returning the same number in the last. Okay, can't I use some method for this? I have understood the question with G method. The question can also be solved with this method. What does it mean, what will you do by shorting, what will happen by shorting, by doing shorting, all the numbers you have will come together, that is absolutely correct, so as soon as you have all the numbers with six, you will have your own. What are the two methods? The first method was that either return a number which is not occurring thrice, it is a simple thing, or else return a number which is occurring exactly once. This number will be returned, he said, yes, when this is returned, it will have only two methods, okay, so what are you doing, you are returning a number which is coming exactly once, then how will you check the open condition, said, simple thing. I have started trading from here and said, okay, I have started trading from here, now once you take it a little bigger error, we reduce it here, take 222 here, okay, what will you give? Is the one on its left and the one on its right equal to zero? Will the one on the left be equal to the sum of both? The one on the right is not, meaning it is not exactly a one-time present. Have you meaning it is not exactly a one-time present. Have you meaning it is not exactly a one-time present. Have you understood this? Have you understood the place Apna exactly one time means returning the answer is six then no this too will not be returned ok then Apna is above it Apna said is the one on its left equal to this one not the opposite so the one on the left is not equal but the one on the right is equal It is done, we will not get this done, then we will not be able to return this too, then we will not be able to return it, then we will not be able to return this also. I saw whether the one on the left is equal, I said yes, the one on the left is equal, the one on the right is not, but I did not want both of them, that is okay, this much 99. Did I see that the one on my left is also not equal, and the one on the right is also not equal? No, both are not equal, so what about you here, you have got the answer, it was a simple thing, he said, what will you do with me, 99 is 310, I understood, he said, yes brother, I understand. Now, where will the exception come here? In this method of ours, what if this 99 was the last element, like this is Maa Lo, it would be like Olav's, yes, this is the last element to be handled and similarly if this is our first. I would have said 90. Yes, yes, the right one will be gapped. If you can't check the left one, then the first and last errors have to be handled. It's a simple thing, Hanju. If it's a simple thing, then what will you do with the first and last? What will we do if we check it separately then it is not a very typical thing, rest of the check will be done for the whole, he said, it is okay, we are doing our own sorting is always done in linear session, what happens at the time of sorting, n people and one. This is absolutely correct, as your N increases, it will increase linearly. There is no problem, space is not required for it is a simple thing, let's see the implementation once. Come here, it is open as soon as you come. First of all, what have you checked, if this vector of this vein has come, if the size of this whole is less than three, then it means that brother, your answer is the same which is yours. Here also your answer is in the zero of Namas, the same is your answer, it is a very simple thing, maybe I just did it, yes, I understood this thing, after that what did I shorten it and said yes. Brother, I have made it short, there is no problem in making it short, no one said, okay then what have you checked, you have checked a simple condition, you have done this to check the first one, because you are the first, it is the one who is first who is the first. If you can't do left then you will have to take care of yourself, the first one is last, it's another thing, so I checked the first one, brother, is the first one equal to the right one or not? He said, it's okay if it is not equal to the right one. You have got your answer right here, if it is a bullet, then the first one will not be equal to the right one, then your return name here will be zero. Said, ok, what is the name, this is my name support, ok, is there any problem? It's not the same thing, then what did you do? The look of four has come from. Where did the look of 4 come from? Said I plus tu minus tu one means the one who came from here is a different thing, the one on the left has checked the pan, there is no problem. What will you do from here, if the one on the left and the one on the right are not equal? ​​If both of them are not equal? ​​If both of them are not equal? ​​If both of them are not from this, will you get your return done, then what will you check inside the condition, if this is the name of the name, if this is from the one on the left. It is not equal and at the same time it is not equal to the one on its right. If both of them are not equal then we will return ours. Do you understand what A is saying? Said yes brother, I understand. If it is not equal to both then If it is equal to even one of the two, then you will not be filing your return. He said, this is absolutely correct, okay or you have run your entire forum on top of this, now what condition do you have to share, just on the understanding of the last one, let yourself be the last one. And the condition has to be checked that if the last condition which is the last condition which will be equal to the one on the left, the one on the right does not say okay here, what did you say, how did you directly return it to the light one because the question. What was I saying to myself that I was getting excited that there will be such a present, there will definitely be a number present, so I have checked all my elements, even the elements, I have checked all the elements, now only the element child. And there was no one there, so what should I say first that he is the one who has directly returned what I am doing. I hope you have understood it well and after submitting it, thank you very easily. Okay, yes, its space was given to him. They are not doing it, they said it is absolutely right and how much time will be there and what to do on top of this, they are also tweeting the look of four, they should have done off n people and plus n honey but they are ignoring plus n. Let's give
Single Number II
single-number-ii
Given an integer array `nums` where every element appears **three times** except for one, which appears **exactly once**. _Find the single element and return it_. You must implement a solution with a linear runtime complexity and use only constant extra space. **Example 1:** **Input:** nums = \[2,2,3,2\] **Output:** 3 **Example 2:** **Input:** nums = \[0,1,0,1,0,1,99\] **Output:** 99 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-231 <= nums[i] <= 231 - 1` * Each element in `nums` appears exactly **three times** except for one element which appears **once**.
null
Array,Bit Manipulation
Medium
136,260