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
20
Loot Gayi A Hello Everyone Welcome Back To My YouTube Channel Short For Today Khayal Going To Solve This Question Parents Is Check Flex Discuss Words For Women About This Problem What You Give Strength Which Is Three Different Brackets Kali Basis Directions Like Rage And Need To Tell Weather This express in this spring this balance and note like on this decade name on which rocket is the festival classification opening rocket renovated and opening almost great and the closing correct and go away please that similar if e c the second o d exam pim c Due to which balance and last notification this video not have using back and not balance vital force for tomorrow morning like hair too much soil time complexity is active wax switzerland for string a special operation on 500 rupees sickly what will let you do stupid thing in Mind That Whenever They House Something With Kids That ATM Machine Chances That Giving Stocks For This Let's Discuss Why This 200 Grams Per Latest Ghr Hai To Vo Hairless Page-10 Page-10 Page-10 That Rampur Loot And Let's See How Does So Result Per Latest Thanks Oo Hai So What Will Do It Will Start From The Forest I Will Care In Counter And Opening Day Tweet Is Gully Round Square Will Additional Stock The Second Bluetooth Setting Rishi Round Account Opening Prohibition That Diner Knowledge Special Square Opening On Windows 8 Tuition On 19 World Cup a so I did that also just closing back at will a point from stock and will see weather is the closing rank what is this who is the item with support from distant is pot opening racket the water flowing packet secs are you can continue for the rate in The processing of there any of its nodes in you can directly in return for this we will see that this also heard since it case will move to next and in counter the closing of our products and services from the 10th check the weather just before opening it And in closing I keep the item Indra Dev encounter using Kali but not disclosing rocket 15x every time you points that will make the sentence 100 to 150 topic this is approaching vaikuntha item wisftok president opening date for this project is that souvenir guddu And Veer With A Sin And Fifth's Motu Patlu And When The Would Mean That Everything Executive Perfectly Fine Joe Wilfred Per And Eternal Truth So I Hope You Guys Let's Two One Thing Research Now Discuss The Case Which Is In Which The Parents Is But I am your next, if there is a photo with it, then the supposition will also be fast, this one will be the example from below, I am India's enemy, okay so let's, I am 13 Shaikh, yes friend, I am really here, what happened, the son's driver will go to the first this opening directly Push Notifications Arrested On Opening Day Quotes Will Push And Ultimately I Will Give You To Dushman Na Vigo Ko Vijay Vikram Veer And Will See You Will See Exercise Ho Sakti Is Note 09 Jul 21 Swift The Top Element Which Is This Point I Anil Check this in the point element is the opening and closing date gas tomorrow morning guddu ko butt nau straight tweet a ya dengue do everything in the sense and what will discuss what like so short duration loop sacrifice leg spin testing will return to rule over a great You don't even know the spelling mistake that and it is not because answer to various full pattar algorithm will attain true redundant test cases that whenever we are talking to we need to take in condition but it is not I ignore take date to return true that in this chart This note MT Everest Amazing spider-man Witch Mince That Britain Was Not spider-man Witch Mince That Britain Was Not spider-man Witch Mince That Britain Was Not Balance and Vital Force Improvement Trick Basically two algorithms are coach till analytics so code is speed sample like so python code to show what everyone else is such formation and where given string what made You Madam Map To Every Then Why Now Scooping Explanation The Frozen Racket I Apni Were Kept And Using Back And Opening Packet And Rudraksha Add Once I Love You Bol Hundred Meter Set For Apne Baith Naam Let's Go To It I Item Interesting And That Is that is in not opening balance so its native which will directly pending star that and defeated note mind gives its previous closing of its will to illness and will check is that is the means that not empty and record of I to I is the clothing knotted Clothing noted as an as equal to stop that bedi the opening racket suggestion bracket of opening show bracket of opening buildings according one should sacrifice is equal to work for watching test particular thing this swift 10 top richest opening rapid and is i when skin in pc in And the bracket clothing blankets and to bring back is not of same trick it means dad need to return for that one text message inbox empty new delhi to do this condition synthesis equal operator advertiser 2014 star k 2222 ki ns note mts admit discussing a Vital Force's research made clear Inch The Code And I Hope You All The Story Of The Code You Have Any Doubts In Questions On Your Feet Washing Comments And Time Complexity Of Mother S Singhvi Go To 8 Main Items Interesting Facts Of In Any Land Of Saints And Pious Souls And Because We Should Also Possible Storing All The Items Industry And Quality Of Life In This Time He Told Opening Parents Is And Will A Pushing And Decimal Dainik Hindustan Ko Hai To Page 209 Thank You For Watching
Valid Parentheses
valid-parentheses
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. 3. Every close bracket has a corresponding open bracket of the same type. **Example 1:** **Input:** s = "() " **Output:** true **Example 2:** **Input:** s = "()\[\]{} " **Output:** true **Example 3:** **Input:** s = "(\] " **Output:** false **Constraints:** * `1 <= s.length <= 104` * `s` consists of parentheses only `'()[]{}'`.
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
String,Stack
Easy
22,32,301,1045,2221
264
welcome back for another video we are going to do another decode question the question is 264 ugly number two a ugly number is a positive integer whose prime factors are limited to 2 3 and 5. given a integer n return the m ugly number example one and equal to ten the output is 12 explanation 1 2 3 4 5 6 8 9 10 12 is the sequence of the first 10 ugly numbers example 2 and equal to one the output is one explanation one has no prime factors therefore all of its prime factors are limited to 2 3 and 5. the ugly number sequence is 1 2 3 4 5 6 8 9 10 12 15. since every number can only be divided by 2 3 and 5. we can split the ugly number sequence into three subsequences as below 1 times two three times two four times two five times two one times three two times three four times three five times three one times five two times five three times five 4 x 5 we can use merge sort to get every rc number from 3 subsequences let's work for the code we first declare a array with the length of n we initialized first ugly number 1 at index duo we then initialized 3 array index variable index 2 index 3 index 5 to point first element of the array we initialized three choices for the next ugly number we use a for loop two theory array with ugly numbers two m minus one if a number is chosen as the next ugly number update the number with the multiple of corresponding prime factor finally we return the array element at index m minus one time complexity is o n space complexity is o n the solution works thank you if this video is helpful please like this video and subscribe to the channel thanks for watching
Ugly Number II
ugly-number-ii
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`. Given an integer `n`, return _the_ `nth` _**ugly number**_. **Example 1:** **Input:** n = 10 **Output:** 12 **Explanation:** \[1, 2, 3, 4, 5, 6, 8, 9, 10, 12\] is the sequence of the first 10 ugly numbers. **Example 2:** **Input:** n = 1 **Output:** 1 **Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. **Constraints:** * `1 <= n <= 1690`
The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
Hash Table,Math,Dynamic Programming,Heap (Priority Queue)
Medium
23,204,263,279,313,1307
15
hey guys welcome to code world and today we'll be going over Le code number 15 three sum so this problem is pretty similar to two other problems I've solved on my channel uh which are two some one and two some 2 and we'll be combining concepts of both of those problems in order to reach the most optimal solution for this one so in this problem we are given a one-dimensional problem we are given a one-dimensional problem we are given a one-dimensional integer array of numbers and what we want to do is return all of the triplets of this array such that their sum is equal to zero and we cannot con uh our solution cannot contain any duplicate triplets so we have an example down here we have an integer array called nums uh comprised of these numbers and we see how uh the output for this example uh contains two uh triplets so um our output is going to be a two-dimensional output is going to be a two-dimensional output is going to be a two-dimensional array and each of these triplets satisfies the condition in which the numbers when summed equal to zero so we know that -1 +- 1 + 2 is equal to 0 so know that -1 +- 1 + 2 is equal to 0 so know that -1 +- 1 + 2 is equal to 0 so we add that as one of our triplets and we also know that -1 + 0 + 1 is equal to we also know that -1 + 0 + 1 is equal to we also know that -1 + 0 + 1 is equal to zero so we add that as our other triplet okay so we're here in a Scala jaw and I will be showing you uh both possible solutions to this problem first a more boot Force solution and then I will show you how to optimize it to reach an N squared solution so the boot Force solution involves um finding every combination of triplets possible in the array and then checking to see if this combination of triplets when sum together equals to the Target which is zero uh this solution is going to be an N cubed solution and I will explain why so uh the algorithm for this NCB solution involves having three for Loops one outer for Loop which will uh keep a pointer to a number so we will initialize this to be the first number then we have a second for Loop uh for a second pointer to another number which we will have seven and then the inner for Loop will go through the remainder of the numbers in the array so we'll have 8 10 and5 and what we'll be doing in this algorithm is that we are going to be um summing these numbers up in each triplet so we have -2 + 7+8 and we'll check to see if it is 7+8 and we'll check to see if it is 7+8 and we'll check to see if it is equal to zero um and in this case it is not equal to zero so what we will do is we will move on and our next triplet is -2 710 so we will do the same thing is -2 710 so we will do the same thing is -2 710 so we will do the same thing we will have -2 + 7 we will have -2 + 7 we will have -2 + 7 + 10 and again we see that is not equal + 10 and again we see that is not equal + 10 and again we see that is not equal to zero and so we would continue this for every triplet uh we then have -2 + 7 for every triplet uh we then have -2 + 7 for every triplet uh we then have -2 + 7 + -5 and we see that this is equal to + -5 and we see that this is equal to + -5 and we see that this is equal to zero and so this will be one of our triplets right so after this what we would do is we would move our second pointer to the next number right um our first pointer would remain at the first number and then we would check um as our third number the remainder of the uh numbers in the array and finally we would have another loop where we keep our red pointer here our green pointer would move on to d10 and then our inner for Loop would just have this last number uh at this point we would need to move our outside our outer pointer to the next number and restart and this would allow us to find every triplet possible now um here is the code in Python for this uh first algorithm as we can see it would involve three for Loops uh an outer for Loop which goes from 0 to the length of numbers minus 2 uh a second for Loop which goes from I + 1 to the length of which goes from I + 1 to the length of which goes from I + 1 to the length of numbers minus one and a third for Loop for the remainder of the elements in each iteration and because of these three for Loops it is an N cubed uh runtime solution and in each time what we' do is solution and in each time what we' do is solution and in each time what we' do is we'd see if the um numbers sum to zero and if they do we would to pend the triplet to our result now we would also need additional checks and data structure just to make sure we aren't adding any duplicate triplets um but this is just the um a summary of the code which I wanted to show you guys to explain why it would be an N cubed solution now in order to improve this runtime uh to reach the optimal solution uh what we would need to do first of all is realize that we could take advantage of sorting these numbers just like we did in two sum two so uh we're going to start off by sorting these elements in our array and we know that a sort would take um nlog N Run runtime complexity uh this will not affect our runtime complexity overall because um our optimal solution will be n^2 so it is optimal solution will be n^2 so it is optimal solution will be n^2 so it is okay to sort in this case so we know that 8 would be smallest then we'd have -52 7 and 10 then at this point what we' -52 7 and 10 then at this point what we' -52 7 and 10 then at this point what we' need is Just One Singular pointer which we would start from the first number and then we could have two other pointers which is left and right poter point there and just like in two sum 2 we would take advantage of the fact that these numbers are sorted in ascending order in order to move these left and right pointers accordingly right so we would have our first check um and we would check to see 8 + -5 + 10 and we would check to see 8 + -5 + 10 and we would check to see 8 + -5 + 10 and we see that was that would be equal to um -3 which is smaller than zero okay so in -3 which is smaller than zero okay so in -3 which is smaller than zero okay so in this case because we have a sum which is smaller than zero uh we know that we need to increase our sum and we can take advantage of the fact that our numbers are sored or sorted in increasing order so because our sum is smaller than zero we need a bigger sum so what we would do is we would move our left pointer towards the right in order to increase our current sum uh now we can recompute a sum to make a check and we would see we can now check and see um if our sum is equal to zero so we have8 + -2 + 10 and we see that is equal + -2 + 10 and we see that is equal + -2 + 10 and we see that is equal to Z so a triplet has been found uh because the triplet has been found um we can add these three numbers to our result and then we can continue on with our uh solution with our finding our Solutions right so we can now move our left pointer again so to WR by one and we'd recompute the sum we would see that it is not equal to zero and then at that point when moving our pointer our left and right pointers would cross and we um would be done with this inner while loop so at this point we can move our red pointer to the next number and repeat with the same algorithm so we would move our red pointer here to the5 we're then considering the8 and then again we have our left pointer at -2 and our right pointer left pointer at -2 and our right pointer left pointer at -2 and our right pointer at 10 so again here we can compute a sum and we would see that -5 + -2 + and we would see that -5 + -2 + and we would see that -5 + -2 + 7 + 10 this time is equal to uh positive 7 + 10 this time is equal to uh positive 7 + 10 this time is equal to uh positive 3 which is greater than zero so in this case instead since we have a sum which is greater than zero we want to decrease our sum and we know our numbers are sorted in increasing order so all we have to do is move our right pointer to the left so having moved our right pointer to the left what we would do is we would recompute the sum and we would see that this time when adding -5 to -2 to 7 we get zero so a triplet has been found again and we would continue this algorithm to finish all of our checks uh however in this case um we do not have three Flor Loops uh in order to run this algorithm we just have one outer for Loop which is represented by the Red Dot uh to um take into consideration the first number and then we have an inner while loop with two pointers left and right pointers which will only Traverse the array once and because of this we have an outer for Loop and an inner while loop this improves our runtime to an O of and squared time complexity which is a great improvement over our previous solution so this one is going to be o of n^2 so now we can go back to Le code and n^2 so now we can go back to Le code and n^2 so now we can go back to Le code and write up our solution okay so we're back here in leak code and we're ready to write up our solution uh so again what we said is that first of all we are going to start off by sorting the nums array and we know this is going to take an N log n runtime complexity just to sort uh but that will not affect our overall runtime complexity which we know will be n^2 which is greater than n Ln will be n^2 which is greater than n Ln will be n^2 which is greater than n Ln anyways and afterwards what we're going to do is we're going to have our array um say for example -2 after having um say for example -2 after having um say for example -2 after having sorted it actually would be 8 -5 8 -5 8 -5 -2 7 -2 7 -2 7 10 and we know our Target is equal to zero and what we would have is we would have initially our first pointer start at the first number we would have a left pointer and a right pointer and we would want an external for Loop and an internal for Loop uh using this idea of having an i pointer an L pointer and a right pointer and taking advantage of the sorted array in ascending order so we're going to start off by saying nums that sort which is a python method in order to sort the array and takes n l in time and we going to PR prepare our resulting array which we know is going to be in a two-dimensional array then we to be in a two-dimensional array then we to be in a two-dimensional array then we can say for I in range from zero to the length of nums um minus 2 and in increments of one what we're going to do is um have two pointers right we're going to have our left pointer which is going to be equal to I + one and we're going to be equal to I + one and we're going to be equal to I + one and we're going to have a right pointer which is going to be equal to length of nums minus one and we're going to have an internal for loop as we said and we're going to continue this for Loop until the left and right pther do not cross and we're going to calculate our sum so our sum is going to be equal to nums of I nums of L plus nums of R and then we're going to check to see the different conditions of whether our sum is smaller equal or greater than zero so if sum is smaller than zero what we wanted to do is increment our left pointer to achieve a larger sum else if our sum is greater than zero we wanted to decrement our right pointer to achieve a smaller sum and finally if our sum is equal to zero then we want to append our current solution so we're going to pend nums of I nums of L nums of r as a triplet and then we can continue our um algorithm by incrementing our left pointer um so you could also do this by decrementing the right pointer uh you can decide whichever pointer to move in that case now um another thing we needed to make sure is that we do not have any duplicate triplets in our solution so in our for loop after starting each um new iteration want to check is that as long as I is greater than zero and nums of I is equal to nums of I minus one meaning that the two subsequent numbers are the same uh in this case what we want to do is just continue on to the next iteration because we do not want to have duplicate triplets so if I moves from one number to the next number being the same we can just skip that iteration and similarly in our W loop after finding a solution here and appending it uh and moving our pointer uh we can say that while left is still smaller than the right pointer so they do not cross a nums of L is equal to nums of L minus one meaning that we have moved the left pointer and it points still to a number which is identical to the president what we can do in this case is increment our pointer again um afterward words uh what we can do just do is return our resulting array so let's check to make sure that this code runs okay so I had a typo here um when decrementing the right poter we got to make sure by we are decrementing by one uh I put zero here by accident and we should make sure our return statement is outside the for Loop so I'm going to rerun this again and we see it's accepted let's MIT and it works um so thank you so much for watching this video I hope you found it helpful if you liked it please like And subscribe to my channel and I'll see you on the next one
3Sum
3sum
Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`. Notice that the solution set must not contain duplicate triplets. **Example 1:** **Input:** nums = \[-1,0,1,2,-1,-4\] **Output:** \[\[-1,-1,2\],\[-1,0,1\]\] **Explanation:** nums\[0\] + nums\[1\] + nums\[2\] = (-1) + 0 + 1 = 0. nums\[1\] + nums\[2\] + nums\[4\] = 0 + 1 + (-1) = 0. nums\[0\] + nums\[3\] + nums\[4\] = (-1) + 2 + (-1) = 0. The distinct triplets are \[-1,0,1\] and \[-1,-1,2\]. Notice that the order of the output and the order of the triplets does not matter. **Example 2:** **Input:** nums = \[0,1,1\] **Output:** \[\] **Explanation:** The only possible triplet does not sum up to 0. **Example 3:** **Input:** nums = \[0,0,0\] **Output:** \[\[0,0,0\]\] **Explanation:** The only possible triplet sums up to 0. **Constraints:** * `3 <= nums.length <= 3000` * `-105 <= nums[i] <= 105`
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Two Pointers,Sorting
Medium
1,16,18,259
1,721
Hello Guys Welcome To Disrespect Video Adversities According And Dav High The Daily 4 Inch Problem Of Today Only Code Shifting Notes Know Best Endowed Only Business Language Problem Lol That Printed Channel 's Most Wanted To Give One Example To You To The 's Most Wanted To Give One Example To You To The 's Most Wanted To Give One Example To You To The Subscribe and subscribe the Channel Play Store Income One for ninth to and five to select 214 voice of twenty four given to and at least one in Aankh setting band SisOne this is to three four decent from winning the country from the last second in the last Is this cancer cases from giving us this view is too short from which that convenience logic ab isko subah pastila do hai that guy and does not think mode actually very good dabi band set transformed into a beating transformed into a sweat and tears e believe in simple first Resistance From To-Do List Start To Resistance From To-Do List Start To Resistance From To-Do List Start To 9M Taking There Inner Temple To In To Vade Kandu Irshai Can And From This Least Way Are From Venus Is Amir Vektar Intermediate College Gift So What I Will Do It Is File Okay Bhai Temperaments For All Times Not Also a temple in this world will end with children will run at times dot push back to back of the first one ok so basically university 12345 subscribe button this end converted notes meaning of the first hydropower impotent bana pull back to benefits friendship like push back for Dene Pushp Ek File Ok To Have Converted This Link List That Not Converted In The Sense Is Taken Shelter And Transformed Or In The Sense Is Laddu Adi Se Liquid Form Of The Soul Valley Ask After Making Video then subscribe to the Page if you liked The Video then subscribe to the Page 1212 From Police On Midnight Raid By Swarna Reed And Aksar Zero Indexes Hero 1234 Badli And Electronic Shivling Clips Of 12345 From Zoom Liquid 3.2 This Clips Of 12345 From Zoom Liquid 3.2 This Clips Of 12345 From Zoom Liquid 3.2 This Point To Index One In the ok Point To This Point To Index One In the ok so basically posted by singhanita in numbers are water will be able to give - 1929 will give numbers are water will be able to give - 1929 will give numbers are water will be able to give - 1929 will give the element from backside dec ok what is subscribe - 25 - 2323 lies is subscribe - 25 - 2323 lies is subscribe - 25 - 2323 lies and 128 rates on that maybe just count net and views account - K Member first day will ask or account - K Member first day will ask or account - K Member first day will ask or pimple taste one ok and no I will pass away after seven days clearing and extra function just for convenience of it's not at all this and you can do it even simple way ok I will make white swap is the function Other Functions In the internet and spa The Amazing spider-man OK no I will just Amazing spider-man OK no I will just Amazing spider-man OK no I will just subscribe number se very simple and easy to 102 view of chase equal to temp to tight feature set a good crop ok and as per taste complete building In the subscribe this Video give to-do list subscribe this Video give to-do list subscribe this Video give to-do list time to all so much towards nod32 409 plus first element realm The Amazing Elements that you on settings tree group of elements android stop anime sudhir world book for Vikram Support A Wick In The To Is Give The Function Life Changing Gives Nod To Return For Lips Light Bill Delhi 143 2152 Withdraw From List 12345 Wale Liquid Custom Converted To Are Converted In Just To Do The Thing From The Amazing element's servi swapping and that storing play list is simple two plus two and Vikram Twitter cleared toe stamp tool Vikram tap hundred-one hundred and fifty point tool Vikram tap hundred-one hundred and fifty point tool Vikram tap hundred-one hundred and fifty point M2 world return hit superhit just switch working to iodine work lashes valency of working. Jewelers Sensitive with Working for Blood Test Cases Indicator Chapter Solution That Set Thank You for Giving May
Swapping Nodes in a Linked List
maximum-profit-of-operating-a-centennial-wheel
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
Array,Simulation
Medium
null
735
in this video we're going to solve the lead code problem asteroid collisions in this problem asteroid collations we are given an array of integers in this array of integers we see that we have positive value and we have negative value the absolute value represent the size of asteroid here we have five the size of asteroid is five here we obtain the size of asteroid is 10 here we have minus 5 it means the size of the asteroid is the absolute value which is 5. and the symbol or the sign represent that direction for this asteroid the sign is positive for positive sign it moves to right here we see the sign of this asteroid is positive so it moves to the right all the asteroids moves in same speed and here we see that minus 5 this is negative sign negative symbol so it's moved to the left if the sign of a asteroid is positive it means it moves to right if the sign of asteroid is negative that means it moves to the left all the asteroids moves in same speed so this two asteroid will never collide but we see that these two asteroid will collide this asteroid moving to the right and this asteroid moving to the left if these two asteroid Collide we see the size of this asteroid is five the absolute value is the size and the size of this asteroid is a tin if these two asteroid Collide this asteroid will be destroyed that's because the size of this asteroid is less than the size of this asteroid if we have here minus 10 instead minus 5 then we see the size of these two asteroid are the same right so if these two asteroid Collide these two asteroid will be destroyed okay this is the problem so in this problem if we are given this array of integers this asteroid moves to write this asteroid moves to left we see the direction of this asteroid and the direction of this asteroid at the same so if these two asteroids Collide then this will be destroyed so we are left with these two asteroid moves in the same speed in same direction so these two asteroid will never Collide each other so we have to return these two asteroid 5 and 10. for example if we are given this array of integers here we see the sign of this asteroid is negative so it's moved to left the sign of this asteroid is positive so it's moved to right the sign of this asteroid is positive so it moves to right the sign of this asteroid is negative so it's moves to left we see that this asteroid moves to left this asteroid moves to right so these two asteroid will never Collide each other because these two asteroid moves into different direction then these two asteroid we see that these two asteroid Moves In One Direction at the same speed so this true asteroid will never Collide each other now these two asteroid we see this asteroid moves to write this asteroid moves to left and the value of this asteroid is greater than the value of this asteroid the size of this asteroid is bigger than this asteroid so if this true asteroid Collide this asteroid will be destroyed so if this asteroid destroyed will lift with this three asteroid here we see this asteroid moves to right this asteroid moves to left now we see that the size of these two asteroid at the same if these two asteroid Collide these two asteroids will be destroyed so if this true asteroid destroyed we are left with only this one asteroid minus two so we have to written this asteroid now let's see how to solve this problem first second understanding we are given this array of integers in order to solve this problem we are going to use a stack data structure let's create here a stack data structure this each our stack edit structure in our stack we're going to store the asteroid now we're going to iterate over this array from left to right the first asteroid is 5. we see this is positive if we find it positive asteroid we are going to insert we're going to insert on our stack so let's insert 5 let's move to the next we see this is 10 is positive so let's insert on our stack now let's move to the next we see negative if we find it negative asteroid it means that this asteroid moves to lift now we're gonna check the asteroid we have on the top of our stack we see here we have a 10 so this asteroid moves in this direction now we're gonna check first does the asteroid we have on the top of our stack is positive we see yes this asteroid is positive so our first logic we're gonna check the peak if we saw the peak is greater than is zero if the peak asteroid is greater than zero that means the sign of the peak asteroid is positive if you have positive that means this two asteroid will collide we see that this is minus five and this is 10 now we're going to compare the absolute value now we're gonna check should we remove this asteroid from stack or not if we saw the size of this asteroid is less than our current asteroid we see the absolute value the size of this asteroid is 5 the size of this asteroid is thin so if these two asteroid Collide this asteroid will not destroy it will not be destroyed now what we're gonna do are going to move our second condition in our second condition we're gonna check does the asteroid has the same symbol we see the symbol of this asteroid is positive the symbol of this asteroid is negative so we cannot insert this asteroid so if we saw Peak is less than zero we can insert we see this condition is false so we cannot insert -5 here we is false so we cannot insert -5 here we is false so we cannot insert -5 here we can insert minus 5 on our stack if we saw this peak asteroid is having the same symbol we see this asteroid contains positive a positive symbol and this asteroid contains negative symbol so we're going to move to the third condition in our third condition what we are going to do we are gonna chick does when you move to this third condition we are guaranteed that our current asteroid and the top asteroid has a different symbol different direction right so they will collide now what we are gonna do we are going to add this to Value before that when you move to this third conditions we are guaranteed that the direction are different so the two asteroid will collide this asteroid and this top asteroid also we are guaranteed that when we raised this asteroid the size of this asteroid is not greater than this asteroid if the size of this asteroid and if this is negative and if the size of this asteroid is greater than 10 then this astronaut will be destroyed and we have to remove this in our first condition since you reach this third condition so we are guaranteed that the two asteroid has different symbol and this current asteroid is not bigger than the asteroid we have on the top of our stack right so now what we're going to do we're going to check this size if we find out the size at the same if the size or the same this asteroid will be destroyed also this asteroid will be destroyed right since the size are opposite I can check that if we add this to Value it's a minus 5 plus 10 is not zero so the sides are not the same so here we are gonna check if we find out our current asteroid plus Peak asteroid is equals to zero then we have to remove that top you see this three condition false so we don't have to insert this minus by one hour stack that means this minus 5 will be destroyed and we will have this two asteroid at the end we see on the right we have nothing we adapted this we left with this two asteroid we have to create an array and we're going to convert this stack into an array so what we'll get 5 10. so by solving our given array of integers we find out two remaining asteroid they are not colliding each other so we have to written this array of integers this solution will take time complexity o of N and it will takes a space complexity of n for this stack data structure we are scanning this array only once so it will takes of n time complexity for the old sketch it might takes o of 2 in because we are going to apply this condition using a loaf so the overall time complexity is O of n for better understanding let's take one more example let's assume we are giving this area of integers let's create here a stack edit structure let's create here our stack editor structure if you are not a clear this example will clear your understanding here we see negative value right this is negative asteroid so we cannot insert on our stack so what we're gonna do we're gonna check our first condition in our first condition what we do we check the peak if we saw the peak element if the peak asteroid from our stack is a greater than a zero we see a stack is empty so this condition is false our second condition we have to check if our pick if our Peak asteroid is less than zero we see our stack is empty here also we have to check E power stack is empty we have to check this condition empty stack whether the stack is empty or not if the stack is empty we're gonna insert this minus two this is stack is empty so let's insert minus 2 on our stack so we have inserted here minus 2. we don't have to move to the third conditions now let's move to the next we see positive we find if we find it positive we're gonna directly insert on our stack up until this point we see we have 4 and -2 -2 -2 this asteroid moves to left this asteroid moves to right this two will never Collide right now let's move to the next this is positive so let's insert on our stack this asteroid moves to the right at the same speed so this two asteroid will not collide let's move to the next this is negative we see minus 4 negative asteroid right so what we are going to do we're gonna check the pic we see Peak is greater than brick is greater than zero that means positive so what we're going to do we're going to check the value the size is 4 of this asteroid and the size of its asteroid is three so if these two asteroid Collide if these two acetate Collide this asteroid will be destroyed right so we have to remove it from the stack again we have to check this condition using a loaf while this condition is true right now our next condition we see four for his great and Peak and this value is not greater than the size of this at the size of this asteroid is not greater than 4 right equal to 4 but not greater than four so this condition is false our second condition does the peak is less than zero no so it cannot insert minus 4 here and the stack is not empty this we're applying this condition using a loaf right using a while loop you have to apply this condition while this condition is true so our second condition is a false let's move to the third conditions what we're gonna do we're gonna check our current if when you raise this condition it means that two asteroid this asteroid and the peak asteroid this is our Peak asteroid having a different sign right and this asteroid the side of this asteroid is not greater than four so we are guaranteed that these two asteroid has different sign and the size of this asteroid is not greater than this asteroid now what we're going to do are gonna we're gonna check does the size of this true asteroid at the same or not so if we add this current asteroid and this peak asteroid if we find out the value of zero that means there's two asteroid will collide and these two asteroid will be destroyed together since the size of the same we see that minus 4 plus 4 is 0 so this two asteroid will collide these moves to write this moves to left so this two Astrid will collide and this two asteroid will be destroyed so let's remove it we see then we have nothing on the right so we are done at the end we find it minus two on our stack that means we have only one asteroid we have only one remaining asteroid after all the collisions so we have to convert this stack into an array we have to return the array this is how we can solve this problem this solution takes time complexity o of N and it takes a space complexity o of n now let's see the implementation of this algorithm now let's Implement our algorithm first we are going to create our stacked data structure in the stack we're gonna store integer so stack s t calls to new stack now let's run a loop 4 in asteroid in asteroids okay let's copy this let's replace it okay right inside here we're gonna check if we find out this asteroid is positive if we find out asteroids if we find out this current asteroid is a greater than zero if we find it positive asteroid we're going to add that asteroid in our stack so St dot push asteroid else if our current asteroid is not positive then we have to apply our three logic well our first logic we're going to apply using while loop while our stack is not empty stack is empty well this stack is not empty and here we're gonna check our current asteroid we're gonna check that tough acid rate okay so St dot Peak if we find out the top asteroid on the stack if you find out that positive and if we find out the absolute value of our current asteroid is it greater than the asteroid we have on the top of our stack then the asteroid on the top of our stack will be destroyed okay so here we have to check math dot ABS asteroid if you find it this value is greater than is stack dot Peak if this condition is true that means we have to remove the top from our stack because if this condition is true if our current asteroid and that of asteroid if the 12 asteroid and our current asteroid Collide the top asteroid will be destroyed so you have to remove that so St dot pop we're going to apply this condition while we see this condition is 12 stack is not empty and this condition is true our second condition if we find out our stack is empty stack dot is empty or if we find out if our stack is empty or if we find out the top element is negative we can insert our current asteroid when you raise this line it means that we will guaranteed that the sign up or asteroid is negative right sine of our current asteroid is negative so here we are going to check a stack dot Peak if we find out the value that is less than zero that means the top asteroid containing negative symbol so in that case we can insert our current asteroid so stack dot push our current asteroid else our third conditions when we reach this condition we are guaranteed that our stack is not empty and the size of our top asteroid is the size report of asteroid is not less than the size power current asteroid okay so here what we're gonna do is stack dot Peak Plus our current as steroid if we find out the value of zero that means these two asteroid will be destroyed together so here we have to remove that top from our stack this is the core logic of our algorithm when we are done with this aloof we have to convert our stack into array so int answer equals to new int as stack Dot site right below here for INT icons to answer dot length minus one I greater than equals to 0 I minus right inside here answer I equals to stack dot pop okay a right below here we have to read in our answer array this is our algorithm this algorithm takes time complexity o of 2 and for the or sketch for this Loop for the old sketch we might Traverse our array to H uh and it will take the overload time complexities of n right and the space complexity is of n for our stack editor structure now let's run I'll combine this code if we find it an issue will fix let's run it okay so here we have stack it should be s t naught stack Jolly let's run it again I'm sorry for this a little typo we see it passed all the sample test cases okay it passed all the sample test cases now let's submit it we see it passed all the test cases successfully we have solved this problem successfully it takes 11 millisecond if you have any question you can post your question thanks for watching this video I will see you in the next video
Asteroid Collision
asteroid-collision
We are given an array `asteroids` of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. **Example 1:** **Input:** asteroids = \[5,10,-5\] **Output:** \[5,10\] **Explanation:** The 10 and -5 collide resulting in 10. The 5 and 10 never collide. **Example 2:** **Input:** asteroids = \[8,-8\] **Output:** \[\] **Explanation:** The 8 and -8 collide exploding each other. **Example 3:** **Input:** asteroids = \[10,2,-5\] **Output:** \[10\] **Explanation:** The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. **Constraints:** * `2 <= asteroids.length <= 104` * `-1000 <= asteroids[i] <= 1000` * `asteroids[i] != 0`
Say a row of asteroids is stable. What happens when a new asteroid is added on the right?
Array,Stack
Medium
605,2245,2317
1,992
hey everybody this is larry just me going with q2 of dubai weekly contest 60 find all groups of farmland so this one um yeah hit the like button hit the subscribe button join me on discord especially if you like talking about contest problems and stuff like that a lot of good people there and me but yeah so for this one you know uh the farmland and hector land stuff forest land is a little bit awkward but basically you're given all these ones and you're trying to figure out the bounding box for these ones um the a key thing to kind of pay attention to is that they're all rectangular right um and you don't have to decompose anything the constraints and i think i took a lot of time in this problem just mostly reading to be clear about it but basically the constraints are made so that it always is a it's a rectangle um and as long as you kind of as soon as you figure that out then it becomes easier because um i mean i think your immediate reaction should be some sort of flood fill um but and that's basically what i did maybe there are other ways to do it as well but fletchfield is probably going to be the most easy and a tool that is more accessible for you uh as a if you're you know starting out because it is a basic part of just uh just learning algorithms in general anyway okay so basically um for this one yeah uh what i do with flood fill is that i took i you know look a contiguous area and then i just get the upper left and then the bottom right by taking the mints and the max's um and then we're gonna go over real quick uh oh what the hmm i think i saw so i solved one of the other problems in java and now everything is in java never again anyway so today um yeah so this code you know we have we set up the rows and the columns and then yeah uh we this is just very strange stranded standard that first search for fudge fills so if you have issues with that this is actually a good problem to practice but also in fact there's more forms because this should be a very fundamental part of your arsenal you should distribute in your toolkit it should be something that you can do very quickly because everything builds off this well not everything but like a lot of things products anyway so i have um things that we've done this is just a directional up down left right and then this is the recursion but before that i set up the recursion by going okay if this is then that we care about and if we haven't done it yet then we look at the bounding box and this is just the bounding box with respect to min x min y max x max y um i did it in a global way you don't you actually could do this in a in um you know just returning the function but that's not what i did so anyway now you started off with a one cell you know one by one box and then you do a recursion um yeah and then here you basically yeah and then basically now you mark this as done and this is very basic and this is the meat of the work which is that you know we just find them in and then we find the max and then we set it and stuff like that and then otherwise we just go recursively um to these constraints of that it is still i forget the farmland or the other land i forget and that it is not done um yeah that's what i have this is going to be linear time where linear is the size of the input which is r times c so this is of r times c time and of course r times c space and you can really do better than that because of the deck uh because of your that first search because in the worst case it's gonna have uh use the stack space of time c which is linear uh okay yeah that's what i have for this one let me know what you think you can watch me celebrate live during the contest next okay this is so weird okay farmland so one okay so i have to find it once okay i could be in any order okay h okay that is format okay i forgot to mark it as done that took a while yeah thanks for watching hit the like button hit the subscribe button join me on discord especially if you like talking or seeing about these contest forms in a more real time i'll see you later stay good stay healthy to good mental health uh yeah have good problem solving bye-bye
Find All Groups of Farmland
sort-linked-list-already-sorted-using-absolute-values
You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. No two groups are adjacent, meaning farmland in one group is **not** four-directionally adjacent to another farmland in a different group. `land` can be represented by a coordinate system where the top left corner of `land` is `(0, 0)` and the bottom right corner of `land` is `(m-1, n-1)`. Find the coordinates of the top left and bottom right corner of each **group** of farmland. A **group** of farmland with a top left corner at `(r1, c1)` and a bottom right corner at `(r2, c2)` is represented by the 4-length array `[r1, c1, r2, c2].` Return _a 2D array containing the 4-length arrays described above for each **group** of farmland in_ `land`_. If there are no groups of farmland, return an empty array. You may return the answer in **any order**_. **Example 1:** **Input:** land = \[\[1,0,0\],\[0,1,1\],\[0,1,1\]\] **Output:** \[\[0,0,0,0\],\[1,1,2,2\]\] **Explanation:** The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[0\]\[0\]. The second group has a top left corner at land\[1\]\[1\] and a bottom right corner at land\[2\]\[2\]. **Example 2:** **Input:** land = \[\[1,1\],\[1,1\]\] **Output:** \[\[0,0,1,1\]\] **Explanation:** The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[1\]\[1\]. **Example 3:** **Input:** land = \[\[0\]\] **Output:** \[\] **Explanation:** There are no groups of farmland. **Constraints:** * `m == land.length` * `n == land[i].length` * `1 <= m, n <= 300` * `land` consists of only `0`'s and `1`'s. * Groups of farmland are **rectangular** in shape.
The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order.
Linked List,Two Pointers,Sorting
Medium
148
29
Hi guys I am Nishant Chahar welcome back to the channel all group this question which will be discussed in today's video its name is divide to integers so what is given in it yaar given to integers dividend and divisor divide to integers without using multiplication division and Mod Operator The Integer Division Should Truncates Zero Which Means Losing Its Fraction Part For Example 8.34 Fraction Part For Example 8.34 Fraction Part For Example 8.34 Wood B 8 End - 2.7 335 Wood B - 2 Return After Wood B 8 End - 2.7 335 Wood B - 2 Return After Wood B 8 End - 2.7 335 Wood B - 2 Return After Dividing a Dividend by Divisor Note that we are dealing with an environment that could be harmed. 32 bit sci integer jors for this problem if the query is strictly greater than this then return this and if the query is strictly less than -2 re pa 31 then strictly less than -2 re pa 31 then strictly less than -2 re pa 31 then return this Okay so we've got a lot of if elses here first if is That we ca n't basically divide anything we can't multiply anything and we ca n't mode anything ok so can't multiply anything can't divide and can't mod anything let's keep this as ok if we can't divide then divide If it could have been done then it would have been very easily multiplied, even if it could have been done like this, it could have been done by bringing it into some multiplication, basically dividing by divisor and multiplying it would be equivalent to multiplying it right, so it could have been done by mode also. We could, but we cannot do any of these things. Now we remember in childhood what multiplication was, meaning you guys will remember that if we have to take out six, okay how many times will six come, then 2 p 2 is 6 right. What does it mean, 2 in 3 times 6, how was it done, we took it as common, we saved it, we know its value, we know 3, so it becomes 2 in 3, what to do in similar divide, what to do in divide. What happens is that we subcut the divide. Basically, we continue to subcut. If we want to take out 6 divides, what will we do? How many times is this divide happening? 6, 2 - 2 -2 is 6, 2 - 2 -2 is 6, 2 - 2 -2 is happening. Basically, how many times is this happening? Three times. If yes, then zero is coming, so we solve it like this, we have to return the subclavius ​​question, so this is return the subclavius ​​question, so this is return the subclavius ​​question, so this is approach number one, which is brute force, this brute force approach is basic, which came to my mind, this is what came to your mind in childhood. Multiplication Division Read Division is basically multiple times Subx of something Right so multiple times, we will know the subx number of something, how many times we are dividing it, so I hope you have understood the solution, it is important to tell, after this we will We can proceed further. The next approach is that of our left shift operator. Basically, what is the meaning of left shift operator? First of all, let us understand that if we have a number four, it is okay, if we write four in binary, then something like this will come if We would shift left that means, which is its set bit, shift all of them to the left one by one, so this will be 1 and this will come to our, this will come to ours, this will come to similarly at, so what will come to 16 32 What does this mean? Basically we are doing multiply by 2. We are doing nam ko that is what it means to left shift. When we use left shift operator, this is what it means, so this is what we have to do, so we What can we do, we can shift it left multiple times and see how many times it is coming, like for example, first we divided it by six and saw that it is getting 20. Okay, so we shifted it left to 12. It is getting divided by 12. Yes. It is correct, then it is shifted left once more, 24 has come, it must be 244, it is not happening from 24, so we know that it is happening only in this many times, because we have seen in our count that it is happening twice. This is done, now what should we do? What should we do? If we did 12 out of 20 then we got eight. Now we will do the same thing again and see. Six is ​​happening only once. If 12 is see. Six is ​​happening only once. If 12 is see. Six is ​​happening only once. If 12 is not happening then we know this here. Once we get one more count, then basically three will be the answer. Let's try to understand it in further code, but basically we can multiply it by the power of two. How many times can we multiply it by two times? We will calculate how many times we are actually dividing it. What will be the question for that? So first we will put our base case that if the value of dividend is int min and divisor is -1 then return int max. The divisor is -1 then return int max. The divisor is -1 then return int max. The value of dividend is that of divisor. If equal then return one otherwise what will we do We will take a flag if both are greater than zero OK Divisor Dividend then return true if not else return false OK What does it mean if any one of these conditions falls? If any one of these conditions is false, then the miss will be negative, right and if both of them are false, then it will be true. We know this, we do not know that false is true, plus is plus, minus becomes minus plus. Minus plus is basically minus, plus minus is also minus, so we will get true, here basically, we will get true in both of these and in the end, true means whatever is our flag, we will check only this with the flag. That our final answer will be negative or positive, then what did we do, we converted the divisor to unsigned, took the divisor and dividend as the answer, what did we just do in the while loop of the dividend as long as the value is greater than equal to the divisor, that is It is bigger than that as long as we keep doing this thing, okay, we started by taking the value of count from zero, then the value of dividend increased till we shifted the divisor to the right, shifted it to the left, as long as we shifted the count plus and to the left. We are going to keep increasing the count as many times as this happens and if it doesn't happen then we will add to the result how many times exactly we have shifted it, what will be the power of 2, we will see here and finally then We will subtract from the dividend and keep running this loop again and again until our divisor becomes smaller and finally just at the end we will check the flag. Right what do we do once? Let's dry run it once and check it quickly. And we will have a better understanding so let us take the example 10 our dividend becomes three our divisor becomes three currently both are positive so we do not need the above code so what have we done 10 is greater than the divisor yes greater than three If it is 10, we will start the count from row 3. We will check in the dividend that the value of 10 has increased from the divisor. Now if the divisor is the current count row, then 0 + 1 will is the current count row, then 0 + 1 will is the current count row, then 0 + 1 will be 0, so we will shift it to three only once. If we shift only, this is our three. What happens? If we shift once, then we will get 110. What is the value of 110? This is 4 P 2. This will be our 6. Okay, so six will come. Will go 10 is still greater than 6 If there is no problem then we increased the count We made it one What did we do We made it one After making one we checked again Our divisor is three We shifted three twice First 1 It became 0 once and shifted it to 001. It became 1. What is its value? Will it come to 12? So we checked that 10 is gray. The 12 is not there. What was the value of the count. It was the current one. We filled in the result. What is plus equal to two? How many times is one right shift counted? So we shifted one only once. If it was 0 1 then it will become 0 1 0. What is the value of 0 if two is equal to two? So we added two to the result. Now we have added 2, now what is the value of our divisor, now we will subtract it from the dividend. If we shift the divisor only once, then it will come to six, then 10 - 6, what will come is 4. Currently, now will come to six, then 10 - 6, what will come is 4. Currently, now will come to six, then 10 - 6, what will come is 4. Currently, now our dividend. What has happened? The value of four is greater than equal to 3. We have shifted the count from zero to zero. So, one has shifted the twelve one. We have shifted the count only once. We have shifted the divisor only once. Done, the value of the divisor is six. If the value of our divisor is shifted to sis then our final answer will be it will be greater than this four will be less than six so we should not go inside the loop, count plus will not be in the result. We will simply add the result will be plus equal to one right left shift of count left if the shift is zero then it will be plus one basically then our result will be three our dividend will be 4 - 3 that will be equal To 4 - 3 that will be equal To 4 - 3 that will be equal To 1 that will be equal to two and then we will check whether the value of one is greater than th, if not then we will come out of the result. Finally we will check the flag. If our flag is true here then we will return the result in this. The result is our aa. If you understand, then take one more example and try to solve it. Basically, take it positive, it will safeguard us. Whatever we have written above, this entire code will safeguard us that the basic condition. She has given us this condition which has been given in the note, it should be fulfilled once it is submitted and it is accepted so yes I hope you guys must have understood the question, if not then you can put the discussion in the comment section. You can join the discord group to discuss in it and you can download the Algo Prep app from play store and app store and website also in discussion section you can ask this doubt and thank you so much for watching this video and I will see in The Next One By
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
46
hey guys welcome to algorithms made easy today we will be seeing the question permutations from lead code here given a collection of distinct integers we need to written all the possible permutations given the input 1 2 3 we know that we can have these six permutations for the number so how do we solve this the basic idea behind this question is backtracking so what we'll do here is we'll take our example one two three and we will swap the numbers one two and one three so that gives us two one three and 3 to 1. in these numbers we again swap the last two digits as these can be swapped so this gives us one three two here this gives us two three one and here this gives us three one 2 so these will be our six permutations so what we'll do is we'll recursively backtrack and keep generating the permutations for these numbers so initially what we do is we take a list result variable which will be of type list of integers and we will return this result between this we will call the backtrack function in this will pass result our input array and the starting position here firstly we check if start is equal to nums.length start is equal to nums.length start is equal to nums.length if so we will add the number into a result list but the number is an array so we need to convert it into a list so what we do is we will write a custom function which will convert the num zeroing to list in this we will take a list of integer and we will iterate over the nums array at the end we return the list formed now if the start is equal to nums length we added in a result otherwise we will start our loop for inch i equal to start i less than num dot length in this we will swap the numbers so what numbers do we swap p swap i and start in nums then b backtrack with stat plus one and again swap i n star to bring it to the initial position so now we need to write the swap function also take a time variable numbers of i becomes numbs of j numbers of j becomes 10 so that's it let's try to run this code okay so we have got the result let's try to submit the score and it got submitted and it's faster than 100 of the submissions that were submitted online that's it for today see you in the next one till then keep learning keep coding
Permutations
permutations
Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\] **Example 2:** **Input:** nums = \[0,1\] **Output:** \[\[0,1\],\[1,0\]\] **Example 3:** **Input:** nums = \[1\] **Output:** \[\[1\]\] **Constraints:** * `1 <= nums.length <= 6` * `-10 <= nums[i] <= 10` * All the integers of `nums` are **unique**.
null
Array,Backtracking
Medium
31,47,60,77
367
hello everyone today i will we will see one more problem from leeco which is like a valid perfect square so this problem is like we want to define whether the number is a valid perfect square or not so let's look at the question given a positive integer number write a function which returns a true if number is a perfect square else false so in this method in this problem we should not write any built-in methods should not write any built-in methods should not write any built-in methods so let's uh look at the initial way to solve this problem so let's say like we have a number uh let's say 16. so we know like the square root is 4 so 4 plus 4 is 16 so in a typical way like the square root will be always like less than half of the number itself so that is the clue here so we don't want to check the number from um well let's say like one two since it's uh they say like it's a positive integer so we should not start from uh we don't want to check every number right from 1 to 16 rather we will check from uh from the half itself so for this approach we will go with the binary search and in addition to that uh one thing we just want to remember is like we can start from the number two since like uh anything less than two is going to be always true so why the square of one is always one so we will start so in this approach rather than starting from one we will start from two okay so let's go with this approach uh let's okay let me check this one so as i mentioned like we are going with a binary search so in binaural search the key for the key is like let's say we have a text like 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 okay we just want to find plus 16 okay so now what we should do in this case is like we need to because we don't want to share we want to get the right value first as i mentioned earlier like uh what we will do like we will find the right value for that we will go with this uh formula like math right will be equal to math dot flow and half of the number okay so now we have find the right value so we just we know like so with this point we don't want to kind of worry about the rest of the values 9 10 so we will start from here so the initial point so this is my left and this is going to be right now we need to go with the for loop let's say like we need to go with the follow up let's go saying like left less than or equal to right and then we need to find the mid portion for this one so finding on this mid version submit will be equal to left plus i use javascript that's the reason i'm going with this uh my left plus method but if you're using a python or other languages i believe like there you can directly go with the right minus left by two so right minus left by 2 okay so now my mid position will be so we'll check this value so what is the midpoint value here so let me open a debugger tool okay so my let's say my left is two and my right is eight as for the formula match dot flow right minus look okay so now my midpoint is five okay so we so this is going to be a midpoint now what we should do right we need to do like check this conditional condition so whether the m cross m equal to the number or not okay so we need five so we need to say like look again so this is going to be the uh guess square we need to check if this guess square equal to number if it is equal to this number then okay we found we know like okay this is a valid uh let's say here it is 5 so 5 cross y is 25 so we need to compare 25 against 16. if it is same then uh obviously it is not same so what we need to do is like we need to go with one more logic condition like so k square is greater than the number yes so now the guess square is obviously greater than number so in this case what we need to do right we need to shift our right uh we need to change the opposition on the right so currently the question of right is eight so what will we have the right person will be like right is equal to mid minus 1 we already know the mid is 5 so now submit is 5 so the right portion will be 4 now and again we need to go for this for loop so in this for loop and we have one more condition like if guest square is less than number so if it is less than this number then we need to say left will be equal to mid plus 1 so these are the conditional checks so based on this check we will come to know whether the number which you have passes the input is a valid square or not let's dive into the real time problem code itself so what we will do like so the first case is like we just want to take a consider the value from the number 2 positive so let's say that if the number now we are going into this while loop first we need to check this left i think the left has left as 2 and then so we are getting his formula right match that flow numb by okay so now we'll go over this now we need to i take this uh values from two to eight so left less than equal to right now we need to find the mid value so make sure the formula for mid is left plus math.floor right minus left by left plus math.floor right minus left by left plus math.floor right minus left by two so left plus mass star flow right minus left by two okay so now we just want to say that let guess square or we can say like uh guess square equal to mid cross mid okay now we select if yes square equal to num then return true r else if then the conditional check is like we need to set our right uh to mid minus one so now right will be equal to minus one and here okay square let's start now then move the left mid left equal to okay let's run this code so some diamond set x error if k squared equals equal to number let's see the syntax on line 22. okay so since it is we don't want this one okay true now let's put the let's do the manual testing here like test case 14 from the course false let's submit score yeah so this is the right one and here the complexity of this problem time complexity is like uh oauth logan yeah probably like in the next upcoming videos i'll try to show more problems on the uh building with more binary such problems once again thank you for watching this video if you have any questions please share your comments in the comment box if you have any feedbacks or any suggestions that's it please share it on the comment box thank you thanks for watching this video i
Valid Perfect Square
valid-perfect-square
Given a positive integer num, return `true` _if_ `num` _is a perfect square or_ `false` _otherwise_. A **perfect square** is an integer that is the square of an integer. In other words, it is the product of some integer with itself. You must not use any built-in library function, such as `sqrt`. **Example 1:** **Input:** num = 16 **Output:** true **Explanation:** We return true because 4 \* 4 = 16 and 4 is an integer. **Example 2:** **Input:** num = 14 **Output:** false **Explanation:** We return false because 3.742 \* 3.742 = 14 and 3.742 is not an integer. **Constraints:** * `1 <= num <= 231 - 1`
null
Math,Binary Search
Easy
69,633
1,512
Hello everyone, welcome to my channel, there will be many good purchases, right from the beautiful to the best approach to the question is quite simple, I have given you an integer number, count the number and tell me how many are good by the first few words. What does it mean? Okay, so how many more forests are there ahead, how many bands will there be, make one on this and make one on this, okay, now let's move ahead, look at this is you ahead, no one else is visible, if you are not, then some. It didn't happen here, there are three, look, this 3 has become one plus one, so one has got one more, okay look at this one has made one leg, okay this one has one plus one, right, this one has become plus one. Okay, now when I came here, there is no one else here, there is no more one, there is 3, there is no other 3, okay, so look at my answer, it is four, okay, so we just have to do the account, so the most simple and brute force method which is In approach one, I will tell you it is very simple, whatever you tell me right now, just like I am standing here, I will start IK with I plus one, like it will start, okay, how many more ones are there, is this one, no, this is one, okay. So I have added OnePlus to my account, okay then this next big one, is this also one, yes, I got it on another one, okay, so on two, I got it from here, when I got this one, I was on this one, okay, now I have come here, now I Where will I start from I Plus One, I will start from here, I will look for you here, you are not here, okay, so I did not find anyone for this you. And similar, you did not find it, I came here to move ahead, it will start from here, it is three, no, it is three, yes, I found it on one, ok, similar, now I came, it will move forward, it will start from here, will it start from both? Yes, I have got one more, then yes, what is bigger than both, I have come here. Will it start from here? Is it from both? No, I have come here, so after this, I cannot go, it will be auto-banded, so I have come cannot go, it will be auto-banded, so I have come cannot go, it will be auto-banded, so I have come till here. Will we take it till here only and till -2 is ok, it will always start from I plus one, so -2 is ok, it will always start from I plus one, so -2 is ok, it will always start from I plus one, so look at our answer, if we go to four A, then this is a very simple code from root four, is n't it, we will write a loop on double, ok. But from i = 0 to i &lt; n - 1 ok. But from i = 0 to i &lt; n - 1 ok. But from i = 0 to i &lt; n - 1 i plus is fine and where will k start k will always start after i because see when the legs meet when i &lt; s then k will always start after i. when i &lt; s then k will always start after i. when i &lt; s then k will always start after i. Okay, so I will keep adding plus in my result, this will be our answer, so this is our simple approach of n² and this will also be accepted because our constraint is very small, so approach one is completed here. In approach one, right was done in off n square. Now let's see in off n. So if you see, you have to make a square by picking up any two elements and making a leg. So if you store which element how many times. It's like this, it's one, it's like that, it's like this, one, two, three, make it one, it's like that, it's like this, it's one, it's like this Meaning, which is equal to it like one and everywhere else, one is visible here, it is visible here, only then can it be made, when it is similar, then look at the value of tu like this, if there is one, then it can be made. It is not possible for us to do our work, so we need to make legs, like this is four, neither is four's but four, total four is one, right, total four is one, if we have to make it, then how many ways are there to make two sardines from each four? Are out of four elements, so like here you can do 1111, you can love this, three ways are found there, okay then you will not do this with this again, you have done this before, you will not do this again. If you had done this then you can love it again, then what result did you get? This equal was zero in the beginning. Look here the frequency is four, so 4 * 4 - 1 / 2, how much did it go? 6 1 * 1 - 1 so 4 * 4 - 1 / 2, how much did it go? 6 1 * 1 - 1 so 4 * 4 - 1 / 2, how much did it go? 6 1 * 1 - 1 / 2 how much? Got it 0 1 * 1 - 1 / 2 This also got the / 2 how much? Got it 0 1 * 1 - 1 / 2 This also got the / 2 how much? Got it 0 1 * 1 - 1 / 2 This also got the answer 0 What is the total, it is six, this was my answer, ok, this question was quite simple, this became our second approach, time compactness is off in this but look at the space complexity. It has become off because we have stored the elements in the map, this is our map, okay, but pay attention to one thing in this, what is the problem in this, isn't it that you once traveled on this entire area and then put it in the map, then it is okay. Again hit travel on this map of yours so that if you can find out this then two are fine, let's see that too, it is also very good and is a very simple and clean code, see they come in the third every day, we will show you by doing this, time complexity is off. No space is completely still off and other is off because of the map. It is very simple. In this, I thought like let's go to mother, you are standing here, stand here, let's go to mother, you have just come, see 0 1 2 3 1 in this index. If there are one, two, three people, then this one will become one on three, if I were here then how many people can this tu fall in love with, before this we have seen how many tu, two have seen one, then two will be able to become first. It is second, it is third, it is fourth, it is fifth, it is fine, I am here, so I have seen a forest nearby, I have not seen it because that forest is not there in the map, it is fine, no problem, there will be no addition in the result, simply zero in the result. It got added because I saw one nearby otherwise even the foot band would not be available but now I just saw one so I will update it. This is my number and this is the frequency. How many times have I seen it, okay now I have come here. Have you met me, have I seen you nearby? If not, then it doesn't matter. Add zero and put tu here and its frequency has become one. Okay, now I have come here, now look, pay attention here, this is you, isn't it currently? How many times have I seen you before this, look at the map and you will know that you have seen me once, then add the value of the frequency as per the value in the map, so that it can be made on such number of times, if you get relief twice before, then you can become love with it. Now we have seen it only once, so it became one, so pay attention to the value which is there in the map has been added, because there was one frequency, it will become one, so I have added one, but now I have added only one frequency. You have seen one more one, here it is, so the frequency of this also needs to be updated so that if someone comes in the future, there should be a correct pregnancy for that person, right, then look, now there is one here, so how many runs have I seen before this, it is here. Okay, but now I will update it. Total two one for future. Now I have seen it. Look, one or two. Where will you know? Look, you will know from the map. If you have done plus, look here. Pay attention, one leg is important, right? This one is plus because I have seen another one, so here I have made one three, so that if any one comes in the future, it will be 3. Now look, again one has been made, how many are there next to it? One, two, three becomes one, from here we got to know that three are plus three, we made it three more, new ones will come, okay and we will have to update it, we made it four, now you have come here, I can see how many of you are there in the paste. See, I see in the map, two, you see, correct, this is two, one will become one from this, then plus you, and update its frequency here, make it 3, its value is fine, but it is quite clean because We have done our work in one single driver. Okay, so let's quickly code all three and finish it. So let's quickly code it and finish it. First of all, the question is zero, then enter, it was equal to zero. I started it &lt; Looking at Let's take the ordered map, it's comma, it's okay, this is the shortcut way of writing here, I am adding plus to everyone's frequency, so your frequency is getting added here, okay, the code will be from, okay, this is my frequency in the getup link. Now take out the variable named result, okay, the second towel is in the map, first I updated it in the map, okay in the result, we should also submit this, but eat and name in Namas, okay, look, first of all, what will I do that There is also the result, whatever is my number, if I have seen it nearby, how many times have I seen it will be added here. If it can be made so many times in the result, then I will get from MP of N, how many times I have seen it nearby. It's okay but now you will have to increase its frequency too MP off plus so that you do n't get updated MP off for the next time, okay don't do anything just add the result in the last, you see how simple and cleanest the code was, isn't it more clear than dry iron? That's why I explained it directly to you in the comment area video. Thank you.
Number of Good Pairs
design-underground-system
Given an array of integers `nums`, return _the number of **good pairs**_. A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`. **Example 1:** **Input:** nums = \[1,2,3,1,1,3\] **Output:** 4 **Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. **Example 2:** **Input:** nums = \[1,1,1,1\] **Output:** 6 **Explanation:** Each pair in the array are _good_. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations.
Hash Table,String,Design
Medium
2285
70
all right so we have about 220 videos to go we've done about 30 videos if you have not checked out the github check out the github I have not been that good with code samples my first videos don't have code samples but I think it's very necessary for learning to have clear code samples well named well commented for teaching purposes in my opinion I don't really like comments and code because when code changes the comments won't change but anyway also I will be gone for about four or five days I'm going to be in Germany visiting a friend and I hope to make a video there as always if you have not already subscribed to the channel subscribe to the channel I'm trying to make this the premier resource the one of the best resources for preparing for software engineering interviews obviously I can't build like a brand or thing likely code or like geeks for geeks because they're huge websites they control the infrastructure that dominates this space of prep and all the information that we learn from but I want to make a vast resource with tons of helpful videos with clear explanations to make this process a little less hellish so let's get into our problem climbing stairs and I'll see you later ok so today's question is climbing stairs this is a fundamental dynamic programming problem all about sub problems always all well supper-table problems always all well supper-table problems always all well supper-table looming and what the question asks is if I'm given a certain amount of steps to traverse if I need to jump three steps i if I only can take a one step and a two step how many ways or how many unique ways are there to climb the stairs so if I have to traverse two steps what I can do is I can take a one step and on one step that adds up to two steps or I can just take my two step I can just do the two step and then I've gone two steps if I have to traverse three steps upwards I can go a one step that is three steps I also can do a two step and then on one step or I can take the one step first and then do the two step that's how they do three steps if I need to do four steps the number of unique ways is five what are the like I take a one step or one step and a one step I could take a two step and then a one step or one step I could take a one step the two step and then the one step and then I could take one and then used to as the final step finally I could just do the two step and that adds up to four steps so how are we going to approach this problem as always too short take it away then we will have to use Johnny and chromatic to solve this what you need to understand about this problem is I if you've done this problem it's simple but if you've never seen this problem before what do we need to ask ourselves how do we need to think about this we know this is dynamic programming because yeah the title of the video said that and the thumbnail said that but how would you approach this in an interview so first I would ask you what does it mean to take a certain amount of steps from a certain point what does that mean what does that do to our overarching problem and how can we relate those reductions to subproblems to a global answer so okay stay with me what I want to do is look at the top-down approach to do is look at the top-down approach to do is look at the top-down approach and then we will see why we need to use dynamic programming okay so what we're gonna do is we're gonna do the top-down gonna do is we're gonna do the top-down gonna do is we're gonna do the top-down approach no memorization at all we're going to see why we need the memorization but I need to take six steps all that we need to understand is what is my choice in reduction of subproblems so every step if I take a one step or a two step no matter what I do if I'm at a certain position what can I do I can take a one step or in two step here's what happens if I have six steps to take and I can take a two step and a one step the answer to the subproblem is going to be the sum of the possibility trees what those yield if I take a two step or a one step if I take a two step we branch what does that look like if I take a two step that means I have four steps left to take if I take a one step that means I have five steps left to take let me label these so the answer to six steps the total ways to make six steps is the sum of the answer between the total ways to make four steps and the total ways to make five steps so this is the intuition what we're gonna do is every point we're going to express the two possibilities we have and what we're gonna do is we're gonna keep reducing when we get here we're gonna have base cases our base cases is we know the answer when I have 0 steps to take how many ways are there to step there's one way we can do nothing if I'm negative how many ways are there to make those steps there's zero ways those are our base cases F of 0 and F of negative a number so what we're going to do is we're gonna keep reducing we're gonna keep expressing our decisions and go down in this tree until we reach our base cases and the lower gonna see is our base cases know the answer they're going to return us up they're gonna give us knowledge and on the way back upwards will start having answers and I want you to follow me just stay with me for this so at the four sub-problem I have this so at the four sub-problem I have this so at the four sub-problem I have two choices do a two step or a one step let's exercise both choices so if we take the two step at the subproblem for we're going to know that the answer to so problem 4 is the addition of if we took a 2 step if we took a one step remember 4 minus 2 4 minus 1 so what we do is we add those and now we can express our decisions for the five step so remember our code is going to go depth-first we're going to solve all depth-first we're going to solve all depth-first we're going to solve all these subproblems down here before we get here we'll see how that plays into memorization so right here five let's take our two step in one step so the answer to the amount of ways we can make a five step is the some of the ways we make 3 step and the waves we make a 4 step so do you see how eventually we're going to converge to a solution these sums will do themselves as we're coming back up and then we'll have the answer for overall call so what we need to do here is we need to break down the two step so the answer to the two step is the sum between if we take 0 steps and if we take one step so the thing is we see up a case here 4-0 we already know the answer case here 4-0 we already know the answer case here 4-0 we already know the answer to this so the thing is this zero is just going to return those we went to return to our caller the amount one because the amount of ways we can make zero steps is one if we can take one or two steps we return one so after we return one okay that's great so now let's break down the three and now let's break down both of these guys and notice 3 - 2 3 - 1 4 - 2 4 - 1 so and notice 3 - 2 3 - 1 4 - 2 4 - 1 so and notice 3 - 2 3 - 1 4 - 2 4 - 1 so that's what we're doing 3 - 2 3 - 1 2 - that's what we're doing 3 - 2 3 - 1 2 - that's what we're doing 3 - 2 3 - 1 2 - 2 - 1 we're just expressing our 2 - 1 we're just expressing our 2 - 1 we're just expressing our decisions at you 2 point and that's going to build up to our global answer so what we need to do here is let's break down these levels further again we're going breadth-first this is not we're going breadth-first this is not we're going breadth-first this is not how the code would do it would go down this tree first we can either take the one step first through the two stuff first it doesn't matter so what we're gonna do is we're gonna break all of these down further alright and so now we see that we've broken down it a little further we've taken our two step we've taken our one step so now we see we'd have a ton of base cases that panned out here a ton of base cases turned out to happen so if we go negative we know that the amount of ways is zero so what we do is we return zero upwards and let me get rid of those plus signs for readability because we get the point now that it's in addition so what we need to do is return 0 this returns zero because that's this base case so this zero returns one because the amount of ways we can make zero steps is one way we do nothing and now let's fill out all of our other base cases and what they return and I want you to notice a lot of these base cases have panned out when we go negative we return zero when we get zero we return what as you can see but we still no more so problems to solve so let's go through our final tier and again we'll see why this is very bad and inefficient until we memorize it so let's continue and finish off these subproblems like these wands in these twos okay and so we want to do is we panned out all of our base cases so let's do what all these base cases will yield if we go negative we return zero there's no ways we can make negative steps if we need to make zero steps then the amount of ways to make zero steps is 1 we just do nothing so now let's pan out all of these base cases and you see this recursion returns upwards we keep going what's the answer we ask another call we ask it can you give me an answer can't give me an answer to keep give me an answer until we have an answer when we have an answer they go backwards they're like hey I have this answer and then the guy who just got his answer he's like oh wait yeah let me calculate my answer he tells it to the guy above it so this is going to go upwards and eventually we'll get to our top solution here so what we need to do is let's show all of our base cases returning so now what we do is let's do our addition upwards so the subproblem answer for one is zero plus one so the answer is one returns one so everywhere that we see a one answering we can return a one because we know the answers to subproblems one the code would actually do it let's just do it for speed sake and so now we see the answer to the to sub-problem is one plus answer to the to sub-problem is one plus answer to the to sub-problem is one plus one the answer to two sub problem is two so now let's go through the whole other tree and fill that out and you see how all of these returns are slowly building us upwards so now the answer to the three sub-problem we're going to need three sub-problem we're going to need three sub-problem we're going to need that for the four so problem the answer to the three sub-problem is 2 plus 1 to the three sub-problem is 2 plus 1 to the three sub-problem is 2 plus 1 which is 3 so the answer to three sub-problem is 3 so the answer to three sub-problem is 3 so the answer to three sub-problem is 3 let's return that upwards all right and so now let's finish off the other 3s and get them to return 3 and this is a critical realization on when you make do you see how the four sub-problem has its you see how the four sub-problem has its you see how the four sub-problem has its answer do you see how this four sub problem is over here and you see it was three sub-problem three sub-problem three sub-problem three sub problem we're gonna look at that shortly but let's finish this so two plus three is five so the answer is to force our problem is five so let's fill out this four sub problem so now we have the answer for if we took a one step so what we need to do is we need to finish off this five the answers to the five sub-problem is three plus five which is sub-problem is three plus five which is sub-problem is three plus five which is eight and I've not even checked this but the answer to the sixth sub-problem is the answer to the sixth sub-problem is the answer to the sixth sub-problem is going to be 13 let me double check and excellent so the answer to the sixth sub-problem is 13 I just ran the test sub-problem is 13 I just ran the test sub-problem is 13 I just ran the test case on it so what we notice is first off I'm gonna establish yes this is like the Fibonacci sequence because we're doing step to step we're looking one behind us and two behind us but aside from that what we notice is that we are duplicating subproblems and when you in a notice in a depth first manner we're going to go down here and solve all these subproblems I will have the answer for the zero sub well I'll have the answer for one I'll have the answer for - I'll have the answer for three I'll - I'll have the answer for three I'll - I'll have the answer for three I'll have the answer for why am i answering - over here why am i answering - over here why am i answering - over here why am i answering for why am i answering one why am i repeating subproblems in this tree so the problem is this code runs in exponential time it runs in this code runs into to the and time why is that onion memorize what we're going to do is at each of these nodes we're going to definitely make two four kings we run it forth twice so there were depth of the recursion tree at maximum juicy subtract 1 the depth of the recursion tree is going to be 6 it's going to be if we subtract it or 1 each time we're going to add a depth of 6 on this tree so the bound upper bound on time is going to be 2 to the N is this an exact count no it is not an exact bound but we can upper bound the time by using that to knowledge we know that it's going to be upper bounded by 2 to the N and the problem is we're repeating subproblems so this is where memorization kicks in so the problem is when you're noticing guess what when I go depth-first I'll guess what when I go depth-first I'll guess what when I go depth-first I'll have the answer to the for subproblem what happens is this whole subtree but you see all this work that we're going to cut out for the four sub-problem to cut out for the four sub-problem to cut out for the four sub-problem let's cut it out right now did you see that do you see how huge of a chunk that ate up of our tree by not following the floor path because I already know the answer is 5 to the 4 sub-problem I literally saved myself all sub-problem I literally saved myself all sub-problem I literally saved myself all that work because I know the answer but there's another thing we know the answer to the three subproblem it's 1 plus 2 is 3 so why am i doing that again I'm not going to do it again I'm going to cut this whole subtree out so let's cut it out right now so do you see here do you see we just remove it's amazing how much work you can save by knowing the subproblems you already answered and again here we're gonna go to death first Manor will already have the answer for the one sub problem we won't need to solve it here so let's cut that out right now when we're here we're also going to have the answer print two sub problem we won't need to know the answer for the two so problem down here let's cut that out right now so this is root three sub problem is going to have the answer for the one sub problem it's going to have the answer for the two sub problem that it needs so the thing is this is roughly how our recursion tree will look like I'm not totally sure if this is completely right but I want you to understand what we just did that was memo-ization I can't erase this because memo-ization I can't erase this because memo-ization I can't erase this because now we're using them why is it you do you see how many calls we just destroyed do you see how much of the time we just saved that is what memorization is about I'm a huge fan of top-down approach for I'm a huge fan of top-down approach for I'm a huge fan of top-down approach for dynamic programming I love how intuitive it is and as long as you memorize it's a good way to go about these problems so now let's look at to the bottom-up approach and the reason is bottom-up approach and the reason is bottom-up approach and the reason is bottom-up is we start from the bottom-up is we start from the bottom-up is we start from the bottom and then we work upwards towards the answer so we're going to see how that table pans out right now so now let's look at the bottom-up approach so the look at the bottom-up approach so the look at the bottom-up approach so the each of these cells whenever we're doing dynamic programming tables every one of the cells all they mean is if I'm taking zero steps how many unique ways can I take steps if I can take a one or two step if I need to make three steps how many unique ways are there to make three steps with one and two steps and our original question if I need to make six steps how many unique ways are there to make six steps were the one at a two step and Java a table has initialized to zero all of the values of zero in the air so we can just give it that so we're going to be solving through until we get our subproblem six so what we need to do is the answer to the subproblem six is like we just did the answer to the subproblem of five if we take a one step and the answer to the subproblem of four if we take the two step these some of those is going to be the answer to subproblem six same thing we did we're just going to bottom up this time what we're doing here is the same thing as our top-down here is the same thing as our top-down here is the same thing as our top-down approach we're just going to start from the bottom with what we know are base cases the amount of unique ways that we can take a one or two step and make zero steps is one we do nothing and the amount of unique ways to make one step with the one and two step is just taking the one step so what so this is all we need two base cases in order to solve this table because this tables going to rely on two previous values so this cell if we take a one step we get one if we take a two step we get one so one plus one is the answer to the sub-problem two which is the sub-problem two which is the sub-problem two which is now two so all we did is take the addition between it we took a one step and we took a two step addition of these subproblems so again the answer to the subproblem in three is the addition of if we take a 2 step 3 minus 2 is 1 if we take the 1 step 3 minus 1 is 2 so now addition 2 plus 1 3 and yes we could do this in constant space but I just want to do it like this so that you can see how we fill this out and how the subproblems span out do you notice how every time all we care about is the 2 previous items this means we can just use costs and variables we can just use local variables to keep this because it makes it more clear for teaching purposes so now the answer to the 4 is going to be the addition of the third and the second subproblem why if we take a 1 step 4 minus 1 is 3 take the 2 step 4 minus 2 is 2 addition so now 2 plus 3 is 5 and so now the answer to our five sub-problem three plus five is eight and sub-problem three plus five is eight and sub-problem three plus five is eight and now the sixth sub-problem is the now the sixth sub-problem is the now the sixth sub-problem is the addition take a one step take a two step take a one step take a 2 step the addition is going to be 8 plus five 13 and so that's it that is the bottom of approach so all we do is we add the previous cells because the answer to this subproblem is the addition of these two subproblems and our base cases allowed us to answer these we ripple down the array and we finish and we get our answer which is 13 so this is how this problem is done the reason this is easy dynamic programming is because the subproblems are fairly easy to break down it's kind of difficult to understand this at first and once you really see how this works it becomes very straightforward so now let's look at the time and space complexities of both solutions so the time and space of both the top-down and time and space of both the top-down and time and space of both the top-down and bottom-up approach bottom-up approach bottom-up approach to be a Levin the n is the total stairs to climb if I need to climb six stairs that means these are going to be my balance so the reason that are top-down balance so the reason that are top-down balance so the reason that are top-down approach the recursive approach is o of n space is because of our call stack we're going to have to use o event space and also we're going to have to store and sub problems the reason that our bottom-up approach is o of n space is bottom-up approach is o of n space is bottom-up approach is o of n space is because we keep that table with n plus 1 subproblems if you count the zero subproblem call it n doesn't matter we scale linearly in space we can do this in constant space we could do it in constant space because all we care about is the previous two items so for the bottom-up approach we can do in constant bottom-up approach we can do in constant bottom-up approach we can do in constant space but for the top-down space but for the top-down space but for the top-down our upper bound is going to have to be O of n on the space because of a recursion even if we get rid of that table we're still gonna have the recursion if we somehow we're able to keep track of the two previous items for the time complexity the reason it's o of n is because for memorization were only going to solve up to n subproblems after that we'll have constant time knowledge of the answer to a subproblem so we would never go past that our bound is going to be the bound on the amount of subproblems we have to solve and for the bottom up pretty straightforward we just go through an array with n plus 1 entries and that's why it's relevant time for the bottom-up so this is this time for the bottom-up so this is this time for the bottom-up so this is this question if this was a clear explanation if this helped you understand things better then subscribe to the channel like this video my goal is to make this a premier resource for software engineering interviews and people learning this stuff I understand that this is not exactly the most practical stuff in industry so we really need a great resource to study this off time when we need to interview because it doesn't always correlate to what we're doing during the day so that's all for me and I hope
Climbing Stairs
climbing-stairs
You are climbing a staircase. It takes `n` steps to reach the top. Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top? **Example 1:** **Input:** n = 2 **Output:** 2 **Explanation:** There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps **Example 2:** **Input:** n = 3 **Output:** 3 **Explanation:** There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step **Constraints:** * `1 <= n <= 45`
To reach nth step, what could have been your previous steps? (Think about the step sizes)
Math,Dynamic Programming,Memoization
Easy
747,1013,1236
141
hello everyone welcome to my channel coding together my name is vikas soja today we will see another lead code problem that is linked list cycle so we are given with a linked list and we have to find the cycle in it so what is a cycle if the same node is repeated the sum node in the list can be reached Again by continuously following the next pointer if the same node is I treated again or twice then it's a cycle so if you see in this example we went from three to two to zero to minus 4 and then again we are going to 2. so it's being iterated twice so that's why it's a cycle so let's see how we can approach this problem so we will use points cycle detection approach or we what we call this low fast approach so what will happen first we will initialize start and fast 2 3 so what we will do we have to do slow we have to uh increment by one step and fast increment as two steps right so if you see if you have initialized fast and start to three now in the next iteration slow will point to this flow will 0.22 and fast point to this flow will 0.22 and fast point to this flow will 0.22 and fast will point to 0 and again in the next iteration slow will point to zero right and first we'll point one two here by following this path so right slow we have to increment one step and Flash fast as two step now again slow will point to here and if you see fast was there so one two first we'll also point the slow pointer so now when fast is equal to slope will return true right so in a circle if someone is running with speed X and the other guy is running with 2x so they are bound to meet somewhere in this track right they are bound to meet so the same fashion the slow and fast if they are moving one is moving with a speed X and the fast is moving with speed 2x then they are bound to meet if this if the path is a cycle right so let's see the code we initialize our slow and fast Pointer while fast not equal to null and fast dot next not equal to null will do slow is going to slow dot next will increment one step and fast as two steps if slow is equal to fast then we'll return true else uh what when the loop is over will return false so pretty simple code so let's run this solution yeah test case of passing so hope you like this video if you know if you like this video please share and subscribe thanks for watching bye
Linked List Cycle
linked-list-cycle
Given `head`, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**. Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** false **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Easy
142,202
1,650
hello everyone let's take a look at lowest common ancestor of a banner tree three okay for this problem let's take a look at the problem description since it's a log question so given two nodes of a panel tree p and q went to return their lowest common ancestor let's take a look at definition of this node it does not only have left and right node it also has a parent node so it's very helpful here in the first example ps5 curious one so lowest common ancestor is not three in this example ps5 q is four so lowest common ancestor is five okay let's take a look at constraints so p and q exist in the queue and p is not same as q okay so some similar questions previously for example nicole 236 lowest common ancestor of bankruptcy one and leeco one six four lowest common ancestor for banana tree two so um some very similar questions if you haven't practiced those two problems you can take a look and solve them first okay for this problem so let's take um we can come up with a solution very quickly for example for node um let's say we need to find the lowest common ancestor of six and four so let's start with six first we can put six and the audience ancestors into a hash set then we can start with another node four like uh it just travels from yourself saying finance parent keep iterating its parent as long as one parent exists in my hash set will just return the first parameter node that existed in my headset so for this solution we know the time complexities of log n and space complexes or log n of course this average case in some cases uh my tree may maybe like degraded into like several linked lists which means um like we don't have many other nodes the tree is not very evenly distributed we just have some very long uh subtrees so it may become all an okay let's take a look at another solution so for this problem it's very like that we have two linked lists and we need to find the first common node if they have interactions right so all these nodes like zero one eights are useless here so we so in our mind we don't need to think about them okay so it's like we have two link lists and it's the interacts at five and we need to find this node five okay one solution here is that uh like we can calculate the length force then for the like for the longer node which can just um we know that for no six and the distance is two from this node to root and for node four the distance is three so we can just uh make node four like um go one step first then each of um social can like finance parent and as long as they have the common parent we can just return but another solution here is uh that um we can try to think about the simple case first so we have node four and no six in each iteration we move them to their parent so when they're five we find the two nodes are same so we can just retain it a complex case is here in this case let's think about that the distance from node p2 com node is l1 the distance from common to root is l2 the distance from q to com node is l3 so if we start from node p note p goes to root note first when it's uh reaching the root note we place p at q then actually to go to common node we know the distance is l1 plus ao2 then pass l3 for node q we do something similar we ask node q like to go to rule node when it's reaching the runer we place q at node q node p then ask it to come to tom node so the distance is l3 plus l2 and plus l1 we find the distance assumed so if they work in this way finally they will meet at this comp node right so the code look like this uh we initialize a to node p when initialize p point to node q then uh each step they just go to their parents like for a if it's reaching num pointer which means uh it goes it reaches roots then we update it to its parent it's non-pointer then if we find it's a it's non-pointer then if we find it's a it's non-pointer then if we find it's a noun pointer we place it at q similar like for node b if it's non-pointer we place it at b if it's non-pointer we place it at b if it's non-pointer we place it at node p so at last if say our 0 becomes the same node like at least uh when we iterate like l one plus l two plus l three times they will finally meet and they will meet at this comp node okay so if a and b are same we will work this while loop and we just return a so time complexities is log and of course it is on average in some cases like the tree just like this it's just like very too long linked list is a time complex it will be something like a login instead of log n become owen okay that's it see you next time
Lowest Common Ancestor of a Binary Tree III
find-root-of-n-ary-tree
Given two nodes of a binary tree `p` and `q`, return _their lowest common ancestor (LCA)_. Each node will have a reference to its parent node. The definition for `Node` is below: class Node { public int val; public Node left; public Node right; public Node parent; } According to the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor)**: "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow **a node to be a descendant of itself**). " **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1 **Output:** 3 **Explanation:** The LCA of nodes 5 and 1 is 3. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4 **Output:** 5 **Explanation:** The LCA of nodes 5 and 4 is 5 since a node can be a descendant of itself according to the LCA definition. **Example 3:** **Input:** root = \[1,2\], p = 1, q = 2 **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 105]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` * `p` and `q` exist in the tree.
Node with indegree 0 is the root
Hash Table,Bit Manipulation,Tree,Depth-First Search
Medium
1655
1,646
hello everyone today we are going to do another lead good problem and its name is get maximum in the generated array so let's be clear we are given a generated array so uh we have given a pattern by the question Setter and it is like the value at the 08 index 0 index is 0 at the first index it is 1 and other the pattern are given and we have to make an array with the help of that pattern so let's firstly read the first line of the description you are given an integer n so we are already given integer and we can see in the code and a zero indexed integer array nums so zero so the array the indexing is starting from 0. and the length of the array is n plus 1 so it's a point to be noted that we have to generate an array of size n plus one so what will be the index the last element index it will be n because we have n plus 1 as the size and the last elements index is always the size minus one so it will be n so firstly we will pass these two cases we will simply have a if condition if n is less than 2 then we will simply return the value of n okay so I think you got this point because if the uh if the compiler we will enter 0 it will return 0 and if the in the case we will getting 1 the compiler will turn us one so simple we are just passing these cases and now the real game is uh we have to go into we are going to start the real game so we are given here nums of 2 into I so what is 2 into I it's a e one integer or we can say it is a r these are the even indexes of the array so what it can be nums of two it can be 4 it can be 6 it can be eight it can be ten till n so what we are given is Let's see we will I will take at index 4 what will be the value firstly it's it will be equal to nums 2 into I so what will be the I here I will be equal to 2 and numbers of 4 will be equal to nums of 2. so here we're witnessing that the value of the value or the data which is present at the even index of that array is equal to ah to the value which is at its half so we can firstly we have to uh like a declare an array so we will declare it nums and here people often make mistakes here it is written the length n plus 1 so we will declare n plus one so yeah then we will initialize the values at 0 index and the first index it is 0 and for one it is one okay so now we will run a for Loop uh we will initialize it to 2 because we have already done zero and one we will initialize to two and then we will run it till n y n because the size of the integer is n plus 1 what will be the last index it will be n and then we will uh take the condition it will be I plus 1 so yeah so what we will do is firstly we will identify La uh just I have just told you that it is half of the index so the value at present at the index or the index in index by 2 are equal so we will simply write the nums at ith index I am considering it even is equal to the value present at by 2. at half of the index so here we if we initialize it I is equal to 4 it will be equal to 2 so here we can also see the present like the index for 2 is equal to 1 and at the four it is equal to 1 so yeah uh I think we are satisfying these cases and then we will move further so what is the next condition it is nums 2 into I Plus 1. yeah so how we'll do this so it is actually they are representing what the represented is in even integer plus one so what are they representing they are representing odd index so what we will do is uh they have these are like 3 5 7 9 and it will go further like this so let's take nums of three what it will be equal to 2 into 1 plus 1. and what will be the I here I will be 1 so yeah so the I will be 1 here and uh it will be equal the nums at the third index will be equal to I and what we are given here we are given I plus 1 so what it will be nums of two so here we can see this pattern the whole data of the array is depending upon the previous values the values of nums of 0 1 the 2 is depending on zero and one and like this the 3 is depending on one and two and like this we are getting the whole array so for odd we are like in the small classes also we all know like if you are familiar in that type of coding that the odd mod 2 is equal to one so we will simply apply this condition if I mod 2 equal to 1 so when it will be satisfying when the I will be odd so what will our Norms of I become it will become C numbers of I here is now I by 2. so we will not write it again we will just simply initialize it with I because it's already I by 2. and what will be the next case it will be I plus 1 so we have followed this one and now we are focusing on this so it will be nums of I by 2 plus 1 so I am just having a quick look whether we are satisfying it or not so if it's three it will become so let's say according to us it will be let's say it is 3 I is equal to 3 what it will become I by 2 which will be equal to 3 by 2 it will be equal to 1 because we are having integers and it will be nums at 1 plus it will be nums of I by 2 so 3 by 2 is 1 plus 1 so yeah we are satisfying our condition and now we can proceed further so now again we have formed the array okay what is the next step we have to find a maximum element and add array so for uh for that we have an inbuilt function Max so we will just simply initialize another integer let's say number and we will initialize it to 0 because we have something to compare we need something to compare as our first element with our first element so after this after the if condition in the for Loop itself we will compare and we will find the maximum number between number and the nums at Pi index okay so we have initialized it we have and now we have to return our value what we return we will return simply the maximum which will be the number okay so I think we should run it first we'll see if yeah so it's accepted till here we have constraints like it will be okay so let's submit it so yeah it's done and thank you everyone please like and share and also subscribe my channel thank you
Get Maximum in Generated Array
kth-missing-positive-number
You are given an integer `n`. A **0-indexed** integer array `nums` of length `n + 1` is generated in the following way: * `nums[0] = 0` * `nums[1] = 1` * `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n` * `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n` Return _the **maximum** integer in the array_ `nums`​​​. **Example 1:** **Input:** n = 7 **Output:** 3 **Explanation:** According to the given rules: nums\[0\] = 0 nums\[1\] = 1 nums\[(1 \* 2) = 2\] = nums\[1\] = 1 nums\[(1 \* 2) + 1 = 3\] = nums\[1\] + nums\[2\] = 1 + 1 = 2 nums\[(2 \* 2) = 4\] = nums\[2\] = 1 nums\[(2 \* 2) + 1 = 5\] = nums\[2\] + nums\[3\] = 1 + 2 = 3 nums\[(3 \* 2) = 6\] = nums\[3\] = 2 nums\[(3 \* 2) + 1 = 7\] = nums\[3\] + nums\[4\] = 2 + 1 = 3 Hence, nums = \[0,1,1,2,1,3,2,3\], and the maximum is max(0,1,1,2,1,3,2,3) = 3. **Example 2:** **Input:** n = 2 **Output:** 1 **Explanation:** According to the given rules, nums = \[0,1,1\]. The maximum is max(0,1,1) = 1. **Example 3:** **Input:** n = 3 **Output:** 2 **Explanation:** According to the given rules, nums = \[0,1,1,2\]. The maximum is max(0,1,1,2) = 2. **Constraints:** * `0 <= n <= 100`
Keep track of how many positive numbers are missing as you scan the array.
Array,Binary Search
Easy
2305
1,094
foreign hey guys this is Jasmine from Tech Buck interview and welcome to another tutorial today we're going to talk about the car pulling problem which is another interesting problem related to intervals in this problem you're given an integer called capacity and then an array of trips and basically each trip has three components the first index is the number of passengers to pick up the second index is the starting point in terms of kilometers and finally the last index is the end point for the trip the question asks us to return true if it's possible to pick up and drop off all passengers for all given trips otherwise return false we have an example here in this one the capacity is four and we want to pick up two passengers from kilometer one to five and then we are going to pick up three more passengers from kilometer three to seven you can quickly find out that from kilometer 5 to 7 we're gonna have five passengers on board which is more than our initial capacity so we return false in another example we pick up two passengers from kilometer one to five and then another three passengers from kilometer three to seven the maximum number of passengers for all trips from kilometer five to seven is five which is equal to our given capacity of five so we return true we're getting some constraints as well what are the more important constraints in this one is the length of where trips has to be less than or equal to one thousand another constraint is that the start point is less than the end point which makes sense and then the end point is smaller than one thousand however to make our solution kind of General we disregard the 1000 upper limit here and at the end I'll briefly talk about how this constraint can make a difference in terms of our solution so without further Ado let's go to the next section which is the algorithm section so in this part I have another example in this one the capacity is 12 and we should complete overall five trips and we want to know if it's possible to make trips happen according to our current capacity okay to better demonstrates the solution I've created a timeline here let's go through each trip one by one the first trip starts at 2 and ends at three so it's going to be this one right here with a capacity of eight people the second one starts from kilometer one to three with four people on board the next one is going to be from kilometer three to six with only one passenger we continue to the next trip the next one is from kilometer four to six and is requiring eight passengers and finally the last one is going to be from four a kilometer four to eight with four people on the board okay so let's find out the number of passengers in each of these time intervals for the first one the number of people from zero to one would be zero and from one to two the number would be four the number of passengers from two to three would be 12. as you can see and passengers from three to four would be one person from four to five it would be a one plus eight plus four which is 13. from five to six it'd be thirteen as well from six to seven it would be four from seven to eight it would be four as well now as you can see there is an interval between four to six that exceeds our current capacity which is twelve and the number of passengers here in this interval is thirteen so we got to return false it's not possible to complete all the given trips with a capacity of twelve actually when we work with time interval problems we need to somehow sort the intervals or insert the intervals in a sorted order you might think of many data structures to give you this ability but you need to find the right data structure depending on the problem you're solving here one of the most important things to do is to be able to insert intervals efficiently in the data structure one of the efficient and simple implementation of this method is binary search tree however in certain cases like in the worst case scenarios for example if all intervals are given and already sorted order the insert time complexity and the binary search tree would be o of n we might think of a better and more efficient data structure called red black tree which is a self-balancing tree and the which is a self-balancing tree and the which is a self-balancing tree and the corresponding implementation in Java is called tree map it probably has other implementation in other languages but in terms of this problem I'm going to solve this one with the tree map which is like I said a Dropout implementation of a red black tree and guarantees time complexity of login in terms of insertion in a sorted manner okay for now let's consider that we found a data structure to give us the ability to insert each time interval in a sorted order now having that data structure let's see how we can solve this problem let's come back to the original State uh when we added all the intervals in a sorted order for this specific problem on each time interval I'm adding the number of new passengers when they get in the car and then deduct that number when they leave the car in this example at the very beginning at time one we pick up four passengers so I add four here and then we drop at we drop them at kilometer three so I deduct the number by four here at kilometer 2 we add eight people so I just add eight and then here we're going to remove those eight passengers and then I deduct the number by eight this time the total is going to be minus 12. here we add one person so it's going to be minus 11. and then at the end we deducted one person so this one would be -1 for the person so this one would be -1 for the person so this one would be -1 for the next interval we started at kilometer four for eight people so we add eight and then we finished our trip at times six so we deducted this whole thing by eight and the final result is going to be -9 and the final result is going to be -9 and the final result is going to be -9 and for the last interval we added four passengers so this time is going to be 12. and then we removed those passengers here and the final result is going to be minus four okay so I cleaned our time trip a little it's more visible and you can read it better this not these numbers are basically changes in terms of Passenger occupancy here we have plus four changes in our occupancy and then plus eight and here we have minus 11 passengers changes to our onboard people to find out our current occupied seeds we have to add all these numbers together here we have plus four changes in terms of our occupied seats and then here plus eight and when we add them together we end up with overall 12 changes in our occupancy at this moment it's better to write it down like this here the changes in our occupancy is 12. and the number of changes is minus 11. so the sum of changes in our occupancy would be one and then here the number of changes in our occupancy is 12. so the overall changes in our occupancy would be 12 plus 1 which is 13. and then the changes in their occupancy is -9 so the changes in their occupancy is -9 so the changes in their occupancy is -9 so the overall changes in our occupancy would be four here the overall changes in our occupancy is zero and then as you can see in one scenario the overall change in our occupancy becomes 13 which exceeds the capacity that we were allowed to have so we conclude that we're not able to complete these trips considering our overall capacity now let's go to the next section and talk about how to write the code for this algorithm okay so to implement the solution first we add the tree map that we talked about earlier to store our intervals or trips note that here I didn't add the extra check for the edge cases like if the capacity is zero or when we don't have any trips because our constraints already covered those cases but in the real interview you have to clarify the constraints first and if the constraints allow for zero capacity you need to check for those edge cases at the very beginning now we look through all the trips that we have here we have the number of passengers for each trip and here I added from and then the next one is two or basically to this destination now I'm gonna try to add those trips into our time interval map I add it from I used get or default because in the case stud there is no entry in our map our default value would be zero and then I add the passenger account let's do the similar things for two however in this case we deduct the value of Passenger accounts as I've added all of our trips into the tree map it's time to calculate the change in our occupancy and check if the occupancy change or in other words use capacity change exceeds the allowed capacity that we have I add the variable called use capacity at the very beginning its value is zero and we Traverse into our interval map if you remember from the previous section we added all the changes in our use capacity to find out our final use capacity here now it's a good time to check if our use capacity exceeds our allow capacity or not and if this is the case we gotta return false immediately and we don't check over the rest of the map for efficiency then at the end we're turned true if all the use capacity changes are in the permitted range meaning that there are less than uh or equal to the allowed capacity to calculate the time complexity we have two for Loops here and in the first Loop we Traverse over all the trips so it's going to be o of n for the first Loop and then there are two insertions in the map because it's a tree map it's guaranteed log of n time complexity for the insertions and the overall complexity for this for Loop would be all then login and the next for Loop is just a simple traversal to all the values in the map so it's time complexity is going to be oh man and the overall time complexity for this solution would be olvan login and because we have a map that stores our intervals the space complexity also is oh oven no is there any other way to improve the time complexity the answer really depends on the constraints if you look at the constraints we see that our trip length is between one and one thousand considering that constraint do we have a better replacement for the tree map here I'll leave that Improvement to you as an exercise to optimize the solution to reach o of n as our new time complexity the solution that I provided here is a more generalized one where the upper limit for the number of trips can be very huge okay so let's quickly run this code to make sure that everything's okay all right it passes the sample test now I submit my code to ensure everything works here we go thank you very much for watching this video If you like this video don't forget to subscribe to our channel for more tutorials and I hope to see you in the next video as well
Car Pooling
matrix-cells-in-distance-order
There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them up and drop them off are `fromi` and `toi` respectively. The locations are given as the number of kilometers due east from the car's initial location. Return `true` _if it is possible to pick up and drop off all passengers for all the given trips, or_ `false` _otherwise_. **Example 1:** **Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 4 **Output:** false **Example 2:** **Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 5 **Output:** true **Constraints:** * `1 <= trips.length <= 1000` * `trips[i].length == 3` * `1 <= numPassengersi <= 100` * `0 <= fromi < toi <= 1000` * `1 <= capacity <= 105`
null
Array,Math,Geometry,Sorting,Matrix
Easy
2304
1,568
hey guys we're back with another leak code video today we're going to be doing problem number 1568 minimum number of days to disconnect island so we're given a 2d grid consisting of ones which is land and zeros which is water an island is a maximal four directionally horizontal or vertical so not the corners right four directions up down not like this whatever the grid greatest had to be connected if we exact if we have exactly one island otherwise it is otherwise is said disconnected what and one day we are allowed to change any single land cell i into a water cell lancel one whoa what am i reading into a water cell zero return the minimum number of days to disconnect the grid okay so we have this example we have this grid we have water over here which is all zeros and we have this ones over here which is uh land and we need to every step every day we can remove um one uh one yeah we can move one we could remove one uh piece of the land so um the first day we take this one and we turn into zero the next day we take this one and we turn it into a zero and then we have two uh disconnected islands there the corners don't count remember it's four directions top down left right and so this is a separate island and that took uh two days so we need at least two days to get a disconnected grid we first changed land grid one and the grid zero two to water and two disconnected islands okay great so now we have this problem i we need to find the minimum number of uh days so we can't start uh trying out all the possibilities and start moving all the lands one by one maybe this one and that one and check every time whether we have disconnected great each time we can't do that right that would be super complicated that's a brute force solution uh obviously it doesn't make sense it's not the approach to take so now let's take a step back and think there's no way they want us to act they look for all the possible solutions that's not the proper approach so there needs to be an upper bound there needs to be a maximum number of days uh that uh something needs to take right so that was my thinking okay and so and i'll be honest i didn't i because i when i started this problem my thinking was wrong and so i went down the whole wrong approach and i explained where i went wrong right now so i'm thinking now okay so an island has at max four sides as a top the bottom the left and the right if we had one single block one single piece one and it had no top no download left no right that would be its own island so what i thought was that okay at most we could have an island like that where we'll have an island and it'll be connected from the top it'll be connected from the bottom left and the right and it'll take us four days to remove each one first they would be the top then the left and the bottom then the right and then that will be its own separate island so that's the max right the max upper bound would be four that was my thinking that's obviously the wrong thingy and i'll explain why so then we could start working from that and i figured i'd start working with that and i'd go down that approach and try to figure out four three two one i could handle four cases and figure that out all five cases because in the case where we already have um an empty island that was wrong because and i'll explain why but the reason i kind of went down that approach was because i didn't draw it down i was thinking of it in my head and that's why i think it's important to sometimes uh write stuff down or draw stuff down because when you do that you'll see uh errors with your own approach sometimes so if i started drawing this down right what i was thinking was this okay what i was thinking was this so i had this grid i have zero and the maximum could be a one and it could be surrounded by four other eyelet or four other pieces of land right and so i was thinking okay this could be the worst possible scenario and now i would need to make this one an island because it's connected with top down left and right and so i'd have to take one day to make this a zero and next third day and then finally four days and that would take four days the maximum is four days that's completely wrong because once you start writing it down you notice that well to have an island like this you need to have an island um to have a piece of land like this well you need to have pieces of land connected to it right and if you look these pieces of land only have one item connected to it and so that means that all i needed to do was remove this one and this could have been an island and so now i kind of started thinking of it differently you have to start thinking of it differently and so now you have to think of what are the possible cases um uh where the piece of land could be located well we said one already which is four the next one well if there's always if there's four well there always has to be one or there could have been something like this right where a piece of land could have uh could have had um let's see which one has to be surrounding it um let's say something like this forgive me something like that right and so now you see this one over here it could have had three surrounding it no that's not three black okay let's do it like this actually this one over here now has three surrounding it so a piece of land could have either three surrounding it or it could have four surrounding as we showed already or in this case on uh let's say this um one over here now i could have two surrounding it or over here it could have one surrounding it or have zero surrounding it well if it what if a piece of land has four surrounding it that means it'll there always has to be either one that has uh two surrounding it or one surrounding it because let's take a step back okay i think i'm taking this the wrong approach well let's say we had a fully uh um filled up piece of land right here right what's the most filled up piece of land you could think of well let's just all once right we see we have all ones well i now what are the possible cases well this one has three surrounding and this one has four surrounding it right oh this one has two surroundings sorry and this one has three surrounding it this one has four surrounding it well i don't need to remove the four i can move the i don't need to move the three the best one i can do is when i remove the one that has only two surrounding it right so it's always going to what i'm the point i'm trying to make is there's always going to be a corner case there's always going to be a piece of land that is kind of on the corner at worst case at the worst possible case there's always going to be a piece of land that is on a corner and you can just remove two of the sides and it'll uh be an empty land so this is a corner i can remove two of these i can move this one and i can remove this one and i'll have an empty piece of land right there that's the worst possible case it can't get any worse than that because if you were to try to make it three right uh let's just say something like that's three surrounding well if one has three surrounding it well there has to be another one that only has less than three surrounding it in this case two in this case uh one right and the same one with four that's be one that it has three surrounding it or two surrounding it or whatever too strong again and so from there we can do this at the most um number of days the cap is always two right and you can look at examples too the cap is always two and never goes more than two so a cap of the number of days is two so now we can either we can move two it will take us two days or it would take us only one day where we have something like this and we just remove this one and we get turn this into zero and we have two uh lands two islands or it would take us zero days where we already have an island so that's the basic just of it so now what you want to do is you want to check do we have an island already if we have an island already then uh yes we'll just return zero okay because we already have an island then we'll try to remove an island at every single uh land piece of land there is we'll try to move sorry now remove an island we'll try to move a piece of land from all the possible pieces of land and then check if an island is formed each time if there is then we'll return one instead if we removed one at every possible location and we still haven't uh had two islands then we just end up returning two because we know the max is going to be two so we'll say we'll try with zero we'll see if we didn't need to remove anything and then we'll turn zero then we'll try removing one we'll check everything right and then we'll return one and in that case we don't need to check removing two or three or four because we know the cap is two so we'll just return two so once again so from there we can kind of call the solution we know there's only three possible choices and so choice one we already have two islands so i have this helper function called is multiple islands is down here so it's set to false there's not multiple islands i create a visited um array then i go through the entire matrix every time i see a grid that's one and it hasn't been visited yet right if it's one and hasn't been visited yet well then we'll start visiting first thing i'll do is i'll check if i already saw one before right then i returned truth because that means that we had two if we didn't okay then i'll say okay i just saw one i'll set is multiple true that's not really the proper name but whatever you call it saw one and then i'll say okay fine now i want to visit that entire island so i'll mark island and i'll uh a depth first search a simple death research top left right bottom i'll visit all them if i go out of range i'll just break and i'll set each one to visit it so then we'll keep going again and at some point if i hit another island that i haven't visited yet right if another piece of land that i haven't visited yet and most and is multiple true meaning i saw one already then i'll just return true and if i haven't seen another piece of land in all this time then i'll just return false so i go through the entire grid i'll remove an island i'll check now if we have multiple islands then i'll turn one if not then i'll add it back and i'll try another one if all those failed then i just need to remove two which is probably a corner case and that will be or a side i guess you kind of say it would be a side too and um actually no just be a corner and then i'll return two and that's the basic um problem the main thing is trying to understand um that the upper bound is two right i made the mistake of thinking the upper bound was four which is completely incorrect the main thing is understanding that the upper bound is two hope that guy that helped don't forget to subscribe don't forget to like and if it didn't help well try not to dislike but i guess just comment and let me know how i can improve and where i made mistakes yep
Minimum Number of Days to Disconnect Island
pseudo-palindromic-paths-in-a-binary-tree
You are given an `m x n` binary grid `grid` where `1` represents land and `0` represents water. An **island** is a maximal **4-directionally** (horizontal or vertical) connected group of `1`'s. The grid is said to be **connected** if we have **exactly one island**, otherwise is said **disconnected**. In one day, we are allowed to change **any** single land cell `(1)` into a water cell `(0)`. Return _the minimum number of days to disconnect the grid_. **Example 1:** **Input:** grid = \[\[0,1,1,0\],\[0,1,1,0\],\[0,0,0,0\]\] **Output:** 2 **Explanation:** We need at least 2 days to get a disconnected grid. Change land grid\[1\]\[1\] and grid\[0\]\[2\] to water and get 2 disconnected island. **Example 2:** **Input:** grid = \[\[1,1\]\] **Output:** 2 **Explanation:** Grid of full water is also disconnected (\[\[1,1\]\] -> \[\[0,0\]\]), 0 islands. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 30` * `grid[i][j]` is either `0` or `1`.
Note that the node values of a path form a palindrome if at most one digit has an odd frequency (parity). Use a Depth First Search (DFS) keeping the frequency (parity) of the digits. Once you are in a leaf node check if at most one digit has an odd frequency (parity).
Bit Manipulation,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
735
hey guys what's up uh in this video i want to go through this little 735 asteroid collusion uh we are giving an array of asteroids of integer representing the asteroids in the row for each asteroid the absolute value represents size and the sign represents its direction so positive means going right and negative means going left each archery move at the same speed we need to find out the state of the archer after all occlusions if so also i mean the smaller one will explode and both of them both are the same size but both of them will explode two are showing moving in the same direction when we've never met so uh let's look at this example uh we have five uh going to a right ten going right left uh negative five going to the left so these two guys will hit each other will meet each other and because this one is bigger than this one so that's why this one will stay and then uh yeah that's why these two because they are moving the same direction that's why um only these two left and for this one uh this pair and because they're the same size going to the opposite direction and none of them will stay and for this pair the two will collide with negative five and negative five will stay because it's bigger and then the ten and negative five will collide and the ten will stay because it's bigger and for this one um i guess both of them is i mean uh this one is going to uh left and then the other two going to the right they never meet each other so uh all of them will stay and this question were asked by uh by google amazon and all the big names so let's take a look at the solution um to solve this problem we need to use a stack so the key thing to remember about stack is um is a lasting first out and also we need a temporary list so ignore this part and let's take a look at this part first if the a stands for asteroid so if asteroid is greater than zero and then we will append that to the stack so that means everything is moving to the right and then we will put in a stack and then um else means that it's going to the left it means it's a negative and that's why left equal to a and when not when if the stack just this is the trigger statement so if the stack is not empty and a temporary asteroid will be a pop off from the stop from the stack so while there is something in this temporary uh as a template temporary asteroid if the temperature is greater than co means is that it's going right so the camera is going right that's why we assign it uh to a right variable so now we're doing some comparison right so if the right the size of the asteroid is going to the right is bigger than the one that is going to the left so the right one will win and then we'll go back to the stack and if the left one wins and then we need to move uh out another asteroid from the stack and then to fight against the ones going to the left to see which one wins in the next round that's why we put in a temporary asteroid again and then put it back to the loop to here and when the right one wins we break it because it's no more subsequent asteroid needs to come out from the stack and then um sorry let's go back to this case so if the left one wins and also in the case when uh there's no more uh the right one in the stack which should come to this case and we have to append the left one to the stack and then that will be the end of story this is no more uh right ones and another case would be their equal size and this is trivial and both of them collide so that's the one possibility where uh yeah so this is one possibility so when uh the when the temperature is greater than zero means of whatever comes off from the stack is a it's a right one however it could be in the case when uh in case of where if the temporary is negative means uh all the asteroids in the stack is to uh toward the left so all the right ones are dead so in that case we just keep appending it right this is nothing to go against the ones going to the left now so and that is the bulk of it uh when we have i mean the starting point will be i mean whatever is in the stack will be uh something is greater than zero means it's all to the right but in the case where uh in this case the starting asteroid is going to the left right and that and this statement is accounts for that scenario right if the actual is negative and the stack is empty at that point we just keep appending to a like a term list and then we would append the template at the end of the um ahead of this the stack which we will be returning so let's test this case i can run some code it works it looks pretty efficient to me uh let's talk about this complexity analysis it's pretty trivial right so i speak of n and being the number of asteroids because we have the this um for loop here i'll look through all the uh possible asteroids so um and that's why and also for space complexity will be open as well and that will be in the worst case where if all the archery in you know this is going to the same direction so that will be all of them will be in the stack or in them list um on the other direction uh if everything goes to the left if everything goes to the right just go to uh the stack and then we will return it so uh space complexity be open um so uh pretty straightforward question and uh if we know that we need to use stack this one is not that difficult and yeah so this is my solution i hope you like it and if you do please like and subscribe to the channel and hopefully i will see you in the next video thank you for watching bye
Asteroid Collision
asteroid-collision
We are given an array `asteroids` of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. **Example 1:** **Input:** asteroids = \[5,10,-5\] **Output:** \[5,10\] **Explanation:** The 10 and -5 collide resulting in 10. The 5 and 10 never collide. **Example 2:** **Input:** asteroids = \[8,-8\] **Output:** \[\] **Explanation:** The 8 and -8 collide exploding each other. **Example 3:** **Input:** asteroids = \[10,2,-5\] **Output:** \[10\] **Explanation:** The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. **Constraints:** * `2 <= asteroids.length <= 104` * `-1000 <= asteroids[i] <= 1000` * `asteroids[i] != 0`
Say a row of asteroids is stable. What happens when a new asteroid is added on the right?
Array,Stack
Medium
605,2245,2317
1,647
hey guys welcome back in today's video we'll be talking about lead code problem 1647 it's called minimum deletions to make character frequencies unique and the reason why i picked this question is because it's currently being asked by microsoft for their online assessments so let's look at the question a string s is called good if there are no two different characters in s that have the same frequency the given string has returned the minimum number of characters you need to delete to make the s good oh uh for example they're giving us aab and we don't need to delete anything because we have a frequency of a two times and frequency of b one time those are unique very good in this case we have aaa b and c in that case we have frequency of a three times frequency of b three times and frequency of c two times you can see that you can delete the b's resulting uh you can delete two b's resulting in a good string a b c we have three a's one b and two c which is good there's one more example all right cool so i'm gonna take this example on the white board to explain how we're gonna tackle this so uh to tackle this problem we're gonna use a dictionary first to store a character with their frequency count so we're gonna loop over this uh string right here and we're gonna create that build that dictionary so uh we have a as a three frequency counts b has a also three frequency counts and c has only two frequency once we have that dictionary we're gonna also need a set a hash that in sharp and which is what we're gonna use to keep track of the frequencies that we've seen so far so the algorithm is gonna iterate over this dictionary right here and uh let's just walk through it right so first we're gonna start on a and we're gonna see the frequency of a is three times so we're gonna ask our hash set have you seen that frequency before and the answer is gonna be no so we're just gonna add frequency three into our set and we're gonna move one now we're on the second part where p has a frequency of three now we're gonna same question is b our sorry is three in our set yes it is so we're gonna have to reduce b or remove b character one time now we're gonna make the frequency of that two now we're gonna ask the question is we never set the answer is no so we're just gonna add it in our set and move on now remember that we did make one adjustment right here or one deletion right here so we're also going to keep track of our answers now we can add one to there and now we have c where the frequency of c is 2 is it an over set yes it is so we're gonna have to remove that by one character or remove one c now we have one is one in our set answer is no we can add it to reset however we also wanna have however we have to update our account by one because we deleted one and there is no more item in here so that would be our answer now uh let me add one more example so same idea we're gonna create a dictionary of character and their frequencies three times the two times the right now i'm gonna have a test set again and then i'm gonna go through each one be in the set no we're good now we are looking at this in our set yes it is our answer right here we're gonna add one because we're gonna remove this by one the two is two in our set no we're good now we're looking at c into these two in our set yes so we remove that by one answer increments by one right here one is not in the set so we can just add it what about db in two answer is gonna be incremented by one because two is already in the set now we're looking at one in our set yes if it's in a set then we're gonna increment our answer by one and we're gonna decrement this right there so we no longer have any d as soon as this is zero right here uh we're just gonna uh add that count which we already did so we needed to remove b by one d by one and d by two that's total of four operations so hopefully that makes sense now let's just jump into the code and finish this off all right so we do know that we need to create that dictionary that keeps track of the character and the frequencies so we just add that dictionary right there and now we need that set let's create a set right there and if you want me to walk through it i'll just do it uh you can see that we iterate over as one time to fill up our dictionary and that's gonna take end time right and now frequencies right there we also need to keep track of our answers for the number of operations we did or number of deletions we did whatever we want to call it and then we're going to add in the rest of the code right here like we did before we iterate over dictionary right there and the dictionary has a key of character f being the frequency if the frequency is not in the set we just add it in there and there is no operation for that but if that's not the case then we need to remove the frequency by one remember and let's just go through the code i'm just gonna copy the frequency right there into a separate variable so we can update that and we're gonna have a while loop as long as the frequency is greater than zero right and first thing we're gonna do is we're gonna increment our answers because that we need to delete it by one excuse me we need to remove frequency by one so that's going to take one operation and we do remove the frequency right there if the frequency is not zero and if we can add it to our normal frequency we're good and we just add it into our frequency and we break out of this loop and we go through the next entry but if the frequency is not zero and the known frequencies add return false meaning that it was already in there then we need to iterate over again and we need to increment our answer by one and we need to remove or remove one more frequency from that cool so hopefully that makes sense and then at the end the answer hopefully should be the right answer and the runtime you can see is the main one that we need to fill up the dictionary and this one is just iterating over the dictionary and all the known frequencies contains add uh all of that should be a constant time operation so it doesn't incur any uh runtime for that let me just submit this voila all done cool thank you very much for watching this video guys i really appreciate it if you do like the content please hit the like button and subscribe to my channel if you haven't already in the future videos i'll be talking about uh more of these uh questions from microsoft thanks bye
Minimum Deletions to Make Character Frequencies Unique
can-convert-string-in-k-moves
A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**. Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._ The **frequency** of a character in a string is the number of times it appears in the string. For example, in the string `"aab "`, the **frequency** of `'a'` is `2`, while the **frequency** of `'b'` is `1`. **Example 1:** **Input:** s = "aab " **Output:** 0 **Explanation:** `s` is already good. **Example 2:** **Input:** s = "aaabbbcc " **Output:** 2 **Explanation:** You can delete two 'b's resulting in the good string "aaabcc ". Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc ". **Example 3:** **Input:** s = "ceabaacb " **Output:** 2 **Explanation:** You can delete both 'c's resulting in the good string "eabaab ". Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored). **Constraints:** * `1 <= s.length <= 105` * `s` contains only lowercase English letters.
Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26.
Hash Table,String
Medium
null
314
can you solve this leeco premium question I'll give you 15 minutes to come up with a solution and then once you're ready you can go ahead and resume the video what's up guys it's epsyphus here with another lead code question and today we're solving binary tree vertical order traversal and pretty much for this question we're given the root of a binary tree and we want to return the vertical order traversal of its node values and pretty much a vertical order traversal is taking a tree and returning its node values from top to bottom or column by column and then if we have two nodes that are in the same row and column the order should be from left to right all right so for our first example we have this tree as our input and as you can see for our output we return 9 3 15 20 and 7. so pretty much we are just returning columns as our output so again we return nine 3 15 20 and then seven and what I'm going to do is I'm just going to label these columns so I'm going to label 9 is column negative one this column with our root is column zero this column 20 is 1 and then this column seven as two and from the way that I label the columns you can probably already get an idea of what approach we're going to take to solve this problem and pretty much what that approach is that we're going to have our root be column 0 and then whenever we move right to a right child we're going to add one from that column of our root to get the column of that right child and then when we move left we're going to subtract one to get that column of the left child and we do that progressively as we Traverse the tree from top down so we're going to have our root be zero and then we move right and then we are in column one because we added one and then we move right again and we're in column two because we added one to our previous one and then here we subtract one to get negative one and for 15 we subtract one to get zero and as you can see taking that approach gives us the correct output so now with our second example we can go ahead and take a similar approach we can start off by labeling our root node as being in column zero and then moving left we get that 9 is in column negative one four is in column negative two moving right again eight is in column one seven is in column two and then we get that one is in column zero and zero is in column zero and that's the desired output we wanted as you can see moving left to right we have our leftmost columns being labeled lower whereas our right most columns are labeled higher and the way that we're going to store these columns within a code is just we're just going to use a dictionary with the list as the keys and then we're going to return those lists so that we have the desired output in the desired format and lastly we have our third example and this example is really important because it lets us know that our previous method wasn't enough to get a well-formed wasn't enough to get a well-formed wasn't enough to get a well-formed solution and the reason why is because this case we have that this 5 is connected to this one right here and then we have that this 0 is connected to this 2 right here as in that 2 is a child with 0. and we want to return this well-formed meaning that we want to well-formed meaning that we want to well-formed meaning that we want to return smaller columns first and we always want to return nodes from left to right within those columns and in order to do that this case lets us know that we need to do breath first search traversal and for three questions the data structure that's commonly used for breadth first search traversals is just a cue and how we're going to do this is we're going to take our root node and its column and we're going to append it to this queue and then what we're going to do is we're going to pop it from the queue and when we pop it from this queue we're going to add the column in our dictionary and in our list we're going to add that node value okay and then once we pop it from the queue we add its left child in the queue and Its Right child in the queue along with their columns and we know from our previous method that the columns are just either the given column minus one or the given column plus one and then we repeat that process of popping these from the queue and then adding their value in the column key within our dictionary and once we do that you think of breadth first search reversal with the Q we should be able to get our desired output in our desired format so that's pretty much all we need to know for the idea behind the code and now let's go ahead and get into the code so the great thing about this problem is that the code for it isn't too long so let's just go ahead and get right into it so the first thing we're going to do is initialize our dictionary and this is going to be the dictionary that holds our columns and this is just going to be a default dick list and what this is just a package we're going to have a dictionary where the values are automatically list so you don't have to think about taking care of that and then after we initialize this list we can go ahead and initialize our queue and within this queue we just want to go ahead and add our root node and its column which is zero and we want to do a base case um if our root doesn't exist we want to return an empty list and now let's go ahead and get into the meat of the code pretty much what we're going to do is we're going to go ahead and pop our cue and we're going to check if the node that we popped if it exists then we're going to go ahead and add it into our dictionary add the value into our dictionary and then we are going to add to our queue the left node and the right node so node.left and then column right node so node.left and then column right node so node.left and then column minus one and then add the right node column plus one and this is pretty much the meat of the code one additional thing we need to add is a start and stop variable and this is just going to be helpful for returning our result so we just want to start as men of column start and then stop is just going to be the max of column stop and finally what we want to return is turn calls I for I in range start stop plus one and this should be the solution let's see if it works okay there was some errors within the code that I just had to fix and that was basically just turning the node column structure into tuples here and this should work now let's go ahead and run it and see what we get awesome cool so works and we see that it beats about 80 percent submissions 40 of the submissions in terms of memory and this is a o of n time solution and that's just because it just goes through each node once and in terms of storage it is also of and complexity and that is encapsulated within our columns dictionary and our queue so all in all this is the most efficient solution in Python and this is the best solution all right that's all we have for today for this question if you enjoyed this and would like to see more content like this please make sure to like And subscribe and look out for more videos coming soon thank you guys
Binary Tree Vertical Order Traversal
binary-tree-vertical-order-traversal
Given the `root` of a binary tree, return _**the vertical order traversal** of its nodes' values_. (i.e., from top to bottom, column by column). If two nodes are in the same row and column, the order should be from **left to right**. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[9\],\[3,15\],\[20\],\[7\]\] **Example 2:** **Input:** root = \[3,9,8,4,0,1,7\] **Output:** \[\[4\],\[9\],\[3,0,1\],\[8\],\[7\]\] **Example 3:** **Input:** root = \[3,9,8,4,0,1,7,null,null,null,2,5\] **Output:** \[\[4\],\[9,5\],\[3,0,1\],\[8,2\],\[7\]\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
102
86
Hello guys welcome to vikram media manager david c the question related to subscribe my channel subscribe loot the differently and before the thing of putting all the value scheduler target subscribe The Video then subscribe to the Page if you liked The Video then subscribe to The Amazing Subscribe Must Subscribe Shri Ram Inter Result and Links Is Veer One of the Problem Statement Directly Looty The God of War subscribe to subscribe our Channel And subscribe The Amazing spider-man Suggestions for more subscription spider-man Suggestions for more subscription spider-man Suggestions for more subscription Ajay Devgan Preserving Order in which you appeared in THE EVENING TO ALL THE VALUE VIDEO SUBSCRIBE TO CHANNEL subscribe this Video then subscribe to the Page if you liked The Video then subscribe to the Video then subscribe to Pan Gua Higher Nine Wickets Over All The Present In These Original Certificates Will Oo Will Not Be Known Person President Is Particular Withdrawal To The Withdrawal Patience Video Subscribe Point To Point Subscribe Now To Have Taken That In Order To Connect With Two Language Should Not Be Absolute Value In Partition subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Page The Country and Successfully and Matter this Tree Submit School Time Complexity of subscribe thanks for watching this Video Channel Ko Kar Do
Partition List
partition-list
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`. You should **preserve** the original relative order of the nodes in each of the two partitions. **Example 1:** **Input:** head = \[1,4,3,2,5,2\], x = 3 **Output:** \[1,2,2,4,3,5\] **Example 2:** **Input:** head = \[2,1\], x = 2 **Output:** \[1,2\] **Constraints:** * The number of nodes in the list is in the range `[0, 200]`. * `-100 <= Node.val <= 100` * `-200 <= x <= 200`
null
Linked List,Two Pointers
Medium
2265
168
hey everyone welcome back and let's write some more neat code today so today let's solve the problem Excel sheet column title while this is an easy problem it actually took me longer than I would have expected and I'll kind of go into why that is we're given an integer called column number and we want to return what the column title would look like in a spreadsheet like Excel but to put it simply we start with the character a and it maps to the number one and they kind of show that over here and then B will map to the number two and then going all the way down to Z which maps to 26 because there's 26 characters from A to Z pretty simple now when we pass 26 what we do after that is kind of just add a new digit like we have now double A so this will map to 27 a b will map to 28 so sort of we're just incrementing this First Column or the last column depending on how you're looking at it and this would go all the way up to 26 6 more characters which will get us to 52. can you guess what that will look like probably a z now intuitively they don't really show it here but intuitively what do you think comes after 52 if we try to increment Z we're gonna get back to a because Z is like the last character of course so then what's going to happen over here if we leave it as an a it's going to still be the number that corresponds to 27 but that's not what we're trying to do here we're trying to get 53 over here so to achieve that we put a b here so this kind of works like numbers when you think about it like this might be the number 19 and then when we try to increment this we end up resetting back to zero which over here might correspond to something like 10 and then we also increment this digit which puts us back at 20. so really what this problem is about is converting base 10 numbers and when we say base 10 we mean like the general number system that we're used to like 199 this is considered base 10 if we add 1 to this it becomes 200. it's called base 10 because each digit each position can have up to 10 different numbers from 0 all the way up until nine so now we're trying to convert this into a base 26 system where each digit like a z each position can have up to 26 characters from A to Z now there are a couple catches to this problem and the biggest one is let me just clean this up a little bit the biggest catch here is that we're actually starting at one we're programmers and we usually like to start at zero and that's kind of how the number system works as well like with two digits here the number of possibilities we can create like the number of possible numbers we can create is going to be 10 times 10 because in each digit it we have up to 10 possible values we can choose and that's because we kind of start at 0 and then we go to zero one zero two zero three and that will bring us all the way up to like a hundred different combinations from zero up until ninety nine so that's pretty simple now what happens with this over here because I was staring at this third example and I just could not figure it out so let me actually explain it with base 26 and two positions we can have up to 26 characters in each position well intuitively I was able to quickly look at this and realize that number is actually going to be smaller than 701 but how is that even possible well to quickly explain yes we can have a through z in this spot and that's 26 possible characters we can also have a through z in this spot and that's 26 possible characters but this calculation 26 times 26 actually doesn't include the ones that don't have a second digit the ones that only have a single digit which go from a through z so if we were actually going to count the total number of column titles that we could have that have up to two digits but also could have one digit we'd need to do 26 squared plus 26. and the reason for that is in our base 10 system when we didn't have a second digit like if we had a 19 that has a second digit but if we had like 0 9 the first digit is going to be zero implicitly but with our base 26 system that doesn't really work like we're not if we have a b here and we have nothing here it's not like we're implicitly putting an a because that kind of messes things up this isn't like a super important thing but I just wanted to explain like the intuition of why this problem is a bit different and it all kind of goes back to the fact that in our case here a the first digit the first character does not map to zero it maps to one it's a consequence points of this okay so now how do we actually solve the problem knowing all of that well anytime we have a number between 1 and 26 it's pretty simple to map this to a character because we're always starting at the a character and we're just gonna add the number that we get from this and actually we're not going to be adding this number because if we were to do that one would end up putting us at B but that's not what we want so what we actually do here is take this number and subtract it by one so let's say n is the column number n minus 1 is what we're going to be adding to a but that doesn't really work for the case where let's say we have 28 like this second example down here so actually what we want to do to build this digit by digit or character by character we actually take this number and mod it by 26 and when I say mod it we actually do subtract one first just like I kind of showed earlier but then we mod it by 26. what's that going to give us in this case it's going to be 27 modded by 26 which is going to be equal to 1. so that tells us that our first character should be a plus one and that's going to put us at B so what we did so far is just built that first character so now how do we get the second one well let's take our original column number which was 28 and try dividing this now by 26 because that's just generally how numeric systems work like this is more of a math problem at this point and by taking this number and dividing it by 26 we're asking how many 26s go into this original number because that's going to tell us which character we should put in the next spot and clearly by looking at this we can see that only a single 26 goes into this so now our new column number our new n value is going to be equal to 1. so now we're going to reset start this whole thing with a new value of one so we would take this number then subtract it by one then mod it by 26 and we would get zero so that's going to tell us that a plus 0 which is going to be the character a is going to go in the next spot so that works but actually there was a subtle bug that we had and it becomes clear when we talk about the example input a z because this maps to 52. let's try the exact same algorithm so we take 52 subtract one and then mod that by 26 we get 25 left over that's good A plus 25 is going to bring us to character Z so we got our first character there so we're good to go there now we take our number 52 and divide it by 26 we get two and then if we repeat this same operation 2 minus one and then mod that by 26 we get one and if we take a plus one that's going to bring us s to b so we're off by 1 here that's the problem how did we get off by one well basically when we took the N volume and subtracted one before we modded it we should do the same thing down here we should take our n value subtract one and then divide it by 26. so if we redo it doing it like that we get 52 minus 1 divide by 26 and that will bring us to I think a one because we're always going to round down and then if we put like this one here and then redo this calculation we will actually get a here instead of getting B so again the whole thing that makes this problem complicated in my opinion is the off by one error and that's a consequence of starting at one instead of starting at zero okay with all that said now let's code it up so what we're ultimately trying to do is build the output string and we're gonna do that while our column number is greater than zero I didn't really show it in the drawing explanation but at some point we're going to divide this by 26 to the point that it's equal to zero and that's when we know that we have no more characters to add to this result so the first thing we do is get the remainder and that's going to be column number minus one just like I showed earlier and modding it by 26 and when you take this what I was doing earlier was taking the a character and then adding the remainder I don't know if it's actually possible in Python to do it like this I think you can in C plus but I know that this for sure works we take ORD of a which gives us the ASCII value of this character and then we add the offset and that's probably a better name for this instead of calling it remainder I'm going to call it the offset and then we want to take this ASCII value and then convert it back into a character which you can do like this in Python and so this is the character that we want to add to our result string here but you can kind of see the way we're building this is in reverse order like I showed earlier we had like maybe a b come first and then the next one what we're gonna get is the character that goes in this spot to the left of B but when you increment it like this we're doing it in the opposite order so when I actually return the result out here I'm going to reverse this before I return it so in Python it's pretty easy you can do that like this we could also have built it in the correct order we could have also built it as an array and then joined those characters at the end I don't think that really matters like if an interviewer wanted me to do it that way I would pretty easily be able to modify the code to do so which is why I don't think that's like a super important detail so now is the part where we in our Loop actually update the column number and remember we're not just gonna take it and divide it by 26 by the way the double slash in Python means integer division so that it actually rounds down but this remember is not enough just like up above how we had the negative one offset down here we're gonna do the same thing so this is the entire code very quickly what do you think the time complexity is well on each iteration of this loop we're going to be taking the column number and dividing it by 26 until it's equal to zero and by definition that is the logarithm function specifically it's log base 26 of n that is going to be the time complexity and the way logs work that is proportional to log Big O of log n you can tell that this is a very mathematical problem it's not really much to do with data structures and algorithms in my opinion but running the code we see on the left that it is pretty efficient so if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io thanks for check out neatcode.io thanks for check out neatcode.io thanks for watching and I'll see you soon
Excel Sheet Column Title
excel-sheet-column-title
Given an integer `columnNumber`, return _its corresponding column title as it appears in an Excel sheet_. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... **Example 1:** **Input:** columnNumber = 1 **Output:** "A " **Example 2:** **Input:** columnNumber = 28 **Output:** "AB " **Example 3:** **Input:** columnNumber = 701 **Output:** "ZY " **Constraints:** * `1 <= columnNumber <= 231 - 1`
null
Math,String
Easy
171,2304
114
So hello everyone my name is Akshay welcome you a gf gp beauty week of de 78 so before starting today's question there was some dispute in the last question which I explained everything was correct but I missed a line and For the same reason, our code was submitting even after missing that line, so its tips how it was probably in some manner that it did not get stuck in us like it was not a problem but when I explained then the first doubt people were having was that You did not use the widget that is already there, so the same mistake was made by me, I did not do that and still the code was getting submitted, hence and the contrusi was getting great, so the first thing is that widgetized is created. So we have to do it to that also. Line number 48, I have done it. Okay, the second thing was that one asked because when you are right, man, when we gave the team, but here I am marking false because I just Note has not been processed, when I have taken it out from someone that I am marking it as current through and okay, so now let's see, the name of today's problem is link list, so let's see what the question is about if you have the question. If you have done it then it is very good otherwise think how can you do it then given link list of size and ok so where every no representatives sub link less and contents two points ok and next point order flat in link list search And the notes are given upper in single in the right direction and every single note which is red has a sub link list which is this note bottom pointer okay so we have to merge them, we have to march it changes, right this happens and In the same instance, time complexity and crossing the right direction and M which is H sub lincol, its size is fine, so it means we have taken all the notes and time complexity is 10.3, so if the time pane is dot free, it will reduce the date mains, then its time complexity will be discussed immediately. You can do it, friend, what can be reduced, you have given it to us, en square also, this will be the first time, you can do it and the same has been given in respected, okay, so its tuition will be there, friend, we will pay mouth sort only on this. We will just put it there and now it will be like a link, so how does the death end happen? First see what we do, we used to have a big lamp, we used to break it until it becomes two elements, right, we break it. How to do this thing, the half portion video element used to be two elements and with that, you would have sorted them and presented them to us, then you would have run the sleep direct function and kept breaking them until we have you sorted arranged and Give C just used D mode function approach it means friend its function right then we will also do the same 28 and lastly we will just create a march function and if I right you are precise modes you are sorted we also have to do the same so first let's see March you sorted Hey how do we change the pointers in this linked list so that we can sort it so okay so I take these two lists man I take this one list this smaller list how will five seven reduce on Indonesia At second, what is the value of Sorting will be maintained five and 10 and why am I putting at the bottom because I read in the question next quantar understand the meaning of the plots you are doing friend this case is done right what will be the second case right us while storing an answer as well Chalna padega hai na and what I can say let's make a variable in the answer, our five will be stored and I will call D from function let's say M I will call for what time is the list and this is the B list. Will be 76 And who do we have to do it with without bottom and B right replace its value seven dot bottom What will it become So now you can see and the answer is what has happened 5 and 7 nine C have you most D List Which List Aate Twenty Tennis Karna Like B Is Greater And Again What I Will Do You Will Answer B Aate Ka Bottom Will Be 30 Right And B Will Be 20 Nine I Can See Date 30 Is Greater To Hum Ye Second Case Me A Gaye Yaar Right in this second case, what we have to do here is we have to reverse things like so b is the value so what I am doing is I will call the function for it is 30 and I will call for 10. And 20 right, I will do this, so it's again compared with 30 and 20 iteration, you understand friend, after that it will be very easy for us to write the code, I will store the answer nine which is a small answer, so from here if you look manually then what is the answer? The return should be 30 so if I try to do a best draw from here then I can right which is what I did, below 20 I can also do another generator, what else did we store, after every call we Made an answer note so what I was doing I was moving in a dot b direction b and b let's write date it is a dot bottom ok I will move in which direction first pass the bottom this the functions where what will you do it After doing this, I always had to print my flat, date is the same, I am using this bottom point, otherwise I use the next one, there is no problem in that, the quality will be the second one that this dot di &gt; b dot d, so with that we have to di &gt; b dot d, so with that we have to di &gt; b dot d, so with that we have to store the answer back. Have to do D Answer will be call What un be dot exactly right Energy was stored coming at this point of time I want 10 Ahead Answer What did I do Answer was going to store Right so five dot will be seven dot bottom Will be 88 dot bottom will be 10.20 bottom was there so we have the answer A 10.20 bottom was there so we have the answer A 10.20 bottom was there so we have the answer A chuka hai yaar a chuka hai or not a chuka so this is what yaar mode short kya doin last tu sorted man go in iron the call my function Right, this is the code of our function. Okay, let's see how to reduce our function. So, how will our code reduce? Let's check it. Once that will be the name of how to reduce, I will pick it up from here. Immediately. Want fruit is equals you na any of these two cases have to be returned right so I will just return root so from here there will be 28 returns I will say it is return every what I would like to do here I will pass two lists There is already a list of 19 which is something at the bottom, there is a list of 28 which is something at the bottom, it is connected like this right so I will make the connection if root dot next which is equals you become 28 and what function will it reduce here. Which I just drove and showed you immediately simple end come de last see will se date after march will just return road just return route end 19 will happen here more function call will happen here 10 common 19 for and it will return after Morning you return and similar will happen here so what can I write right key root dot next went till the last while doing medical right so √ next I till the last while doing medical right so √ next I till the last while doing medical right so √ next I can write this. To download it will be no tax, I wrote this code, I did no dancer and as if the data of A is low, A's data is low, then we will put it at the bottom of the answer, like A's data is 12, right, so Whatever is there will be included in our answer. Answer I have been included and in the answer dot bottom we have the remaining list date. This is the remaining spawns. The answer is dot is placed in the bottom, so we did it because the question said it is D bottom point and start of D next point will be similar case, the answer is we have done it in A so D rest of D list which remains this wide. The dot is at the bottom, right, and the Let's resume the video. Okay, so this is done, so I am already explained, that's what I am checking, five, ten, 19, 28, after 28, I don't have anything right, so I checked, for the condition from legs = I gave the team there. condition from legs = I gave the team there. condition from legs = I gave the team there. Okay, nine route dot next will be flat and off the route dot next ride, so how am I doing this, actually I was doing this every time, where did I go from here and finally we returned the answer √ and finally we returned the answer √ and finally we returned the answer √ Right so I also tell you how to reduce the tree. It is very important to understand that it is slow. So if it is a Let's compiler then what will be its time complexity. If you submit it then it should be because the time complexity of C is just visiting and every note is right. I have used here modes tu sorted hit de submit button it will get submit because of our time comes complexity date will be n jo right direction notes and the number of notes is ok so it's successfully submit so de time comes tu will B number of notes I can C date you of N so this is the first one doing it right and F of 19 pe hoga jab hua tha ye give it uses this function F of 19 you 28 right and this is to shorten this thing Of m space is reversible, right? When I showed you the dragon, you can see that O of tu means all the notes are in the subless so I can say O of tu m There is a space here so I can date Hi that of tu m hoga so every n so for every n it is using 2m space right so I can say date this space complexity will be o of n cross 2m and remove the constant so I can say date you of n cross mia It is written in the space of butt was not even considered return to this date this is it for today's video meet tomorrow's Piyush 79 and for d last thing date dsl represent you can started with d source code and this mind Instagram you can Connect me any other time if you have any doubt for guidance then meet me take care bye
Flatten Binary Tree to Linked List
flatten-binary-tree-to-linked-list
Given the `root` of a binary tree, flatten the tree into a "linked list ": * The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`. * The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree. **Example 1:** **Input:** root = \[1,2,5,3,4,null,6\] **Output:** \[1,null,2,null,3,null,4,null,5,null,6\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-100 <= Node.val <= 100` **Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Linked List,Stack,Tree,Depth-First Search,Binary Tree
Medium
766,1796
1,816
hey guys spain here today we're going to talk about question 1816 called truncated sentence so let's see what the question is asking so given the string an integer k and all the string is separated by spaces and we want to truncate the sentence up to how many number how many words in case of for example if the string is hello how are you contesting and k is four so we only want the first four words from this sentence how can we do that so basically first i want to split to sentence to words so i want a space because it will separate by space then later on after we separate it empty stream and then until the k index all right so and then yes this will be there so but we need to do some still gonna do something with it and i find a simple word okay so i'm going to take out the yesterday plus let's take all the last space we added all right thank you guys if this video helps you like subscribe and code until the fan thank you guys for wisdom leading okay guys
Truncate Sentence
lowest-common-ancestor-of-a-binary-tree-iv
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation). * For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences. You are given a sentence `s`​​​​​​ and an integer `k`​​​​​​. You want to **truncate** `s`​​​​​​ such that it contains only the **first** `k`​​​​​​ words. Return `s`​​​​_​​ after **truncating** it._ **Example 1:** **Input:** s = "Hello how are you Contestant ", k = 4 **Output:** "Hello how are you " **Explanation:** The words in s are \[ "Hello ", "how " "are ", "you ", "Contestant "\]. The first 4 words are \[ "Hello ", "how ", "are ", "you "\]. Hence, you should return "Hello how are you ". **Example 2:** **Input:** s = "What is the solution to this problem ", k = 4 **Output:** "What is the solution " **Explanation:** The words in s are \[ "What ", "is " "the ", "solution ", "to ", "this ", "problem "\]. The first 4 words are \[ "What ", "is ", "the ", "solution "\]. Hence, you should return "What is the solution ". **Example 3:** **Input:** s = "chopper is not a tanuki ", k = 5 **Output:** "chopper is not a tanuki " **Constraints:** * `1 <= s.length <= 500` * `k` is in the range `[1, the number of words in s]`. * `s` consist of only lowercase and uppercase English letters and spaces. * The words in `s` are separated by a single space. * There are no leading or trailing spaces.
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
Tree,Depth-First Search,Binary Tree
Medium
235,236,1218,1780,1790,1816
161
okay so let's talk about our one added distance so you're giving a string s and key so you have to return true if both of the 180 system apart and other spots will return false so you can use either inserting deleting and replace right so we can only uh insert one character they do one character or replace one character so uh in this one so we can definitely know the length should be the same right so they are not the same when they are inserting we're not deleting right they are not the same as well right but we're now replacing they are definitely the same right so i can just make sure like on the first condition are they the same length or not if they are lying i can know it's either inserting okay if they are not sure if they are not then they know it's either inserting and they did it if they are the same i'm going to know is going to be replaced at some index when they are not equal the same and i can just check on the next one right so let's talk about the replace because this is the easier one so imagine a c a and a b a right so in this index they are not the same right but i'm still going to traverse transverse the uh the string and i'm going to just make sure they have the same index and the same character for the same index if they do let me move on the next one and since that since they don't have the same decks right i mean they don't have the same character right i can just compare the substring after the index which they are not the same so it's going to be one it's the substring and i'm going to say i plus 1 is this is equal to what uh t dot substring and then i plus 1. just check the following character you don't need to care about like what this is right it doesn't care they are not the same you don't actually care about it so you move on the next index and this is the solution for replace so what happened for the insert or did it you can actually use the same format so in certain details should be the same concept but the problem is you have to know which one is the shorter length for the string and i always put the shortest length for the s and then the largest lamp for the t so when i know they are not the same right when some index they are not the same right my eyes shouldn't move i would uh sorry my ester i so uh string s the i in this i won't move i only move t dot index i plus one this is because i know i'm going to d one or i'm going to insert one something like this right and i have a because i need to what i need to insert one character for the s or you want to delete one character for the t here right so uh when i call it you definitely know right so what happens if you have what if you have empty string for s and then there is a character a for the t right so at some point you want to what you want to know this is definitely what this is definitely you can definitely delete it right and they are actually the same right so in the uh in the return value for inserting and deleted uh you should return true right and then for the replacing you only check the condition in this one if they are not the same i mean if they are not the same you have to return false right all right so i basically finished the idea all right so let's talk about the so the problem is why if the style if s and t are the same is equal right you need to return false because they shouldn't be the same you want to either insert in deleting or replacing right and then i'm going to have n equal to s dot length and n equal to t dot n right and then if n greater than i'm going to reverse the string and this is going to be what t comma is right now i know my shoulders uh shortest length is always x right so i will say if m equal to m right this is like replace right so replace x comma key and then i'll see if i can just what i can just return what can just return delay or insert or sap right so let's run a random replace function and a string d so uh if there are another sample that definitely returned four star four in i could be your i list install installments and plus so if star chart aai does not equal to a t dot chart at i just check the following so is the substring i plus 1 is this is equal to t dot well substring a i plus 1 right this is pretty much a simple concept right so what happens if what if is public boolean insert your insert screen s 20 and then for n i could be zero i less than star length i plus and then uh at some point i need to return true because a could be empty right and you are not accessing you're not access the full and definitely i need to have a i definitely need a condition so because i can only be what if n equal to m minus one i can only be one kilo the less right so this should be what return for this one and if not if there are not one kiloton difference right and i'm going to return close so i'm just making sure that so this might be my mistake but i know this right and then when you traverse the follow you always traverse the s right because x is always what the shoulders run s is always the shortest one you reverse when as the length is longer so you reverse so now you know as the lens is always shoulder which is on the uh insert so if they are not the same i can just return is the substring at i then this is equal to t dot substituent a i plus one so i think this is the solution so let me run it and i have a table uh yes i do which is 21 hi okay now submit all right so this is a solution so let's talk about the time so this is going to be all of us i mean i'm going to say all of them right if they are equal then you return first and equally you're checking every single character right and then you reverse so this is nothing and then when you replace right and then this is all the fun right this is all open and then when they are not the same you check the substring the equal equals every single character so you can probably happen in what probably happened in the first character right in the first character uh and on the sensor you traverse from the second character to the end so this is all of n and this will be all of n right so uh so this is pretty much it right so it's going to be un squared for the worst case and same thing for the dd or in uh dd or insert you traverse all of them right and then later on you uh for the first character layout another center right and then you check for the following character and then which is what i uh from i plus one two one to n right so this is what all of n as well so all of them times all of them is n squared so this is the worst the time complexity and square for the space is going to be constant right so uh this is pretty much it right and then if you don't want to use the helper function right i'm going to just copy and paste my solution so this is going to be exactly the same thing so if they are the same right you return first and then i'm going to say an m for the s dot n and t dot length so i'm going to reverse the string if what if s is greater than m right so i put the shortest string for s only then i traverse the entire string s right then if they are another saying and i don't i'm going to check the condition when an equal to m right um this is going to be replaced right so i just say i plus 1 and i plus 1 if they are not the same which is what deleting or uh deleting or insert right and then s is always shoulders right so you don't care about it so you always substitute for i plus one and then later on you will just make sure like if a minus one the length difference is actually equal to one if they are actually equal to one and this is correct so uh again this is going to be uh okay for sure so the timing space is going to be the same all of n and this is all of them uh all of them as well but in this one you are using a photo so everything is happening what happened in stack so if you just call the recursion something is this going to be uh hit definitely i mean this is definitely uh for sure because you are actually recursion but whatever all right so this is this now the uh this is not the main point so if you have any question leave a comment below subscribe if you want it and i'll talk to you next time bye
One Edit Distance
one-edit-distance
Given two strings `s` and `t`, return `true` if they are both one edit distance apart, otherwise return `false`. A string `s` is said to be one distance apart from a string `t` if you can: * Insert **exactly one** character into `s` to get `t`. * Delete **exactly one** character from `s` to get `t`. * Replace **exactly one** character of `s` with **a different character** to get `t`. **Example 1:** **Input:** s = "ab ", t = "acb " **Output:** true **Explanation:** We can insert 'c' into s to get t. **Example 2:** **Input:** s = " ", t = " " **Output:** false **Explanation:** We cannot get t from s by only one step. **Constraints:** * `0 <= s.length, t.length <= 104` * `s` and `t` consist of lowercase letters, uppercase letters, and digits.
null
Two Pointers,String
Medium
72
516
hey so welcome back this is another daily code problem so today it was called longest powderomic subsequence and it's a medium level question and so this is like a different one where I'm actually just going to already have the code written out and I also have some printing statements it's just for me because this one was just a hard problem it's a two-dimensional and dynamic programming two-dimensional and dynamic programming two-dimensional and dynamic programming problem so um it wasn't very intuitive for me initially I thought it was like a backtracking problem um where you kind of keep track of two pointers and do this uh in a Brute Force manner but it seems like you actually can or you actually can do it using dynamic programming so essentially what you're going to do and I have all these print statements showing you the two-dimensional grid that you're going two-dimensional grid that you're going two-dimensional grid that you're going to make is in the final case this 2D array is going to look like this where you have these letters bbab and just explain the problem I guess I should quickly um you will have a given string get assigned to you and you want to see what the longest palindromic subsequences for it in a subsequence is just say you're given a sequence and you want to find out okay what is the longest palindrome that you can have in here and palindrom's just when reading it from left to right it's like the same so whether you read it forwards or backwards you'll read it the same word um but a subsequence is like you can actually just take a any of these numbers and you can remove some and you can keep some but you just have to keep the ordering so in this case we could just remove a and that would give us the longest subsequence BBB and that's fine because we're not changing the ordering we're just adding we're just keeping or removing something so that's a subsequence okay and so all that we're going to do is say Okay um why don't we make a two-dimensional grid why don't we make a two-dimensional grid why don't we make a two-dimensional grid from this and we're going to put the word like this just like how it is but then we're also going to spell this word downward so this is B then be then a then B okay and so all that you're going to want to say is okay given these two strings then we're going to build it kind of in this direction we go from left to right and then just keep going like this okay so we're going to start from the right and then we're gonna go out and then in out and in out in okay and that's what this these two for Loops are doing is we're just kind of maintaining this iteration here okay and so that's how we do that and so what this kind of represents is we'll be comparing in this case this B with this B and we'll say okay what's the longest palindrome here well that's one because they have a length of one and then we're going to compare a with a here right and so we're going to compare this row to this column and a well that's a the longest palindrome there is one all right and that covers this case here where initially we just set it to one and so from there we're going to be like okay now we have to take this which that's going to be comparing um that'll be comparing a to A to B basically so we have a here and we're comparing A and B Not Just A and B but this sequence here which is a and b all right and so the longest um palindrome from comparing A and B will just be one and you get that by just saying okay you've now entered this for Loop like we've already done this logic here to get that one we've entered this for Loop and we say okay if a does not equal B because we're at the B column then let's do this logic otherwise we do this and since a doesn't equal B here then we're just going to take the maximum of what's below it in what's to the right of it and the reason we're doing that is because well when we get to here we realize that with the sequence A and B and we're comparing a with it here we already know what the longest subseq or palindrome for a and a is and we already know what the longest pounder for B and B is and those are both one right but when we're saying okay what is then the longest palindrome for both of these because A and B don't match like these aren't parallel to each other then you know you just have to grab one of these whichever one's maximum and they're both one in this case so we just set it to one okay it might be hard to wrap your head around with me the second example will help you because it's a bit longer and so then we move on and we go for this one and we say okay what is comparing and once again this is b a then B so now we're comparing B to B and so that's one we initially just set it to one and then we compare okay when we look at b and a we've now entered this for Loop and we say okay at B and A this subsequence here since B we have a b here does not equal a then you want to compare okay below whatever is below it and to the left of it take the maximum and that would be the comparison of BB and a into that would just be one the maximum of these two is one and so you set one here all right and so then you move on and so then you're at this iteration where you see okay now we're comparing B with B A and B and then you see okay these do match B here on this row matches with this B column right these two and so then you want to say okay you actually handle this case where they are equal to each other and in that case you do put you add a 2 to whatever's in the diagonal of it not you don't take the maximum of what's to the left and what's below what but you take the diagonal value which is one and then you add two to it okay and so the reason behind this is the diagonal value of this bab versus B here is actually a an A represents what's in the middle so whenever you take the diagonal of like this subsequence you're actually grabbing what's the current maximum of its diagonal so say in this case was actually more like this and say we pre-computed that its and say we pre-computed that its and say we pre-computed that its diagonal was three and so when we're calculating this cell since this diagonal had a 3 here you're just going to add 2 because these two match and so then you update and it would be like five in that case but in this case we're updating from 1 plus 2 to 3. okay so I hope that kind of explained it a bit where there's the cases where first you just fill in this row with all ones because it just represents okay B and B have a maximum dramatic sequence of one then a compared to a here have one B here with B like they're all one so you just initially set it all to one and then you say okay whenever you encounter something where they don't equal each other you just take the maximum of what's below it and what's to the left of it all right but then when you do encounter a sequence where okay these two numbers match say we're going to be a b and we're comparing B with it and you see that these two this B row this column match then you say all right so let's take the diagonal of it say it's this case and so since this was 2 let's take the diagonal of it which is whatever is in the middle of the palindrome and then add two to it which would represent this okay so it's hard to come up with this like I think intuitively you have to do a lot of dynamic programming problems and just trust the process I came up with some of this code but I fell short of um Computing that I know that just didn't come intuitively to me um but doing this sort of like putting the letters like this and comparing it with the column here that's very common for these dynamic programming problems and building this two-dimensional grid and building this two-dimensional grid and building this two-dimensional grid and just finding a way so that when you Traverse this like you can increment one initially and then walk out okay given this these smaller um these smaller problems that you solved how can we add them together to build a bigger problem that's the whole point of diagonal programming or dynamic programming and so then at the very end Your solution is just going to be in the top right hand corner which is pretty standard and it'll just represent okay given this entire string now what is the maximum palindromic string and you just be kind of aggregating it along so yeah I hope that helped a little bit um sorry I didn't just write out the code and explain it step by step I thought this one was just simpler for me plus it's like um literally like I started recording just at the due date so if we refresh the screen we're already on the next problem so yeah that was today or yesterday's problem now and um I'll uh why don't we take a peek and see what the next one is so it's a hard one okay so um yeah follow me for more I'll be solving this one uh probably tomorrow afternoon so um good luck with the rest your algorithms thanks for watching
Longest Palindromic Subsequence
longest-palindromic-subsequence
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`. A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** s = "bbbab " **Output:** 4 **Explanation:** One possible longest palindromic subsequence is "bbbb ". **Example 2:** **Input:** s = "cbbd " **Output:** 2 **Explanation:** One possible longest palindromic subsequence is "bb ". **Constraints:** * `1 <= s.length <= 1000` * `s` consists only of lowercase English letters.
null
String,Dynamic Programming
Medium
5,647,730,1250,1822,1897,2130
1,980
hello guys and welcome back to lead Logics this is the find unique binary string it is a lead code medium and the number for this is 1980 so in this question we are given with an array of strings nums and which is a string of binary numbers you can say like binary strings it consists of only zeros and ones and we have to find a such string that does not appear in the nums and is of the size of uh n is of the length of n so there is a very beautiful hack that I F found out in this uh in this problem and I will tell you that also plus so do watch the video till then now um this is called the diagonal position now how we'll solve the question let's see in example one so we have zero 1 0 so when you will first see that at zeroth index zero occurs that means there is no chance that in the our solution what we are going to return our answer 0 will be at zeroth position it is confirmed that always uh 1 will be because 0 already occurred now let's focus on the second index number one so come on here you see Zero occurring here what if I do convert this 0o into one it becomes 1 one and which is true the I have my solution now let's check for uh example three as well so for example three I have created a table also you can see we are having a given array like this and first the we what we do we take the zeroth element zero index zeroth element Z index is one simply convert it if it is z converted into one if it is one then convert it into zero the logic behind this is that if we are sure that at zeroth index one occurs then there is no chance that it can occur in the solution so I was thinking like this so there was one add zero then we take first index first string first index it is also one add zero and then we take the third one second uh third element second index it was also one so add zero so we get 0 and the 00 was also a possible solution so it means we are going correct so let's try to code this but before that please do like the video please subscribe to the channel if you're new to the channel and share it with your friends I'm currently coding in Java but you can get my uh C++ Python and JavaScript code my uh C++ Python and JavaScript code my uh C++ Python and JavaScript code from my lead code solution which I will post in just a minute so first of all we'll need a string Builder to construct the result string you can also use a normal string but I am using a string Builder because it is easy to append elements to this and also it is a little bit faster so we need to write itate on the ayat element aat character so let's go till the nums do length what do we want to add so we want to add ath element a character so nums of I do Kar I if it is equal to Zer then what we want to do we want to add a one otherwise we want to add a zero this seems fine and simply return nothing to do simply return the SB after converting into string so let's see if there is any error sample test cases are passed you can see as I told you the output was 0 which is true so now let's just submit the code so it beats 100% of the people in code so it beats 100% of the people in code so it beats 100% of the people in Java and memory is also good time is also good if I talk about the time complexity is uh o of n because we are iterating on the nums of nums array and space complexity is also uh you can say n because we are using a string Builder that consist of n characters so but it still uses much less memory when you compared to normal method if you sol this question and I'll be posting my C++ question and I'll be posting my C++ question and I'll be posting my C++ Python and JavaScript code in the solution Solutions page please do check it is of the it will be of the name Millennium 103 and you can see like here my profile photo and check the solutions so I hope you understood the logic please do like the video share it with your friends subscribe to the channel thank you for watching the video have a nice day
Find Unique Binary String
faulty-sensor
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "00 " would also be correct. **Example 2:** **Input:** nums = \[ "00 ", "01 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "10 " would also be correct. **Example 3:** **Input:** nums = \[ "111 ", "011 ", "001 "\] **Output:** "101 " **Explanation:** "101 " does not appear in nums. "000 ", "010 ", "100 ", and "110 " would also be correct. **Constraints:** * `n == nums.length` * `1 <= n <= 16` * `nums[i].length == n` * `nums[i]` is either `'0'` or `'1'`. * All the strings of `nums` are **unique**.
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
Array,Two Pointers
Easy
null
1,457
hello hi guys good morning welcome back to a new video in this we're going to see the problem and yeah I hope that you guys are doing good in this we going to see the problem uh pseudo palic Parts in a binary it has been asked by Amazon not pretty much but yeah it's actually a very good problem if you want to go deep into the logic which we learned yesterday if you don't remember the logic which we learned yesterday was the problem 1 2 39 maximum length of concatenated string with unique and we did it by recursion back and bit manipulation in that we learned a lot about bit manipulation so I highly recommend and again that is that video is not need for this video but still I highly recommend if you want to go deep dipe into bit manipulation please go and watch that video too now uh let's start off although uh I have given you quite a lot of hints but still let's we'll go on from very intuition from very scratch it says that we are given a binary tree bin Tre is nothing but a tree having zero node or one node or two node as a child now where the node values are digits from 1 to 9 oh that's one hint which they are giving in that okay the node values are from 1 to 9 itself that's it which is a very small number so again when a very small or very large number comes in picture it's a very big hint let's say if I ask you the node values are let's say very less but a very big number so that very like large very less it actually gives a very big hint but yeah a path in a binary tree is said to be pseudopalindromic if at least one permutation again permutations is nothing the arrangement of that number of that nodes if one permutation of the node values in the path is a Parr so basically if I just have a random path in a b let's say 2 3 1 now I can do any permutation okay like I went on 2 3 1 I can do any permutation 1 2 3 1 2 anything I can do and that should be a parent roome then I can say that this specific path is actually a pseudo palindrome right okay we have to return the number of pseudo palindromic path going from the root node to Leaf nodes again path can be this also in this entire tree but they're specifically mentioned so as to make the problem medium again so to make the problem medium that again so make the problem medium they have written from root node to Leaf node you're only concerned from root to Leaf that's it which means you cannot or basically you should not stick to the middle you should go from root to Leaf that's it so I will start off from the root and check at the leaf only that's it again if I would have given any path then the problem would have become hard because then you will have to do some pre-computation which will to do some pre-computation which will to do some pre-computation which will involve D but yeah let's see the problem right here so for sure uh I know one thing I will start from the root and will check only the leaf but in that I will have to Traverse every path so One path is 233 okay one path is One path is 233 I can just rearrange that and make a 323 which is actually par Parr is nothing but which is something same from forward and backwards you can see same and in the middle for sure if the number is odd then in the middle you will have a unique character as in like you can have something which is not having the again like it's same duplicate number so for this path I know okay I can just have a permutation of it and arrange that same for let's say 211 again but for this 231 which is again a path from root to Leaf but this in this I cannot form pal because of every element occurring in the all frequencies what did I say now or frequencies that can be a hint not sure why but yeah that can be a hint so now we got to know that the parent room which we had seen in our life are of two kind either can be of even length or the odd length when like when we say even length so you'll see okay a BB and CC okay everyone is making pair but all length is a b c and one will be in the middle which will not make a pair so for sure we can easily see that here one element will at Max one element can have odd frequency at Max if see one element can have because you saw one element can have OD frequencies if it is of odd length else it will have zero frequencies element if it is of even length so we got to know just one thing that only and only at most one element will have odd frequency that can be a big hint for you so as a track of that how to actually know at the leaf this is a paror or not so what we can do is okay we know that we have to go in from root node to Leaf node so we will just do some pre computation as we will just we will keep on doing some computation at every level right now I'm concerned only about the frequency because right now above I have seen that I again if I have at Max one node with the odd frequency ultimately then okay it will be a Parr but if not then let's say it's not a Parr so uh which means I'm just concerned about the frequency of element so what I'll do okay I'll do the same thing I just concern about the frequencies now for the frequencies you can also keep track of the unordered map but as we knew that the size is restricted to just nine which means I can have the nodes from 1 to 9 only so I can also keep track in the array I because you know internally hash map is also built on top of the array it's just that hashing is being done but right now I know okay I have only size of nine so I can make a size of nine as my AR itself and in that the value will be the frequency of the element so right now my two came in once okay once now I can propagate the same value to both of it child okay I can propagate one and okay and I will propagate one for him for my two value but as I encountered a three so for sure three is also will be added so okay corresponding to three I added a one because one 1 three is added corresponding to one I added a one because one is added now I go down and see as I'm going down I'm propagating my frequency which I have built to my children so here three is added again so count of frequency will actually increase like count of frequency of three will actually increase and will now become a two here you will see the one came in so one will actually added here the one came in so one frequencies will be increased so right now ultimately you remembered from root you started from on Leaf you ended you have to check on Leaf only so I have a check here that what is the frequencies of all the element he'll say frequency of 0 is 0 frequency of one is z and all the elements are also zero frequency it's just that frequency of two is one frequency of three is two and I'm not concerned about what is the frequency I'm just concerned about if it's a patter or not and to know that I should know that okay at Max one element should have odd frequencies and I can see that only two is there who is having odd frequencies which means I have only at Max one element that's true so basically ending at here I will have a Pome that's great and if I go and ask here then he will simply say Okay um that oh I have three odd elements it cannot because I can have at Max one odd element like odd frequency element okay that's not a Parr here also it's a even frequency ignore that or frequency okay that's just only one or frequency okay that's also a p so ending at here is a p and ending at here is a p so the answer is a two for me okay that is one thing but uh do you see that how much is the time complexity of this which means you will go on to all the nodes one thing is for sure now you will also at every node let's say which means all these Leaf nodes you will have to iterate on the entire array of size nine because you know that you have only nine elements so this frequency array which means the array which you have made will be having nine blocks or at Max 10 blocks depending upon how you implement it but yeah this will be having o of n into 9 again that's a constant IR ignore that we can ignore it but what if the interviewer is not agreeing to ignore that what will you do there and the same way if we are using the same thing so we will know okay we are actually okay here I am having this specific array of frequencies I will have to pass the same array here and here but you know a DFS works it will go entirely deep and then he will come back and then he will go down so I will have to store this frequency array at every of my height which means every level I have to store this so okay let's say this AR size is nine so at every depth I will be storing that now when I will be coming backward so I just remove it now I will use the existing made one again I'm not this was existing made one this was a dup like this is something else Bally a new copy is being made every time and that's how when I will go back I will have my original copy already with me and then I'll use that copy here so you know okay if I do a simple recursion I will be going H depth which is for sure I will go on but for every depth I will have to also incorporate a nine length area frequencies so that will be time and space complexity which is again that's a concept that's o and o h but this constant is uh interview might not agree so one thing is you can use backtracking which means rather than making the copies again and again if you have not seen the last video in that we have explained very well deeply recursion backtracking and uh bit manipulation but yeah so that is not that is you can watch extra it's a 50 minutes video because it was very deep now in this we know one thing that we can actually use backtracking how that we know that this was a specific AR for us now rather than making a new copy at every level I can use existing copy I know when I'm going back I just decrease the frequency count which means here you remembered I had a 0 1 and two so I know if I have to go back okay when I came down I added the frequency of three so it became a two now I want to go back to original state because I'm not making copy right now this is the in memory operation which is being done so to go back I know okay from element 3 I'm going back I just reduce the frequency of three okay I'll reduce the frequency of three it will become one and that's how I can just do a back track and reach to my previous state okay backtracking is one option but with this what will happen this space o of H into 9 the space only will get optimized that's it this space only part will get optimized but you still be having the time how what will you do about that is what where will come in the actual operation which we want so ultimately in the end you remember that we only wanted what we only wanted the count or the frequency of the element right and in the frequency also we just only want wanted to know okay if we had odd frequency element again I'm only about the odd frequency element and the count of all frequencies element that's it so if I'm concerned about the odd and the even like I'm concerned only the odd but odd complement is even so right now I can say I concerned only odd frequency and even frequency element ultimately remember I was only concern the odd frequency element but now the complement of odd is even so I can just store both odd and even frequencies but are in y to store even also so basically how to know okay you are about to make a even frequency if in even you add a number new number which means okay my even my two frequency is right now four if I add one more two my frequency of two will become a five which is odd so for sure even you add a new frequency like you add a new element to that you it will become OD itself so ultimately we just wanted to store all and even frequencies now for that why to actually store the numbers itself entirely as in like why I'm St the entire frequency okay frequency is two I can just say now frequency is even which is okay for me so I can just represent my odd frequency by one and even frequency by 0 so you will see that I can represent the same thing as 0 1 0 because I'm only concerned about the odd frequencies so I can represent this number as this and you will see this is nothing but a binary form so I can represent this same thing again this is for zero this is for Z this is for one this is for two and this is for three so when I write in the binary form it is actually a 0 1 0 because we wrting from the right to left so it will be a 0 1 2 and 3 now I can represent the same number as 1 2 4 so you saw I was having a N9 length array I figured out that rather I would I should actually take just the odd frequency I'm only concerned about that so I converted that to a zero and one for odd frequency and zero for even frequency and with this I got to okay it's a binary form and binary form can be very easily transformed to number so I just transformed that to a number and now it's just a number and not the entire length and that is how you can actually optimize it so you would not be needing these two stuff which is 999 right now let's see how the entire thing will actually work so in the very beginning you had just two entering in the picture again I'll help you derive that how to actually bring out this binary form also at every level but right now just see that how they actually made or how they will actually look like so initially I will have only two as a frequency of one like always remember but whenever we write in the binary form from right to left so you will see okay 0 1 one is for two this is for the zero bit this is for the first this is for second this for the third although in this problem my zero bit will never be used so one optimization which you could have done in the above uh while making the r itself is never even using a zero but that is index shifting and stuff which will actually cost so yeah no worries um now in this I know okay this I can represent the same thing as this again this is same thing I can represent as 01 1 0 again 02 1 0 which means the frequency of 1 is two I can represent that as a zero itself that's how the benefit again you can just go through other values also but yeah it's just to show you that I am just getting the odd and even frequencies odd frequencies as one and even frequencies as zero now if you remember ultimately okay even if you make it ultimately in the end you just have to make sure that you should have only at Max one OD frequency element which means in this binary form in this number which you form which can be represented in the binary form which is 0 1 0 you should have only one set bit indicates you have only one OD frequency element again I'm saying at Max one set bit either the set bit count is zero or a set bit count is one but you should have at Max one set bit so I have to now go and count the number of a set bits in this binary form now you your main aim is to count number of set bits in this number so one is a standard technique which you have seen or learned many times is like simply go on in on the entire number while like have a while loop if you have if you find uh the bit last bit as one increase the count and just keep on uh doing a right shift so this is a standard technique which you would know that how it actually happens but if you remembered that this standard technique takes log in time for me n is very small so this log in lat will be four although we have reduced quite a lot but there is also if you have ever gone into the built-in popcor which is actual the built-in popcor which is actual the built-in popcor which is actual standard STL to know number of set bits it actually works on other fundamental and this is a improvised way to count number of set bits that the improvised technique which uh your basic stls to count the number of a set bits for example built in pop count they actually work on finding or getting on to the last set bit which means if I have a number 1 0 1 so what this built in popc count does is it has to count all the number of set bits so he will go firstly on this one again the standard technique which we saw above this one how it will go is it will go in this bit then this and then this let's erase this let's have a zero instead and let's have a zero instead so he will then go this at this is a standard technique where it will go into every bit now the improvised technique is it will go only on the set bits starting from the last set bit he will go on to the this bit then last this bit so you saw number of operations has reduced quite a lot and this is very much significant on the large numbers and we are when we are doing this operation again and again so that is the reason I always recommend use the buildin like buildin libraries now how it works is it goes and grabs the last set bit as I showed you it will go and grab the last set bit and will make it a zero he will go and grab the last set bit and make it a zero that's how it actually works now you can just see okay if the number was a nine maximum number of set bits it can have is actually a three because okay for sure 1 because number is a nine right so 1 0 that can be my actual number eight so I can have a nine so you the maximum number of bits are actually two here but in the worst case you can have a number seven from 1 to 9 which is having a maximum number of set bits so its complexity will actually be a o of three again AR you are going in constants but why because you will see why so now I got to know okay the standard technique will use o of four approach this technique will use o of three approach but I want to do it in O of one because I was already doing an O of n then this reduction is not much more for me and this is not even much for me so I want to do it in O of one itself what am I missing I am missing one thing I if you remembered I only want that the count of odd numbers which means the count of set bits should be one that's it now so I can simply say now that it should not like why the f I do need like why the f I need a v Loop V Loop is need if you want to count all the number of set bits here I don't need to count I just need to know if the count of a set bits if it's a zero or one if it exceeds one it is not even concerned about me I'm not even concern concerned about that specific answer so I don't need this file loop I will just need to know that I will just do one operation which means removing the last set bits now after removing the last set bit if the number becomes zero then it only had one set bit else it had more than one which I'm not concern about because it will never contribute to my answer so what I will do is let's say for this example itself 0 1 0 I will just remove the last set bit okay I remove that if the number becomes zero which means great you had only one set bit but you will see that it is not a zero the number is not a zero it actually number four so this is not a zero number which means it has more than one set bit so if I had a let's say number like this so if I remove the last set bit it will actually become a zero voila you have actually got that this is a specific bit representation which has only one set bit so rather than using a v Loop you just have to apply this operation only once right and check if the number you have formed which means again the operation which I'll teach you that n and n minus one how it actually uh gives you or removes the last set bit but yeah uh after the operation you should actually be getting a number zero if you got a number zero which means you had only one set bit or if I just do operation on a zero number itself then still my number will never be a zero because the number starts from one itself but yeah uh no matter what uh it will just give me okay I had one set bit that's it if that's the case good if not if you have more then simply skip it now what was this a quick recap for you to know that how you actually remove the last set bit if you have a number let's say six you can see the last set bit is actually a this specific one at the first bit I want to remove that so what I do is okay I want to keep the entire left part exactly matching this entire right part should be modified such that the specific bit should become zero and all the other bits should be one this is how my Mas need to be made right and again this entire left part should exactly matching which means everything which is here exactly matching on this right part again whatsoever is here because you know that it is a first set bit which means all the bits will actually for short be zero so I need to make mask such that left part should remain exactly same this specific bit should be a zero and the right mask should all be a one or it should all be a zero it also will work for you but again this right part can be a zero or one no matter what because you have all zeros so no matter what will happen with this is I want this specific bit to actually become a zero so I'll do and operation with this above number with this what will happen is left part will not even change at all and the right part like last set bit will actually become zero so for this to make this specific number what we do is we just do a minus one operation so I had a number six which is 0 1 0 I do a minus one so if you do a minus one then for the last bit from the first bit which you get from the very right you just get you like you just borrow a number from them and then here it will become a two at the first place which means see how a borrow works is if I have a 0 1 0 and if I want to do a minus one so he will borrow he will become a one he will become he'll become a two so I'll do a 1 0er this is how minus one will work right that's a simple minus one which works in maths also now you got a number which is 0 1 0 which actually nothing but nus 1 five exactly same now if I do a and operation what you will see is this bit will become a zero and why it became a zero because this left part remain exactly same and this right part I just wanted this specific bit to become a zero and that's how you can make your last set bit at a zero with this operation again now going on back we have got amazing thing that okay on the leaf operation on the leap when we have got this specific number I just will apply operation n and n minus one let's say this number is n I'll app operation n and n minus one then I'll give this I'll get as a zero which means I had one set bit and I'm very good with that now um that's okay that's completely okay um but what about making this entire tree because Aran last time you told that okay you had a two then you have then you went on to three then you went on to four so you were adding the elements frequency okay you added a frequency of three then you added a frequency of three but how will you be how will you make it here which means for okay uh if you are going in from two that you like you came to three then you for three you added a one but then as soon as you add another three you added a zero for that how apply this operation that's the main operation which you missed yeah I missed it because it's very simple that we remembered that we had this specific number now let's focus on one digit just one number okay I encountered a one so you saw frequency of one increased it became a one so here also I say my frequency again remember that this array is written from left to right while the binary form is written right to left so remember this is the zero bit this is the first this is the second this is the third bit this is how the bits are written now you actually saw that this is the number I trans like I added its frequency so here the frequency was Zero I added one so the frequency became one but when as soon as I added another one came in its frequency BEC zero so what is that operation which actually transformed this which means from a zero I added a one I got a one from a one I added a one I get I got a zero that's a zor operation so I know okay I can simply apply a zor operation to actually incorporate the frequency or basically to replicate the frequencies if odd the frequency will be like if the frequency is odd so it will be a one else it will be a zero so to actually replicate that I'll use a zor operation see that's how amazing this is we used zor we use like we learned bit manipulation we learned masking we learned the like bit uh count of set bits how actually the improvised version is this and how we can actually use that improvised version to actually incorporate that in my answer that's how amazing this question is I loved it cool now so you saw that in the very beginning my path like you can just uh name the variable anything I'll name that as path so initially my path have only this specific value which is true so I made a mask which means the path is nothing but a mask which is 0 1 0 as soon as I'm incorporating a new value which is one so I need to incorporate this new value one in this earlier path itself right so for that for this one value needs to be at the exact location which is this specific location which is the first bit I need to do a left shift which means I need to make a mask of this specific one right so to make a mask of this one what I'll do is I'll make a I just a like left shift one time so what will happen is I'll make a mask as 0 1 0 mask is nothing but that specific bit is set so now what will happen is earlier I had my 0 1 0 which is a path which is the path right this is the path and my mask is nothing but this mask I just do a z operation because I remember I need to do a zor operation to actually incorporate the frequencies odd and even thing so I'll just do a zor operation between path and mask I'll get A New Path which is nothing but a 01 1 0 now as you get the new element which is one again make a mask of it will look like a 0 1 0 mask is nothing but the first bit is set and first bit is okay my first number my number value is one which is the same thing one left shift my node value when my mask is made do a z operation again then you will get a zero as this frequencies which is this specific number and ultimately remembered when you have this path you'll do a path and path minus one if this specific value is a zero which means you had at most one set bit that's it although if like which means that you had at most one set bit and with this you can simply get the answer now let's quickly see the code it's pretty again the complexity is actually nothing but o of n because now you are just going all the numbers this is a number this is just a one number one integer which is nothing but a four this is another integer which is nothing but a 0 1 2 4 6 1 2 4 8 it's a number 12 so this is just a number and the operation which you are performing at every step is nothing but because in the last step you will just perform one operation which is n and n minus one which is a o of one operation it's not even o of four or o of log operation that's one operation because you just are finding the if it has one set bit or not now um coming on back the code will be pretty simple that firstly uh we will have a call from the root and we will give the initial value you remember initial value which will be passed in will be a zero now as soon as it will enter this value it will keep on building this path values for me the specific path values the specific path Valu it will keep on building for me now if I go back uh firstly uh I'll go on only if my root mode is not even n now I'll generate my path as we mentioned that my path will be existing path zor with the mask for that specific value for the specific node value when this path is made I should only and only check on the leaf node I should only check again Leaf node is when both the right and the left are null that is a leaf node for me that leaf note I should check if I have only at Max one set bit if yes then increase the count which is a global variable for me because that is a great path for me and then I can simply go and try for the left and right it is also called as a pre-order traversal but yes we like pre-order traversal but yes we like pre-order traversal but yes we like we don't care we can have anything whatsoever it's just that we just wanted to go on and populate the path doing a zor so as to keep track of only the odd frequency element and then maintaining and getting the last set bit to know if I have only one set bit or not and by that increase the count and again with that time and space to of I hope that you bye take care bye-bye
Pseudo-Palindromic Paths in a Binary Tree
minimum-difficulty-of-a-job-schedule
Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be **pseudo-palindromic** if at least one permutation of the node values in the path is a palindrome. _Return the number of **pseudo-palindromic** paths going from the root node to leaf nodes._ **Example 1:** **Input:** root = \[2,3,1,3,1,null,1\] **Output:** 2 **Explanation:** The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path \[2,3,3\], the green path \[2,1,1\], and the path \[2,3,1\]. Among these paths only red path and green path are pseudo-palindromic paths since the red path \[2,3,3\] can be rearranged in \[3,2,3\] (palindrome) and the green path \[2,1,1\] can be rearranged in \[1,2,1\] (palindrome). **Example 2:** **Input:** root = \[2,1,1,1,3,null,null,null,null,null,1\] **Output:** 1 **Explanation:** The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path \[2,1,1\], the path \[2,1,3,1\], and the path \[2,1\]. Among these paths only the green path is pseudo-palindromic since \[2,1,1\] can be rearranged in \[1,2,1\] (palindrome). **Example 3:** **Input:** root = \[9\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[1, 105]`. * `1 <= Node.val <= 9`
Use DP. Try to cut the array into d non-empty sub-arrays. Try all possible cuts for the array. Use dp[i][j] where DP states are i the index of the last cut and j the number of remaining cuts. Complexity is O(n * n * d).
Array,Dynamic Programming
Hard
null
134
hello everyone and welcome back in this video we will be tackling another lit Cod problem which is called the gas station problem we are going to explore this problem from a couple of different angles so let's read the problem first there are end gas stations along a circular route where the amount of gas at the ISA station is gas I and you have a car with an unlimited gas tank and it costs cost of I for us to travel from a station I to a station i+ travel from a station I to a station i+ travel from a station I to a station i+ one and we begin our journey with a empty tank at one of this n stations um and then now given two integer arrays gas and cost we want to return the starting gas stations index if there is a solution otherwise we're going to return minus one if there is a solution it's guaranteed to be unique okay so let's actually now highlight the keywords here so we can keep an eye on those uh first of all we are dealing with a circular route then unlimited gas tank that's the ability of the car you start with an empty tank what else we going to return so the output is going to be if there is a solution it's going to be the index um of the estring gas state and then um we're going to go clockwise in a circular path and there if there's no solution we're going to return minus1 and if there is a solution it has to be unique that means as soon as we find a solution we're going to stop there because we know that there has to be just one okay so this gas station problem is not an intuitive one um wait unlimit gas tank what kind of car is this and why a circular pass anyway it is what it is so we're going to try to solve it okay so let's visualize an example here and um so what we're going to do is um we're going to assume that we have five different gas stations with indices from 0 to four and there are two indg arrays cost and gas for this input the correct answer is gas station at index three so let's take this car for a spin okay so starting from index three we get four units of gas and the cost is one that means we arrive at index four with three gas in the tank okay now here we get another five gas totaling eight so far but we're going to burn two gas to get into index zero so now we have six in the tank right at index zero what's going to happen is we're going to get another one unit of gas which brings our total to seven now we're going to burn three gas to get into index one so we have four now at index one we're going to get another two that's going to bring our total to six but we're going to burn four of those in order to get into index two so now we have left two units of gas in the tank and then finally at index two we get another three gas which brings our total to five and it turns out we exactly need five gas in order to go back to index number three okay so we just proved that it was possible for us to actually go around this circuit and arrive to tree again so one important observation here is that um if the total gas available across all different station is less than the total cost then there is obviously going to be no optimal solution therefore we can complete the trip only if the total gas available is greater than or equal the total cost okay so that's one thing for now um so what we're going to do next is we will start with a Brute Force solution or approach to gain a deep better understanding of the problem then hopefully we're going to move on to more efficient strategies okay so the approach here is checking each station as a potential starting point and so what we do here is we iterate through the gas station starting at each station and then checking if we can compilate a circuit without running out of gas and then we'll repeat this process for each station and we return the first station that works if we couldn't find any we're going to return minus one so there is no solution for this problem so let's say we have five station what we're going to do uh is let's say for example we're going to start from station number two so what's going to happen here is um we can't just increment the indices linearly right so this is not a linear kind of pattern we need to create a circular pattern so we can do that probably the easiest way to do that would be using the remainer of division by n which is the length of the arrays gas or cost okay so let's code this up and see what do we get okay so this is a very simple implementation of this idea in line number four we're going to Loop over for all possible gas station then for each subsequent station in a circular pattern we check whether we can make it that far if we ran out of gas what's going to happen we're going to break out of the loop now you might ask why do we need line 11 and 12 here okay so um this is to make sure we understand why we got here in the sequence of the code so did the loop break if that's the case that means there was no solution for that starting point so we have to check we have to try another starting point but maybe the loop was terminated successfully if that happened that means we just found a solution right so this these two lines are just to make sure we actually know what's happening now let's see what do we have here this gives us a correct but quadratic solution we definitely have to try to do better so let's see if we can do better um the next thing we're going to do here is let's take a look at a different example so hopefully this example can motivate us to do better um and what we're going to do here is again we have five stations and we are given two arrays cost and gas this time we begin our journey at um index zero and see how far we can go okay so let's begin so we're going to go all the way up to index 3 that's it so we started at zero and we made our way to index 3 but couldn't reach four in fact if you sum everything up you will see viver short for two units of gas here otherwise we were able to do it right we could have been to able to do it if we had an extra two units of gas but we didn't okay so if you look carefully here you will see that next we don't need to try indices one or two if we do so it's guaranteed we get a stock at three again therefore starting from I if we get a stock at J that means starting from anywhere between I and J won't work either so if you don't see why as this think about it this way when we got from 0 to one that means our leftover guas was non negative so if we didn't make it with zero we won't make it without it right it's only going to help right now if you don't have zero if you're starting from one we still not going to make it right because we didn't make it the first time around and um now let's get back to the problem here the next thing therefore we're going to do here is starting from J + one which is going to be index 4 J + one which is going to be index 4 J + one which is going to be index 4 right so that means we have to basically go through this circular pattern here and now if you look closely you're going to see another very interesting thing here um actually you can see that we already solved a big chunk of this problem in the first time around so what does this means is we only need to check the balance of getting from four to zero because we already know how hard it is from getting 0 to four so we already know that if we had an extra two units of gas we were able to make it now all we have to do is we have to check going from 0 to 4 or actually Four to zero here sorry um if the balance is going to be greater than or equal to positive2 that means four is going to be the answer otherwise we're done and there is no solution to this problem so this is going to be our observation number three now we have three very important observation what we going to do next is we're going to take advantage of all these three important observation we made so far and we're going to solve we're going to try to solve each sub problem using dynamic programming only once in a bottom of fashion so for example observation number three tells us that um if we don't actually realize these characteristics of the problem we're going to end up solving sub problems more than once so how do we fix this so let's take a this very simple implementation that we're doing uh what we're going to do is we're going to try to solve each s problem only once and then we let we're going to keep track of our total gas balance passing through all a station okay so this is how this is going to work we're going to Loop through each and every station then we're going to check um we're going to have one variable total gas which going to help us check whether there is a solution at all based on our observation number one we want to make sure that we get our total balance is positive right or zero it has to be non- negative if there's a solution and non- negative if there's a solution and non- negative if there's a solution and then the current gas helps us kind of identify the optimal starting point in case there is a solution Okay now what's going to happen is um when we actually run out of gas we going to update the start index jumping I units forward this is going to be based on our observation number two but that's just for the index I want you to realize that it does not change the order of the sub problem you're solving here okay so at the end if total gas is non- negative that means there must be a non- negative that means there must be a non- negative that means there must be a solution and if that's the case we know where to find that right the optimal starting point is a stored in invariable start and we're just going to retrieve it from there now okay let's see what do we got here this is a linear solution amazing cool but um one thing though um this problem is tagged as greedy on lit code which is confusing to a lot of people if you're thinking what's greedy about this problem then you're not alone many people refer to our last solution as a greedy solution which is which does not quite make sense but to be fair it's possible to approach this problem from a greedy perspective the question is whether it's going to be a better solution or a faster solution or not so let's see um there's one way of doing it and let's not mistake this idea with our solution um so what we were doing is we were passing through all stations once while this solution is more similar to our Workforce approach and we are solving some problems again and again here but we're going to skip some Stations between I and J for the next starting point now here is a more interesting one let's make a greedy Choice by starting with a gas station with the highest gain which we can Define as the maximum um positive difference between gas and cost so the station that has the maximum difference of gas and cost and um we're going to start with that because that is going to be the most helpful or the best place to start because we're going to be going to we going to keep the most amount of gas in the tank moving to the next station right so this is definitely a greedy choice and if that didn't work what we're going to do next is we're going to move to the next or the second highest gain second station with the highest gain and we keep trying our greedy choices moving forward so instead of trying things linearly we're going to basically try different starting point using our greedy Choice here but wait a second should we actually bother coding this up Pro probably not right because both of this will be slower than our current DB solution um depends on the implementation the best we can achieve here would be un log in all right that's for now thanks for watching and I hope you enjoyed this video take care and I will see you in the next video
Gas Station
gas-station
There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`. You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique** **Example 1:** **Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\] **Output:** 3 **Explanation:** Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index. **Example 2:** **Input:** gas = \[2,3,4\], cost = \[3,4,3\] **Output:** -1 **Explanation:** You can't start at station 0 or 1, as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. Therefore, you can't travel around the circuit once no matter where you start. **Constraints:** * `n == gas.length == cost.length` * `1 <= n <= 105` * `0 <= gas[i], cost[i] <= 104`
null
Array,Greedy
Medium
1346
179
Hello friends in this section they want a discussion let's see problem log just remember give very common question in which interviewer you will give up and they are all and positive integers only negative numbers unit arrange all the member since they came from the largest number of Times result will be released and limits result industry for example in 500 to 1000 example in various combinations subscribe is divine largest possible member they can form after which let's discuss the logic will not be a simple number best settings and definition of but you should be done in This You Ca n't Get the Desired Result Example Fire Shot in More Will Take Another Example Naughty Adverb in Which is Gold in Ascending Order Descending Order 909080 Defending It's Proven to Be Sorted Out What is the Solution 220 Problem Candidates Should by Using String Comparison Be Sorted Let's Understand Better First and Clean Thup Vintage Same List as Example Input and He is the Will Be Used For Possible Combinations And Values ​​Will Be Uninterrupted Subscribe j&amp;j Amazon Form 300 3053 Note 3 j&amp;j Amazon Form 300 3053 Note 3 j&amp;j Amazon Form 300 3053 Note 3 Apne Pati Saif Baje Entry Not Realities In Products Cutting Is Request Interactive Sessions Will Be Or I Will Form Pati Floor And Vijay I Will Form 343 Isse Zeenat Vivaah J-34 Will Be And Shyam Are Oh Zeenat Vivaah J-34 Will Be And Shyam Are Oh Zeenat Vivaah J-34 Will Be And Shyam Are Oh That I Will Form 345 Ujjai A Joint Form 535 Sims Pay Both img35 Will Be In A Position To That I Will Form Fifty Shades Noida Will Form 1948 Se Via Agni-5 Will Hear No Form 1948 Se Via Agni-5 Will Hear No Form 1948 Se Via Agni-5 Will Hear No Evil With A View To International Jewelery Are All Positions I Will Be The Next Indian Idol Behavior Will Be Always Be I Will Be Form Ki Stree Apne Pati J I Will Form 33333 Wap.in Jain Wap.in Jain Wap.in Jain Ki Stree Will Be Hua Thirty Will Be Ki Na Interactive Sessions Will Move On Hain Na Paaye J Will Form Husband Floor N J I Will Form Addition This Jeanette Ifflu Again Will Affect Both Eyes And Values Your Husband Then Cats Woman Will Bear Next Generation Will Move On That Boat I Will Form 350 500 Add Will Form 535 Science Paper Of A 5th Floor Will Appear Again Vvv The Real Danger Look I Will Be Hair Gel Will Be See Situation I Will Form Trinetri Jai I Will Form Pati Ne Bigg Boss I Will BJP Jai Hind This Iteration Eyes Will Form Pati Firoz Se I Will Form Additional Ft Agent 335 Wills Pentagon And Foreign Pati Fig Tree Again They Will Tree To That I Will Be J Will Be I D J Will Form Trinetri Es J I Will Form 33333 Will Share With All Members From Left To Write Will Give Us This Exactly Matching With This Number 95 3430 Addition To Avoid Fried Food Explain Shopping Logic To Make You Can Be Used Lubricating Oil Writing Digital Signatures Fruit And Number Which Takes Neither Egg Basic Well Written In Let's Converter inter interesting karne swayam letter they can simply singh first created strs vich sm lenge on the internet that nowhere to wait for the interact jhal how to convert all things interesting in inch attraction and don't thing e jhal hai na values ​​side resort function from values ​​side resort function from values ​​side resort function from Arabic prewedding com Pressure Implementation Jhal Loot Will Provide Compressor Inland Format A Minute Kavno Decade Here What Is All The Input Number Seven Zero Sindh Input Tray The Final Largest Number Of Us Must Be Remember Its Let's Check Settings On Input Number Most Difficult Amit First Index Nifty 0.30 Name of two person has builder to open all your friends you jhal that return result now interruption recording letter code have already written death sometime we have to input adware calling largest number with his to input service return home run time error on result end 8 And Expected This About How To Solve Jis Number Problem Ho To Like Thank You For Watching My Video And Subscribe Thank You
Largest Number
largest-number
Given a list of non-negative integers `nums`, arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer. **Example 1:** **Input:** nums = \[10,2\] **Output:** "210 " **Example 2:** **Input:** nums = \[3,30,34,5,9\] **Output:** "9534330 " **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 109`
null
String,Greedy,Sorting
Medium
2284
45
hello and welcome back to another Elite code problem today we're going to be doing the continuation of Jump game one which I did earlier and so this time we still have the zero index array of integers of length n where positioned at n0 but now the difference is first of all we are guaranteed to reach the end so and we also need to return the minimum number of jumps to reach the end and so remember from each Square we can jump so we have something like over here the most we can jump is whatever this number is so we can jump anywhere from one to this number so we can jump one or two and then if we're here we can jump one two three and so on and so let's think about how we would do this so a really pretty straightforward if you've done Dynamic program solution is just have a visited set and then at every index just try to jump all of the available jumps right and then just DP to all those so like for example here you would have you know you'd have an index in your DP and then you would say okay let's try to jump one or two and then take the you know the maximum of those and so you can definitely do that but that's not the optimal solution because I think that's going to be N squared because you're going to have a for Loop in your DP and so even though you only have um I number of states you're still going to have four Loops you're still going to try to jump to like multiple places and so let's think of a better solution and this is not super intuitive to be honest because it's uh yeah it's not super intuitive so but we can think of it so instead of doing a DP let's just think of something like a bread first search and I think if you think of like how do you do breadth first search here it's going to get a little intuitive on what to do and so what we're going to do is let's say we're going to have a breadth first search where we're going to have some kind of like what do I want to call it some kind of range of numbers sorry so we're going to have a range of numbers and we're going to have a left and right pointer so we're going to have some kind of range so let's just draw it like this and our initial range is going to be the first number and so what we're actually going to do is we're going to keep track of like what's the furthest number we can jump in our range and that's going to be our new Range so the furthest number we can jump to is 2 which would be over here right and so once we go through every number on our range the furthest number we're going to be able to jump to here so then we're going to make it a new range and then the new Range the rightmost index is going to be the farthest we can jump and the left is going to be the number right after the one we were just at because we already checked this one so whatever was over here we don't care and so now we're going to go here and we're going to do the same thing we're going to say what's the furthest we can jump to and so the furthest we can jump to so we'd go through every single index and then we'd figure out what's the furthest we can jump to so we're here and we just try to so this is going to be like a greedy solution we're going to say the furthest we can jump is three so that's going to be over here and then here we can only jump over here so now the same thing uh so now the furthest we can jump is to this Index right and so now that's going to be our right bound and our left is going to be over here and so then we would say oh we've reached something and then we just figure out so every time we switch these like left and right pointers we would just add one to our result so hopefully that makes sense it's pretty straightforward but you just take whatever is in your current set of things and you just say what's the furthest you can jump to and then you make a new range and then you just figure out how many times did I make any range and that's going to be like the maximum jumps let's try to do that same thing for example two so let's draw this out it's definitely tricky to come up with but once you come up with it's actually pretty straightforward for like a greedy just jump the farthest and see like what's the farthest I can go okay so let's do the same thing okay so we're gonna just use different colors to show like the brackets so remember the first is over here the furthest we can jump is over here so then our new range is going to be here and then now the furthest we can jump is over here and so our new Range again is this and so yeah we now we literally just count up okay how many of Rangers did we have so we'll just increment or we'll just increment our counter every time we go to a new Range so remember the left so the left is just this old right plus one and then this right is the furthest we can jump right so this is like the max we could jump from all of these and same thing here right the max we can jump from all of these is over here and then the left is this old right plus one so pretty straightforward so let's try to code that up so we're going to have the left and a right pointer right they're both going to start at zero and what we could do is what's our Edge what's our like ndk so we'll just say hmm what we could do is we do want to make sure that we're not out of bounds but I think we could just have an infinite Loop and then once we reach the index we want then we can break so let's try something like that so I'll just try like a wild true type of thing so remember we're going to want to go from so actually now that I think about it when we so even if we make a range that's out of bounds I don't think it's going to matter because if we have something like this right if we have like some numbers whatever and our range is like this the thing is we're always going to reach the last index and we're going to check for it before we're out of bounds so it should be totally fine so we can just have a wild crew Okay so we also need a res so let's just have a res and then I'll just make that zero okay so first thing we need to do this is this okay so first thing we need to do is we need to increment res right because even if even in the first like part uh this is already actually is it a jump no it's not a jump right so we don't need 10 cameras we can increment res at the end I believe yeah because like if our numbs length is one we should return zero right because it's number of jumps I think see maximum length yeah so far array is like this then we should return zero here so we are in cameras at the end okay so what we want to do is we want to have a Max jump right so we can just do Max jump equals and we're trying to maximize that so pretty straightforward so let's just make that we can honestly make it zero it should always be greater so we need to make a negative Infinity so we're going to go from left to right so we need to have a four I in range left to right now we need to say if we did get to the last thing right so we do need to check like are we at this last element if we are we need to return straight away just to make sure we don't get out of bounds so that's going to be if I equals nums minus one we can return straight away so that's going to be a return res okay else we need to see what's the farthest we can jump and then record that so that's just going to be Max jump equals Max jump and what's this going to be this is going to be the index we're currently at Plus the now the number at that Index right so numbers I so like if we are at index just delete this again uh let's actually make this black put this over here yeah so if we're at like if we're at this index the max jump is whatever index we're at so this would be index one plus the actual number so that'd be one plus two right because we're going to be greedy once again so we're trying to figure out like the farthest thing we could have okay so that's going to be that so now we Loop through we calculate our Max jump now at the end we have to update our left and right because like if we had some kind of like BFS range our new range is going to be this number is going to be the left and then the right is going to be the farthest number we can jump to so that's the next jump so we update it here so that's going to be right plus one and that's going to be Max jump now we update res because now we are entering into a new Range so that means we made a jump okay and this should never like because there's a result we should always reach your number I think so let's try that see if we screw anything up it looks good yeah cool and I think this is going to be an efficient solution so yeah it's 60 so this is as efficient as it gets now yeah you got to recognize that this is big Omen because we are only looking at each number in each range once and we're constantly updating the range right so this is going to be Big O of N and this is Big O one space so time Big O of n space we didn't make anything else yeah you can put up a dynamic program but like I said for a dynamic programming you're going to have to Loop through your number so let's say your number is like for example um like a million or whatever you're gonna have to like do you're gonna have to try each jump because you because it's not guaranteed that you just want to jump as far as you can like in the other problem we're removing the where we're moving the end here the you know like in this case we actually want to jump one here instead of two so definitely not the most intuitive solution to come up with but kind of a cool one so I wanted to share that with you guys and hopefully you like this video and if you did please like And subscribe and I'll see you in the next one thanks for watching
Jump Game II
jump-game-ii
You are given a **0-indexed** array of integers `nums` of length `n`. You are initially positioned at `nums[0]`. Each element `nums[i]` represents the maximum length of a forward jump from index `i`. In other words, if you are at `nums[i]`, you can jump to any `nums[i + j]` where: * `0 <= j <= nums[i]` and * `i + j < n` Return _the minimum number of jumps to reach_ `nums[n - 1]`. The test cases are generated such that you can reach `nums[n - 1]`. **Example 1:** **Input:** nums = \[2,3,1,1,4\] **Output:** 2 **Explanation:** The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. **Example 2:** **Input:** nums = \[2,3,0,1,4\] **Output:** 2 **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 1000` * It's guaranteed that you can reach `nums[n - 1]`.
null
Array,Dynamic Programming,Greedy
Medium
55,1428,2001
105
construct binary search tree from preorder traversal and will solve this problem and then also maybe do some drawing to explain what happens return the root note of a binary search tree that matches the given preorder traversal if this is the tree and then preorder traversal is if we start with DFS in the root the first visit the vertex aside then we go to a child left child first here we have 5 so 5 is the next number and so on so it's when you run the efest from the root every time you enter a vertex for the first time you write down its number for this input we need to output some vector presenting this tree there is your definition of a struct every node has value pointers to left and right and we have a constructor with which we can create a new node like that first thing is recall that may be also definition of binary search tree for every node and in descendent of not let has the values smaller than my value and then in descendant of right node has value greater than this thing so 8 after 8 everything smaller than is here on the left part writer on the right part so after getting this sequence I will say this is the root right here after that everything that is smaller than me goes to left part everything greater than me goes to the right part there for sure several ways to do that but the length of a sequence is small so even quadratic complexity should be fine at the end we can think if we can do better than that but do I want a new function maybe not this different pre-order if pre-order this different pre-order if pre-order this different pre-order if pre-order empty and then return no I don't want anything otherwise there is some first thing rod value that say is pre-order of zero now we gather everything that is smaller than this and greater it should be we should just go to the end everything other than the very first value pre-order size.if pre-order of ice pre-order size.if pre-order of ice pre-order size.if pre-order of ice smaller than road volume smaller pushback this value as greater for example for this sequence 507 would be smaller 1012 would be bigger 3 note left sound left child is BST from pre-order I run the function that is pre-order I run the function that is pre-order I run the function that is created here it should be able to build binary search tree based on a sequence given a sequence smaller go to the left bigger go to the right ste from pre order greater and I need to create 3 node of X oh here I get just this value 3 node I don't know root is this of root value by default left and try to become no and here I will say root left is this and root right is that need to return a pointer to their root empty there's some typos or is it run again in this week like you might already have noticed I'm not doing things with timer something is wrong with memory let's try to debug this a little bit print root value and let's say also smaller that size and greater that size for this test I should see 8 3 and 2 8 4 into 4 1200 like every function got here then I ran a smaller function smaller one 1001 and that seems right maybe the issue is that I create note here and then it gets destroyed okay I struggled with this a little bit and I think I'm missing a keyword new but I don't understand it well enough to explain what it does it basically allocates new memory no available conversion from this to that it's just pointer this should do a job seems right submit accepted and this is quadratic complexity let's try to get something better than this but first analyze what happens for this sequence I take 8 I create a root out of it then those two are vectors of smaller values and bigger values than height I know that 5.7 will be bigger so I run recursively 5.7 will be bigger so I run recursively 5.7 will be bigger so I run recursively for sequence 5 1 7 I create some tree and what will be returned is pointer to a root of that tree there is some tree here right I don't need to know how it looks like and then I say left child of 8 is this one and doesn't matter what exactly happened here recursively this is done similarly for 10 comma 12 for this I run our cursive li it gives me a root of that subtree and then I said this in particular if this is empty then this would be a null pointer this is how we create a tree and why this is quadratic because on every level I go through the rest of the sequence is it possible that I will go like that n times yes an example of that is a sequence like 1 comma 2 3 and so on a sorted sequence because then for 1 this is a whole vector of size n minus 1 it's on that this true will be balanced or something like that it will be 1 it took me linear time to find this vector then here for 2 to n again it will be 2 but and I will linearly go through that then through that and so on the number of operations is n plus n minus 1 and minus 2 and minus 3 and so on in total in this case of an Square and eerily this n square is achievable like that can we do better without going through the array again and again I can say that 8 is the root and let's say that every time I pass this vector by reference or it could be global now I know that I need to do something with this number and by default for some time there will be numbers smaller than 8 so I will say that I go recursively to the left child of 8 and I have some pointer pointing to 5 because 5 is a number I need to take care of right now I will put it here and continue in some way but eventually I need to know that when I hit number greater than 8 this isn't first number greater than 8 I need to stop my recursion in the left part I need to now move to the right part is it may be possible who can they run recursively here on the left part remembering the value that is my limit when you hit something greater than 8 stop I can go recursively to the left part and remember the limit it will be something like recursive like whatever the function is called of index this is let say ID of a number I need to take care of right now and some limit a value and I will say if my current number at position ID if it's greater than limit then stop doing anything there with that recursion and every time the logic will be to put the current number as a root then go recursively to the left part but also if this value if let's say here instead of 5 I had 9 then already I should say oh no this doesn't go here instead I should go to the right part right child let's try to count it if pre-order empty then return null if pre-order empty then return null if pre-order empty then return null still true root value is this and I think I can leave this and I my name is to get complexity in both time and space often this is the go root value this create that the end will return the root but everything between will change route left is beastie from pre-order where I left is beastie from pre-order where I left is beastie from pre-order where I get pre-order but let's get something get pre-order but let's get something get pre-order but let's get something more I will create a private function recursion or help or something like that it's exactly like vista from pre-order it's exactly like vista from pre-order it's exactly like vista from pre-order but not only it gets this but also ID where I'm currently looking and limit where if I accept this limit I shouldn't go further if I D sequel pre-ordered go further if I D sequel pre-ordered go further if I D sequel pre-ordered sighs if I'm already out of the array or pre-order of ID is greater than limit pre-order of ID is greater than limit pre-order of ID is greater than limit return you'll do nothing otherwise do this pre-order of ID and run this pre-order of ID and run this pre-order of ID and run recursively over there helper of pre-order ID plus 1 and limit is this pre-order ID plus 1 and limit is this pre-order ID plus 1 and limit is this for example I will there was eight above now I'm down at five I need to say below I can I'm okay with everything with value smaller than five this is my left child what about the right one yeah what I did do I pass there I don't know how many values were taken to use on my left child instead I can every time passed this ID by reference or even better it's equivalent but I'm doing that just for clarity for you what if the RI is now global pre-order let's say that it's numbs but pre-order let's say that it's numbs but pre-order let's say that it's numbs but it's a sinus pre-order and this and ID it's a sinus pre-order and this and ID it's a sinus pre-order and this and ID and now every time when I do something when I use value at position I did then I say ID plus what if this was the case this pre-order will not change at case this pre-order will not change at case this pre-order will not change at all but ID there is one global ID I keep track of what number I'm currently deciding about route left is this and what about route right help her off and now the limit for the right part let's think looking at the drawing for a moment when I'm from eight let's say omit it is route when I go to the right part I'm okay with number like 10 so is there no upper limit there might be it's a function some parent function could pass me some global limit because maybe eight is a left parent of 15 forget about this for a moment if I just left parent of 15 then here values must be smaller than 15 so you're the limit from above matters do that and then return route this will be a helper function but let's make it more professional global variable stuff like that terabit so this is better then I need to also pass them cows next to pre-order means pass them cows next to pre-order means pass them cows next to pre-order means I'm not going to change it I did pre-order and that would be eat what am I doing here I need to say ideas 0 written helper of pre-order the end limit is int helper of pre-order the end limit is int helper of pre-order the end limit is int max there is no limit initial let's remove everything after that and try to fix compilation errors if there are any now I improved from and Square to linear complexity here we go so don't worry about that's the full thing why won't we analyze what happens for this sequence this arrow will denote ID initially it's a tight I am recursive function with upper limit equal to infinity into max and I create root inside I go to the left part I move ID by one because I use died it is like already done I don't I will not do anything more with ID and as long in this sub tree there is upper limit of 8 as long as values are smaller than 8 I will put them there I'm looking at 5 is indeed small relate and put it here go to the left part ID moved so 5 again is done completely and in this left part I'm with upper limit 5 as long as numbers who there will be 1 2 3 4 of may be 0 minus 1 minus 2 I'm okay with negative values then I would continue here 1 ID moves so equivalently we can say 1 is removed is done now I try to move to the left part with upper limit of 1 and now I'm looking at the value 7 it's not smaller than 1 so here value null will be returned then I'd move to the right child of 1 and what is the limit you can stop now for a moment and think about that upper limit is five this subtree is subtree of values more than five so even though from one I go to the right part that per limit is five so in if instead of this seven it was far here I would put four over there but not it's seven is not smaller than five delimit so I return null pointer and now one is already created with both children so I move up now I'm at five I'm trying to create right child of five upper limit here again is eight this is a limit in the subtree the upper limit aside when we go to right child we use limit from our part whatever he passed to us so seven can be used here we move to ten seven is used Canton be used here no it cannot it no cancel Canton be used here it cannot it's no because here we have upper limit of eight here we had upper limit of seven blah this is created so this is returned to a parent function and now here right part tries to be down then go here upper limit 10 looking at 12 cannot be done so no and this is finally 12 oh that's everything I hope you enjoyed this if you want more tutorials about binary trees binary search trees things like that let me know in the comments and I might do it after I'm done with this 30-day do it after I'm done with this 30-day do it after I'm done with this 30-day late code challenge hope you enjoyed this one bye
Construct Binary Tree from Preorder and Inorder Traversal
construct-binary-tree-from-preorder-and-inorder-traversal
Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_. **Example 1:** **Input:** preorder = \[3,9,20,15,7\], inorder = \[9,3,15,20,7\] **Output:** \[3,9,20,null,null,15,7\] **Example 2:** **Input:** preorder = \[-1\], inorder = \[-1\] **Output:** \[-1\] **Constraints:** * `1 <= preorder.length <= 3000` * `inorder.length == preorder.length` * `-3000 <= preorder[i], inorder[i] <= 3000` * `preorder` and `inorder` consist of **unique** values. * Each value of `inorder` also appears in `preorder`. * `preorder` is **guaranteed** to be the preorder traversal of the tree. * `inorder` is **guaranteed** to be the inorder traversal of the tree.
null
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
Medium
106
1,048
Hello Hello Ajay how not to forget because this question is in such a way that we will be decided the year in it all which he can now understand that there is voltage exactly press any one letter in such a way that we Wada jo market jo order change ki war due to which both of them are ABC BBC and try this, whatever change does not happen, if these two, whatever order we have here is also seeing changes, then British will be there only when jo There is a word inside it, only and only, we can accelerate it and along with it, we can keep the old one there and it has increased even more because the match is taking place, so I am here, how can there be any confusion, then in that condition, if the first word is that, but World Cup. Sugar has been taken, by the way, its next one is curved and in the same way till the hour we are getting whatever is there, the second thing is that whatever chain is being changed, we change it so that we all who are in the list of the year. And the long s, how much is possible, it is not possible in this way, here we also, how much will be, if we look at the question, here we have been given a square egg in the input, now this what is that, here But if we look at the next, if we add anything here, then this is what it is, we are not able to do it means that we can just appoint one and this in both of the two, if we look at this which is this, next. So here is what we have this groom and the topic is described both will match now this bill is in that direction if we do that in the middle then that is me but if we are only one then if we are the people who are iron and Here, if we have that we can take it here, then if in this example, if we heat it here, if there are beads in Russia, if we add C, still the case will be found on Friday, then in that condition, whatever our longest Word is channel, we will get it retailed, we will look at the second example, in which also a BCE has been given, PC If this is so, then according to that, if we cross it, inside it we will get Chapter i.e. demand that if you are adding Chapter i.e. demand that if you are adding Chapter i.e. demand that if you are adding then what will happen in that condition, give it here but here that in that condition, this Justin, now this will be subscribed, so here we are also getting one thing which is given in the list. It is not necessary that I was found here in the same way but it is an example. You must be looking at it. At that time, we have to keep in mind that the time spent in inputting should be soft. It is not necessary that such question should be asked now. How would this group fast mission work, so to see if it is a good option, we will first look at whatever question we have that if we know from anyone that you think, this is the first thing in the list. It is not necessary that we will memorize all this in school. Now suppose this is our example and we are looking at the same Payagpur question, then what will we do now that like here we will add first in its pure ghee and which is Apart from that, if we are able to make it according to the other Karan, still we will make that also in this, we will break it and here it happened in the same way in all the villages and I have completed it. Got it drinkable, in the same way everyone else's it is over, now we got it, so we know that it is there and wife, now what will we do in that condition, give this to her, now you will fill it in the same way, rotate it completely and from that It is being said that it will be towards everyone that return but something happened in it in such a way that what we have to do is to go to the office, so after all the excitement, I want Redmi, I am getting it but where will be the problem here that if we So after that if it is like now here Happy See Next 20 Years of Toe Sara Jo Word Hai Usko Me 151 Kauai Sumit Chat will have to be done that whoever of ours is sincere but there is even one on Malaysia then whether he is British or not and for that The time quantity will also increase and if you are getting the partner started in the Jones storage, then his spermicide will also increase, so this is simple submit again Hussain Haq, which is the logic money we had folded, now this complete male was given to him like this. Now what will we do is that we will take it and add the expenditure there which we had done, that is, we will start it if we got it in job or input, now we have this also in the chamber, we will do it in the same way in our Pass job small now what will we do so as we know that whatever our preserve will be this we are the only one and only one so the next one is that as we are here this now we this and subscribe now whatever we here that First of all, if the default i.e. that of that First of all, if the default i.e. that of that First of all, if the default i.e. that of low medium ward has been made, then we will make it lie according to whichever team Sachin will be in this match. Also, the word inside it which we are hitting is British. To check whether we will take a different copy or not, what will we do by using this and the first one of those two is found, so as we have removed it like this and from that, it will not be like this, so in that condition which In this, we must have given the index along with the app, that index and the index which we have just sent, whichever will be our maximum value, we will leave the SIM volume with the add aloe vera, now we will discuss that in the next time. Now we will check the school like we have just set it up and that too we had said that we will take out the quarter mind in the subscription, if tent and nursing will be done then we will cut this also and for that now we can do this if If it is available, it was according to that, whatever we do, we will fold it like this, subscribe and whatever we get in maximum, we will get two tents made, this is our Play Services, in this we have given the school as per 1 hour, so that we complete this and subscribe. Because we use Subscribe now that inside that we will have the posting value that will be that and the wedding will be in Delhi to-do list according to that now Subscribe was busy in the village and hers is that Subscribe like and do whatever according to that and If I subscribe to this, whatever is the maximum according to that mountain and the index that will be in front of it, we will add it to it, in this way now we are in one, the whole tension will be over as it was there too, all this will be our result. We will get the result and whatever happens in our wards or in our country, will be left in the root. Now we are getting it tested so that at that time we will be able to complete it. If we are complete then we will get it done, so if you are subscribing then it will be unlocked pulp and now you will have committee in it plus, and that is all your lenses, now let us avoid the character in the last and along with that If he is doing grease then give it accordingly that he will be there for Big Show and Support as well as interest and intel internal storage space for Congress and that space quantity in between. Subscribe to Bigg Boss, like and share with your friends. Subscribe to the channel till then bye with the video
Longest String Chain
clumsy-factorial
You are given an array of `words` where each word consists of lowercase English letters. `wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`. * For example, `"abc "` is a **predecessor** of `"abac "`, while `"cba "` is not a **predecessor** of `"bcad "`. A **word chain** is a sequence of words `[word1, word2, ..., wordk]` with `k >= 1`, where `word1` is a **predecessor** of `word2`, `word2` is a **predecessor** of `word3`, and so on. A single word is trivially a **word chain** with `k == 1`. Return _the **length** of the **longest possible word chain** with words chosen from the given list of_ `words`. **Example 1:** **Input:** words = \[ "a ", "b ", "ba ", "bca ", "bda ", "bdca "\] **Output:** 4 **Explanation**: One of the longest word chains is \[ "a ", "ba ", "bda ", "bdca "\]. **Example 2:** **Input:** words = \[ "xbc ", "pcxbcf ", "xb ", "cxbc ", "pcxbc "\] **Output:** 5 **Explanation:** All the words can be put in a word chain \[ "xb ", "xbc ", "cxbc ", "pcxbc ", "pcxbcf "\]. **Example 3:** **Input:** words = \[ "abcd ", "dbqca "\] **Output:** 1 **Explanation:** The trivial word chain \[ "abcd "\] is one of the longest word chains. \[ "abcd ", "dbqca "\] is not a valid word chain because the ordering of the letters is changed. **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 16` * `words[i]` only consists of lowercase English letters.
null
Math,Stack,Simulation
Medium
null
530
hello and welcome to another Elite code problem today we're going to be doing the problem of the day for June 14th it's going to be a minimum absolute difference in a VST so given the root of a binary search tree return the minimum absolute difference between the values of two different nodes in the tree and so what you should know in a BST is the Val the values are already sorted and so the rules for a BST is the nodes to the left of the root are strictly less than the root or like yeah and then the nodes to the right of the restrictive Creator so for example for four actually just draw this out so for four we have a six we have two three one okay so for four everything to the right of four has to be greater and which it is everything to the left of four has to be less same thing for two everything to the left has to be less than two everything to the right of two has to be greater than two but it has to also be less than four right because everything to the left of four has to be Lesson Four and so we can use this to our advantage knowing that a binary search tree as opposed to a normal tree is already sorted so if we actually look at the numbers in what's actually the nice thing also is an in order traversal for a tree will give you a list of sorted numbers and so in order to remember is Left Right root or sorry it's left root right so let's take a look what that will look like we'll start here we go left as much as we can so left okay so let's have our traversal here so we have a one now we can't go anymore so we recurse back up two now we go to the right you can't go anywhere else the curse back up can't go anywhere else records back up finally go to the right trial and so if you actually look here because of the way the bsts are written the minimum absolute difference in a BST is going to be between two consecutive numbers because for example if I have a difference between two and three that's always going to be smaller than the difference between two and numbers that are passed through right because they're sorted so if you have a sorted list the minimum difference is always going to be between two numbers that are right next to each other so it's going to be either here so one way to do this problem is to actually do uh you know in order traversal you store all these numbers then you just for every two numbers just compare the difference so here would be like one two and so this would be one and let's look at the other example zero 48 12. 49 okay so here let's take a look at what are in order to reversal would look like so we start at one go left as much as we can so right here can't go anywhere else zero can't go anywhere here occurs back up one all right can't go anywhere so now remember we go left as much as we can so we're over here 12. can't go anywhere from here of course back up okay now we take the root and we go right and we are done and now let's take a look at our differences again so we have one so that's already going to be the answer is one and that's our answer because then nothing can be smaller than one so that's how you would do this and it'll be pretty straightforward you can just have an array and then every time you visit a node you can just Mark that value in the array now what we're actually going to do here is we are going to do the same thing except we're not going to use the array so because we don't need the whole thing if you think about it for a new order traversal if we just have some values right all we need is like the value that we're at and the value before and so for example let's actually show you what that's going to look like so let's say we do this traversal so we started at one we go down to zero and we're going to make our initial value before infinity so that way our difference is going to be maximized and so let's just have a res here and that's going to be Infinity as well to start off and we're going to try to minimize that so we're at the zero this is a value we can't go anywhere else so we're going to remember we're not gonna have an array so we're just gonna have a last value let's call that L and then we're going to have the current value so our initialized last value is going to be Infinity as well so everything the last value is going to be Infinity res is going to be Infinity so let's actually I think it's bigger read some stuff cleaner okay so we are at the zero node and we're going to say okay we're at a node we're actually we actually care about this node so let's just compare the node that we're at minus the last value and so that's going to be and it's going to be absolute value as well so it's going to be L minus the current node we'll just call it C and so that's going to be Infinity so is infinity less than infinity no it's not so it's actually also just let's initialize this to Infinity okay now so Infinity's not but now we need to update the last value to the current value we're at because then when we go to another node we need to compare that to the last value so this last value is not going to be Infinity anymore it's going to be zero we recurs back up now we're here and we need to do the same thing so we need to say okay we're at this node what's the difference between this node and the last value well it's going to be one minus zero so that's going to be one now is the result smaller than one yes it is so that's going to be one now we need to update our last value again so last value is going to be 1 now then we're going to go to the right now we have to recurse down here first right we go left root right so we're at this 12. we can't go anywhere else do the same thing so what's our last value is one what's our absolute value well it's going to be 1 minus 12. that is going to be 11 because absolute value is result less than 11. no it's not okay now we make our last value 12. recurse back up so we're at this 48 do the same thing 48 or it's actually going to be sorry it's going to be last value minus 48 it doesn't really matter because absolute value but it's going to be 12 minus 48 36 here it's 36 less than result no it's not update last value would be 48. go down here okay so then we have 48 minus 49. it's going to be 1 as well is that less than result no it's not and we update finally last value would be 49. so instead of having this array right of numbers of an inverse reversal all we really need is a last value and a current value and then we just can simply take the difference here and then that we just keep doing that and then we just see is that smaller than our previous results and so that will allow us to do that and let's see what that would look like actually for our so let's say our numbers would look like this right so we'd have 12 48 49 so at first our last value is going to be negative or just Infinity right so L equals infinity so we're going to compare these two values that's going to be Infinity this is our curve to start off then we update the last value over here now this is our curve check here now we update again this is our curve this is last and so on so you're just simply updating last to be the current value and then you go to the next value so this will be last again and this will be curve check these two and so on so we can check two values that are next to each other without actually using an array by just having lost value and a result okay so hopefully that's clear let's code it up and what I'm actually going to do is I am going to put in the last value and the result I could do one of two ways I could just make an array of size two because I want to have access to these values in my helper function so I guess what I could technically do is I can just have like uh yeah let's just do like uh results actually let's do it here so these will be like um these will be variables of this class that we can access wherever we want so we just say result equals let's make that Infinity because we're trying to minimize it and then our last value and we're going to make that Infinity as well right because we are going to initialize the initial last value to Infinity because like when we're at this one we want to compare 1 to Infinity but we never want that value to be you know in the output we only care about nodes after the first node okay so let's do that and we're going to have a helper function as well so we're going to define a helper function here it's going to take a node and then we are going to uh we are going to go through our nodes and we're going to actually make sure to never handle a null node so remember we need to go left if we can right so our function for a in order traversal is going to be I can write a status it's going to be left root right for the in order traversal so that's what we need to do so we need to check if um node.left then we need to do that um node.left then we need to do that um node.left then we need to do that so then we call helper uh node.left node.left node.left and once we call this helper node.left and once we call this helper node.left and once we call this helper node.left we're going to have some output we don't really care about the output but we what we do know is after we call this our last value will be whatever like the last value was right so like in this case we're going to be at this one and then so we're going to go all the way down here and then we're not going to have a last value here but when we return up to this 2 our last value would be this one so remember how we did our last value in our picture array we need to so now we know that like our last value will be whatever it was initialized to in here now what we need to do is once we're at the root we need to check what's the difference between the last value and our root node and so that we're going to do that here so we can do self.rez do that here so we can do self.rez do that here so we can do self.rez equals minimize self.res equals minimize self.res equals minimize self.res and then it's going to be absolute value of no dot val minus well it was actually the other way in my picture right so it was actually self Dot last value minus no dot l right in this picture like we update our values and it was L minus C and C is the current node we're at so that's pretty much this now like let's say we are at this two nodes so we just what we just did is we just said okay our result is the minimum of the result minus the difference between the node that we're currently at and the node we were at before but now we also have to do is we have to update our last value now right we have to update our last value and then we have to go right because when we go right where we need to complete we need to compare the value we're at going right to the previous value which is the node we're currently at so we need to update the last value here equals no dot vowel then we need to go right if we can we're going to make sure to avoid null nodes so and so that's pretty much it for the helper function so remember if we can go left we go left then we check is our result smaller than the our last visited node and our current node and then we have to update our last visited node to be the current node because then we're traversing farther down you can't just simply check the node to like the node to its left and its right because you are going to have some cases where uh you can try it yourself but you are going to have some cases where you're not recur you're not like returning straight up it'll so in which case your stuff will fail you actually do have to update the last value in the helper function you can't just say like if you have a left compare the left and the root and then compare the root and the right it's not going to work and so for this now I think we are done there so now we just simply call it on the root and then we return where there's this itself probably screwed a bunch of stuff up but let's take a look okay nice okay perfect so that's it for this problem now let's do the time and space and hopefully that makes sense to you if you want to put up the easier version like I said you can just have an array of the nodes that you visit and so you just go left and so what you would do is you would go left and then right when you do instead of this last value this is where you would put your value into the array so you go left put the value until the array then go right and then you can compare the values but pretty much you got to understand that instead of putting the value into the array we're just updating the last value so we can have one integer instead of a giant array so for time um so we have to go through every node once so that's going to be Big O of n and for space so our worst space act our worst case space we're actually not saving any space because let's say we have something like this and so on like if all other nodes if we have to go down the entire node then this recursive stack is actually going to be o of n so worst case scenario it's going to be oven but average space is going to be for a BST is actually going to be a login and so average space we are saving space because we're not using an array but worst case it's this whole array like this whole tree would be an on one recursive call stack that's why you got it for three problems is we're definitely worst case you know it's not going to change but for the average case which is super likely we do save a ton of space and so yeah like you can try also running only code like let's see what her time and stuff was yeah I mean I do think like this problem has probably been solved enough to where most people have it here but yeah um if you try it the other way with the array I'm sure it'll take more space okay so that's all for this problem hopefully you liked it if you did please like the video and subscribe to the channel and I'll see you in the next one thanks for watching bye
Minimum Absolute Difference in BST
minimum-absolute-difference-in-bst
Given the `root` of a Binary Search Tree (BST), return _the minimum absolute difference between the values of any two different nodes in the tree_. **Example 1:** **Input:** root = \[4,2,6,1,3\] **Output:** 1 **Example 2:** **Input:** root = \[1,0,48,null,null,12,49\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 104]`. * `0 <= Node.val <= 105` **Note:** This question is the same as 783: [https://leetcode.com/problems/minimum-distance-between-bst-nodes/](https://leetcode.com/problems/minimum-distance-between-bst-nodes/)
null
Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree
Easy
532
191
hello everyone welcome today we are looking at another lead code question which is number of bits number of one bits and this is your first question in february week 2021. now uh what the question says is uh we need to write a function that takes an unassigned integer and returns the number of ones into it so what we need to understand is if i am given a value say whatever the binary information that is i need to return how many ones are there into it right uh if you look at it right this is if a very straightforward approach to it is convert that into a string then look at each and every character of it and if you find a one then do a sum of it and then return right so what i mean by that is uh you can say brute force or very simplistic approach which you can come up with is convert it to string then find all ones in this one right this is one way right now there's another approach uh but the problem with this is right this is of n right uh and that's whether you may come back and ask how else can you optimize it so uh before i talk about the second approach let's first solve this approach right so what we are going to do is right we are going to create a string as we just discussed right which will do convert dot to string n comma two now what does this uh this does is it just ensures that whatever the binary digits are given it stays that way and it's not converted to decimal of it now what i'm going to do is right i'm just going to create a counter which is in this one and i'll create the results how many uh reporter so what i'm going to do is y i is less than s dot length right and i say okay if my s i is double equal to zero sorry in this place one then your result plus is anyways my add plus once i'm done my i should return result right so i think this is very straightforward i think you'll be able to understand what we are doing here let's run it and see what is happening i got three then let's submit it would accept it now what now this will be if you see right this will run through the length of the array and in this case right yeah what will happen if what convert or twisting will do is if i have this number this will just convert it to one it will truncate all the you can say prefix zero whichever i'm having right but leaving that aside right it will mostly be the maximum of the length of the array uh length of the input digit n uh because it will keep on iterating that way and if all of them are 1 it will be of n what are the length of the e string will be but how can i optimize it right uh i can optimize it by using bitwise operations now what i'm going to do right is say i'm given n is equal to say this is the input which is given to us right this is the input which is given rules right this is the input which is given to us now this if i look at it right this is a binary form of that is 11 so how that works is uh 2 into what if i look at y versus right so this will be how can i explain that say this is p 1 into 2 k power 0 plus 1 into 2 k power 1 plus 0 into 2 k power 1 sorry 2 plus 1 into 2 k power 3 now what this will be your 1 plus 2 plus 8 this is your 11 right this is your uh binary to decimal conversion this will correspond to a number 11 right so what i'll do is write i'll try to use and operator on this what i'll do is i'll do 11 and 10. now what that will do right let me write the code i think was that it would be easier to walk through the uh whole thing so why say my n is could not equal to 0 that means i'll see until unless this value becomes equal to zero and what i'll do is i'll do my n will reduce to n and n minus one and i'll do result plus right so i'll to understand i'll walk you through what is happening right so what is happening here right let me pin it down let's say this is my original value this is my 1 whatever my n minus 1 will be 10 comma n minus 1 right so what will this do right if i am doing n and n minus 1 this n here corresponds to the decimal value to it so here in first case my n will be 1 0 1 and what my n minus 1 will be 10 what that value will be that will be 0 1 right now if i do an and operation on this 1 and 0 becomes 0 this becomes 1 so my updated value of n will be 10 right updated value of 10 will be 10. now if i do 10 and 9 right that will be again 0 1 and this will be 0 1 one zero sorry this will be one zero so when i'm seeing this uh if i look at band common this is what i'm trying to say is one zero this becomes zero one right now if i look at it this will become 0 and this will become 1 and this will become 0 right now what this value will be 1 0 corresponds to number 8 now i'll go again my n is still greater than 0 i'll do 8 and 8 minus 1 so what that will be so this is 1 0 say and this will be eight minus one is seven so that will be zero one this will be again zero and zero it becomes zero right so in total i did three operations right uh ten to nine to eight and eight to zero right so if i look at this right if i run this see initial value was 11 10 then i did an and operation that became 10 and 7 then it became 8 and 7 and that then became 0 and in all these operations i did plus so this is come up with the same solution it's just that we'd used an and operation with bitwise and operation to resolve the problem so uh i hope you have understood it means walk through it try to understand how that works otherwise uh the other approach anyways we have to kind of convert it to string and then dissolve it now what is the type capacity of this if you look at it right it will never be of 32 in the sense the number of bits that are going to have so this will be o of one of o of one time complexity so with this i'll take you leave um we'll meet uh again and uh in case you have any questions doubts please write reach out in the comment sections uh in case you like the solutions like the both of those approaches we discussed uh please go ahead like and subscribe and please click on the bell icon for any upcoming notifications thank you thanks a lot
Number of 1 Bits
number-of-1-bits
Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)). **Note:** * Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`. **Example 1:** **Input:** n = 00000000000000000000000000001011 **Output:** 3 **Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits. **Example 2:** **Input:** n = 00000000000000000000000010000000 **Output:** 1 **Explanation:** The input binary string **00000000000000000000000010000000** has a total of one '1' bit. **Example 3:** **Input:** n = 11111111111111111111111111111101 **Output:** 31 **Explanation:** The input binary string **11111111111111111111111111111101** has a total of thirty one '1' bits. **Constraints:** * The input must be a **binary string** of length `32`. **Follow up:** If this function is called many times, how would you optimize it?
null
Bit Manipulation
Easy
190,231,338,401,461,693,767
1,851
hello everyone let's take a look at the code on 1851 minimum interval to include each query it's the last question in weekly content and it's also a hard question but there are many solutions to this question so let's take a look at very simple solution and this is a problem description i will skip this section so if you haven't read this problem description please take some time to get familiar with this question okay so the basic idea is we can sort intervals by interval ways in ascending order for example this is original inverse after sorting it will become this then for each interval we just find the qualified inquiries the queries within the range of this interval for example the first interval is four so quarter four is within this rooms next interval is 2 4 then we have 2 3 4 is not included here since we have already consumed it here so 1 is 1 4 nothing 1 is 3 6 we have 5 okay so in order to see up like for each interval scenario idea is like so naive idea is um we just fold up all the queries and to find each query within this range but it's too slow so we can like put on queries in an ordered data structure then you spin research like to find the ones that uh first qualify for example we can use low bond to fund two in the other set okay let's take a look at implementation for the result intervals next we just push our queries into a set we also push the index here since it were used when we built our answer okay this is our answer we'll just write an answer and in this for loop we just follow each interval and for each interval we try to find the qualified queries for setting interval okay it's simple to find the qualified queries for each interval we just use low bound to find the first one then we just found the other elements after these first ones had qualified until that's like we met the ones that not within the range we can just stop or we met the end we just stopped and note that we use erase here since we need to remove this from set once we're consuming it and this erase function will return the next iterator so we don't need to like auto increment it here okay that's it let's take a look at the time complexity this is a sorting algorithm so it would have a log n and here we need to push m elements into sets so it will take a long time and here we will follow and time and the low bound is log m so it's a multiplied logarithm and here you is we will use at most m times so the time complexity is m log n okay that's it see you next time
Minimum Interval to Include Each Query
maximum-number-of-events-that-can-be-attended-ii
You are given a 2D integer array `intervals`, where `intervals[i] = [lefti, righti]` describes the `ith` interval starting at `lefti` and ending at `righti` **(inclusive)**. The **size** of an interval is defined as the number of integers it contains, or more formally `righti - lefti + 1`. You are also given an integer array `queries`. The answer to the `jth` query is the **size of the smallest interval** `i` such that `lefti <= queries[j] <= righti`. If no such interval exists, the answer is `-1`. Return _an array containing the answers to the queries_. **Example 1:** **Input:** intervals = \[\[1,4\],\[2,4\],\[3,6\],\[4,4\]\], queries = \[2,3,4,5\] **Output:** \[3,3,1,4\] **Explanation:** The queries are processed as follows: - Query = 2: The interval \[2,4\] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3. - Query = 3: The interval \[2,4\] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3. - Query = 4: The interval \[4,4\] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1. - Query = 5: The interval \[3,6\] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4. **Example 2:** **Input:** intervals = \[\[2,3\],\[2,5\],\[1,8\],\[20,25\]\], queries = \[2,19,5,22\] **Output:** \[2,-1,4,6\] **Explanation:** The queries are processed as follows: - Query = 2: The interval \[2,3\] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2. - Query = 19: None of the intervals contain 19. The answer is -1. - Query = 5: The interval \[2,5\] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4. - Query = 22: The interval \[20,25\] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6. **Constraints:** * `1 <= intervals.length <= 105` * `1 <= queries.length <= 105` * `intervals[i].length == 2` * `1 <= lefti <= righti <= 107` * `1 <= queries[j] <= 107`
Sort the events by its startTime. For every event, you can either choose it and consider the next event available, or you can ignore it. You can efficiently find the next event that is available using binary search.
Array,Binary Search,Dynamic Programming
Hard
1478,2118,2164
337
hey what's up guys this is Chung here and so this time let's take a look at the nether like tree interesting tree problem here number 337 is called house robber 3 okay so let's read the description here so there's a save here this just the safe has found himself a new place for his theory again and basically he found like a tree structured house right and he can traverse from the root house to all the - all the way to any house to all the - all the way to any house to all the - all the way to any house and each house has a value represent a stand for the money inside the house but he will he can only he cannot take all the house he cannot rob a hot house so like it says here it will automatically contact the police if to directly linked house were broken into on the same night and your you need to get calculate what's the maximum amount of money the thief can rob by traversing all the trees here right so what does that mean it means you cannot basically robbed two adjacent and tree note here or a house here like for example if you robbed three here you cannot walk three and this the trial you can only wrap his grand grandchild here same thing here say robbed here you cannot rob this one work or this one yeah it's very interesting question here so it seems like it's hard to become a same it's hard to become a safe nowadays you need to be a you're to be a to be able to beam to be a good safe you also need to be a good programmer so that you can get a robbed the most out of those houses cool anyway so it's still a tree problem right so going from top down how can you get basically the most node values right and this is like if you think carefully these things it's is it's gonna be clear to be honest to be able to see it this is gonna be a recursion like more like a dynamic programming because every time we reach a new node you will get the you try to get this new node max values from his child work one child nodes here right so how would this work because let's say for example here I'm gonna write it right so when you reach a node here right okay so and when you reach a note here you only have two options here so you either rob this house or you don't right and basically we just need to get the max about the bigger value among those two options here right so let's take a look how we can we calculate those two options here so let's say if you decide to rob these three here you robbed three and then you cannot rob its left or right all right child right you can only rub its grandchild which is the left of one or left of all right of three and the grandchild out five which will be a another note here which does not exist in this case and this one basically if you don't Rob three if you rub three here you can bitten then you can rub oh it's grand trout right and another case if you don't rub three you can only rub its child right yeah basically that's the idea right we're going to use here alright so we're gonna like create a helper functions here like Rob popper right so it's gonna be the note here right and here gonna have a result here and then we're gonna call the robber Rob Alper there's a corner root right and then return the result in the end right so like I like we discussed first okay yeah I mean trail even though it's not right even if note is not right we just return zero because we got nothing to rub right otherwise let's just let's say we decide to rub current node right then that would be what the obedia the current road will the current node will be the node dot value right and then we'll be getting the left side and the right side right so left money right constant zero right let's define these two variables here so and if not current node has a left filing right has an has a left node then what we will do this right money so we basically will Rob all the grunt child run Charles knows on the left side right that's how we define the left money gonna be a Rob so we'll be using the previous result here right and another site right because we want to rob both side we don't want to miss any possible house right after left side grandchild node same thing for the life for the right side if there's a right side sub node here do what we do all right we assign this right money right with this Rob helper right drop upper node dot right side right and then same thing for to sub for two sub nodes off the right side sub no right that's how we robbed all the grand child's note right and then in the end we need to watch we need to return right we need to return a Maximoff so okay so that's the okay let me close to what he goes to uh we first will rob the current right plus right left money right plus the right money right let's rob current right how about a not rub current if we don't if we're not robbing the current so what's going to be the value it's gonna be the helper right left right so if we don't we'll wrap the current we can rob it's the current left and the right no right and then in the end we just return them the max of current and not rob current right yeah so basically that's how we define so the key point of here is rob helper here it's like the it's like dynamic programming select but this instead this one will be like top-down right it's not one will be like top-down right it's not one will be like top-down right it's not a bottom-up so we don't use a rate here a bottom-up so we don't use a rate here a bottom-up so we don't use a rate here instead of what you were using a recursion function but same thing here for this recursion function Rob power here what it returns is for the current note what is the maximum value I'm sorry what was the maximum money I can get for current node and then we just be we just keep recursing over and until we release out all the way to the and then we just use the pre calculated result we come back here and then we just formed for the roots note here right but okay so when since you guys know it is a recursion function here okay one thing if you run this one you know I think this will wrap it's not Rob - Rob okay oh yeah we don't need the result here actually we can just return here yeah we're going to stir we're going to return this one here return this we don't need another result variable here just return so the logic is correct but if you run if you submit this one it you will get like a time exceed exceeds execution limit because remember is all deal with the dynamic programming we want to reuse the previous calculated result but here we're not right we just keep doing the recursions over and over because why because let's say if you're doing the recursion for the node left right it will be it will include this one note that the left will doing all the recursions for everyone right so I use a way to fix this so gonna be a we're gonna have like on money dictionary we're gonna have a dictionary whatever the dictionary would be Rob dictionary right Rob dictionary so this Rob dictionary will save the maximum money we can rob for each note right so in that case so every time before I read before returning this result we just still add the current node we just add the current note the result for a current node to the dictionary right it's gonna be note it's going to be the yeah I'll just copy and paste here yeah so for each note before we turn in it we just record the maximum money take the safe can rob from this for this current node and then at the beginning here right so we can use that rock we can track if the node is Ian Wright is in the Rob dictionary right then we just we simply return it we return the route the maximum value to make some money we can we get from that dictionary right that would say well save us a lot of time here basically yeah pretty straightforward I think I'm gonna stop here I think there are like more I think there's a there's another way of doing it instead of doing the recursions there is going to be a like a different one where you just decouple because here we are we're merging basically we're merging these two values and we're only returning one values for this rob helper function right I think there's another way of doing it is the instead of returning one variable we just return both of these two yeah basically we bubble up these two values all the way we don't merge them so in that case we can use these two values to save some of the route the recursion calls here but it is a similar idea here since we already have this dictionary here I'm gonna stop here to only use the recursions with the memorization for this dictionary and yeah okay so basically for each node we get the maximum value with the maximum values if we rub the current right current that's that and not Rob the current go guys that's I think that's pretty much it is for this problem yeah thank you for watching the video thank you so much guys yeah see ya bye
House Robber III
house-robber-iii
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`. Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**. Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_. **Example 1:** **Input:** root = \[3,2,3,null,3,null,1\] **Output:** 7 **Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. **Example 2:** **Input:** root = \[3,4,5,1,3,null,1\] **Output:** 9 **Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 104`
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Medium
198,213
885
we are given the number of rows and Columns of a matrix and also a random starting cell indices inside the Matrix from this particular cell we need to Traverse through the Matrix in a spiral order till we visit all the cells in The Matrix and at last we need to return an array of cell indices we have visited in the same order an important thing to note here is that we can even go out of The Matrix before we move on to the solution it would be better if we watched this previous videos for a better understanding first let's take an example and observe how the pattern of spiral is working let's say we are given the number of Rows 3 and number of columns 4 so we will have a matrix containing 3 into 4 equal to 12 cells let's say we are given the starting cell indices one two for Simplicity we can rename this R start and C star to inj respectively now from this particular cell we need to Traverse in spiral order if we look at it closely we can observe that there is a repeating pattern in the spiral from the starting cell the spiral visited one cell then it took a right turn then again it will sit at one cell and then again it took a right turn then it will sit at two cells and then took a right turn then again it visited two cells and took a right turn then it visited three cells and took a right turn then again it visited three cells and took a right turn then it visited four cells and took a right turn and then again it visited four cells and took a right turn here we can observe that twice after visiting some number of cells and changing the direction the number of cells visited in the next round is getting incremented by one so all we have to do is simulate this particular behavior from the given starting cell now let's call the solution using the given number of rows and columns we will create a matrix since we need only the indices we are visiting in the final result we can set all the elements to none for Simplicity we can refer to the starting indices R start and C star test I and J respectively we will be storing the result in this array and at last we will be returning it since we are going to start the traversal with the given starting cell we can include that cell in the result array initially we know that the traversal starts towards the right direction so we can set the direction indices initially to 0 and 1 respectively as we observed the pattern starts with visiting one cell and then after doing it twice it increments the number of cells visited in the next round we can store these initial values to these variables foreign Loop we can Loop through the Matrix we will be breaking the loop once we have stored all the visited cells of the Matrix in the result array to move to the next cell we will add the direction indices to the cell indices I and J respectively now since the spiral path can even go out of the Matrix we must make sure to add the indices to the result array only if the indices I and J are inside the Matrix during each iteration we will decrement the number of cell visited once it becomes 0 it's time to take a right turn so we will update the direction indices also we need to check whether for the current sell visit number we have done it twice or not if we have done it twice the choice counter will be zero in that case we will reset the choice counter to 2 and we will increment the number of cell visits to the next round and if we haven't done the current round twice we will reset the number of cell visits which is equal to the number in the next round -1 the next round -1 the next round -1 let's try running the program it's working see you in the next video foreign
Spiral Matrix III
exam-room
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all `rows * cols` spaces of the grid. Return _an array of coordinates representing the positions of the grid in the order you visited them_. **Example 1:** **Input:** rows = 1, cols = 4, rStart = 0, cStart = 0 **Output:** \[\[0,0\],\[0,1\],\[0,2\],\[0,3\]\] **Example 2:** **Input:** rows = 5, cols = 6, rStart = 1, cStart = 4 **Output:** \[\[1,4\],\[1,5\],\[2,5\],\[2,4\],\[2,3\],\[1,3\],\[0,3\],\[0,4\],\[0,5\],\[3,5\],\[3,4\],\[3,3\],\[3,2\],\[2,2\],\[1,2\],\[0,2\],\[4,5\],\[4,4\],\[4,3\],\[4,2\],\[4,1\],\[3,1\],\[2,1\],\[1,1\],\[0,1\],\[4,0\],\[3,0\],\[2,0\],\[1,0\],\[0,0\]\] **Constraints:** * `1 <= rows, cols <= 100` * `0 <= rStart < rows` * `0 <= cStart < cols`
null
Design,Ordered Set
Medium
879
1,822
okay so this problem is 1822 sine of the product of an array so it has all this stuff here but i'm just going to explain this problem as simply as i can so if i get this test case here so say we're given this nums and it's this list here basically if we were to take the product of all the numbers in this array would it be positive negative or zero we return one if it's positive negative one if it's negative and just zero if it would be zero so let's do the easiest case here and the easiest case is if a zero exists in this array it's just going to be zero because anything times zero is zero so if there's even one zero the whole thing will be zero so let's actually just do that case right away and let's go through the nums and if num is equal to zero it turns zero because we don't have to look any further we know it's already zero and then so handling this positive and negative case so if you recall negative one times negative one equals one but negative one times negative one equals negative one so if there are an even number of negatives then this whole thing will be positive if there are or if there are no negatives or an even number of negatives then the whole thing will be positive if there's an odd number of negatives then the whole thing will be negative so basically what does that mean we just want to count the negatives so let's just have something called negs which is going to be you know the count of negative numbers and basically we want to have an else if num is less than zero that means it's negative then we just simply increment that and then at the end here we just need to return what was it again it was if negs is even then this whole thing is going to be positive so basically we can return and then we want to take a condition and we want to check if negs is even and if it's even then we can return 1. if it's odd then we return negative one because the whole thing will be negative and if we run this figure out a semicolon nice if we run this uh we'll see that it works for this case and let's submit this we'll see we got 100 run time so i hope this is straightforward uh this one is probably one of the easier ones but i hope i helped out somewhat and thanks for watching
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
51
this is the 51st liquor Challenge and it is called end Queens the end Queens puzzle is the problem of placing in Queens on an N by n chessboard such that Naruto Queens attack each other given an integer n return all distinct solutions to the end Queens puzzle you may return the answer in any Order each solution contains a distinct board configuration of the end Queens placement where q and Dot both indicate a queen and an empty space respectively so if input n this is one configuration and it goes row so mte Queen empty Queen and so on alright let's get started so I guess first things first if n equals one actually what we should do is this I list string output because that and if I equals n output dot adds a string and this will just be Q then we return output then for the rest of them I'm going to have to iterate through each possible index and backtrack creating when we find these so I guess something that we should do first is create the board so this will be a car right array board equals new car n and then we do for entire equals zero is less than r n i plus we can do board I equals new cart Ray of n and then when we do that we need to go through um yeah that looks right go through the board that'll be board I then J equals Dot so just initializing the whole board so it's just dots turn output there okay got the board set up so now I need to create a function which will be used to recursively run it so we'll call this um private void solve boards so this will take in the car Ray board we then also need to pass in the output we also need the row I'm just gonna be going row by row oh intro so when we call this it will be here go board output then zero so for this four inch I'll read column equals zero coal is less than border length and core plus I'm gonna do board row uh coal equals Q actually now what we need before we do this we need to check to see if it's fine to put it here this is probably best to be another function what should this be called pull it is safe so it's safe for the queen to go so let's be cardboard board then intro int coal so start off with four if I equals zero I is less than rho I plus so we're wanting to check if Q is already on the existing column and the diagonal so I guess straight away if I call equals Q returned false then we need to do the diagonal so let's do int hmm so this left diagram that will be equal to what would this be equal to so we have the column so for left diagonal we need to minus from it and depending on the distance need a look at the row so let's say we're on columns three we need to look at this one so from Ray zero so how would we do that so if you're on Row one we then need one but then let's say we're over here so to have column one two and this will be Rue and this is column three row three as well okay I think I got it so first do row minus I so two minus zero would be two then from the column three minus two which would be one and that's in that position so zero one okay I think I've got it column minus row but we put this in Brackets minus I and then for the right diagonal it would be column plus remember so if left diagonal is greater or equal to zero because if it if the current column is zero then we'll just go to negatives so I want to skip that and board I left diagonal equals Queen return false then we do the same thing here right diagonal is less than board dot length then we do right diagonal like that so if we go through all this we'll get to here and we return true so back to here we do if is safe and what does this take in a board row coal that's when we actually run this so we do that and we do solveboard again this will be board output row uh plus one so we run that we go through each possible combination and then when we go into the next column we can do board row coal Eagles dot so we're just resetting it back to what it was but what we want to do is split up here if row equals four dot length I want to say yeah vehicles border length with a need to add to the output by the way we currently have it set up is it's okay so we need to turn the car array into the list of strings so we would do what we call it's called solved equals new list of string there will be four reach VAR I in board ah we'll do border row solve dot add string dot join be right but this needs to be an empty string and then we return so we start off zero it's less than that so it goes here check to see if it's safe to place but as it's the first row it won't it'll be fine so it already here runs it okay well I think we've got the answer so let's run it and see what the output looks like okay well I must have done something wrong there so there's nothing in this when we get to that point hmm I just realized I've got to add this to Output there we go okay much better so I've got this solution here then this one here is that what leap code has okay cool looks like it so hopefully we can just uh copy and paste all of this interleague code and it'll work just fine so run on the test ones breath accepted and now we'll submit Okay cool so that's the 51st secret challenge called end Queens if you like this video make sure to like And subscribe
N-Queens
n-queens
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other. Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**. Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively. **Example 1:** **Input:** n = 4 **Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\] **Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above **Example 2:** **Input:** n = 1 **Output:** \[\[ "Q "\]\] **Constraints:** * `1 <= n <= 9`
null
Array,Backtracking
Hard
52,1043
452
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is minimum number of arrows to burst balloons so there are some spherical balloons tabbed onto a flat wall that represents the XY plane the balloons are represent as a 2d array called points which is given as input to us where points of I represents a coordinate X start comma X end so this represents the horizontal diameter of every balloon where X start and X end is the diameter start and end points and there is no need to know the exact Y coordinates of this balloon that is the height of this balloon you just have to know its depth because the arrows are shot up directly vertically that is from bottom to top in the positive y direction that is in this way and this is a condition when balloons will burst we'll take a look at that shortly and there is no limit to the number of arrows that can be shot and every arrow keeps traveling up infinitely bursting all the balloons in its path and our task is to return the minimum number of arrows that are needed to burst all the balloons now let's take a look at these examples and see how we can solve this question so let's start with the first example we given the points areay and now you see these are the diameters of the balloons right first balloon is from 10 to 16 second balloon is from 2 to 8 third balloon is from 1 to 6 fourth balloon is from 7 to 12 and we have to find the minimum number of arrows we can shoot so if we go with the original order this will take more number of arrows so it is important for us to sort this array based on its start Dimension so after sorting our array will look like this so this is the array after sorting and now you see and the array is sorted now based on its start Dimension so for example these two balloons will take one Arrow So based on this let us process and for this input array we start with the number of arrows as one because if the input array consisted of only one balloon this balloon will take one Arrow so the minimum number of arrows is going to be one and with the same Arrow we have to check if the next balloons can be shot if they can't be shot we increment that Arrow by one but to start off with we need one Arrow so I consider this as the previous balloon and start our iteration from here so I will start from here and it will go until the end and we keep comparing I with the previous value so let's see so this is I and this is the current balloon so previous is 1A 6 and current is 2A 8 we check if with this Arrow we can burst this balloon yes how are you checking the common part so here as you can see if you shoot an array between this range 2 and six a single AR can burst both the bonss so this Arrow won't be incremented but the previous value will be updated so in the next iteration I will move forward right and this will be a current balloon so this current balloon we can't compare it with the previous value we have to compare it with this common value because with this Arrow it will shoot all the balloons within the range 2 and six so we have to check if this 7 comma 12 lies between the range 2 and six so that with the same Arrow we can shoot this balloon too so this previous value should be updated so previous was initially 1A 6 right and what is the updated value it should be changed to 2A 6 so how are you checking that you're taking the max of these two values which is 2 and you're taking the Min of these two values which is six so that is the updated previous value so previous is now 2A 6 and you check this current value with this previous so take the current balloon is 7A 12 which is not in this range so this Arrow can't shoot this balloon so we need a new Arrow so arrow is now two and this will be our previous value so that in the next iteration when current is here we have to check with this previous value so previous will be changed to the current balloon value so current is 7A 12 so previous is now updated to 7A 12 and we have to compare it with current so now the current is 10A 16 so this new Arrow can be shot anywhere between this range 10 and 12 so with this we can shoot these two balloons but we have to update our uh previous value to Max of this which is 10 and Min of this which is 12 so that uh within this range this current Arrow can shoot the next balloon but we already reach the end in the next iteration we go out of bounds there is no balloon to be processed so until now you took two arrows so this is the second arrow and this is the first Arrow so the total answer is two so two will be returned as the output so the time complexity of this approach is going to be big we go of n login because you're sorting the input array based on start diameter and N to process all the balloons in the sorted are and the space complexity is going to be o of one because we're not using any extra space to solve this question now let's take a look at the code coming to the function given to us this is the function name and this is the input array points given to us and we have to return an integer representing the minimum number of arrows that are needed to burst all the balloons now like we discussed we have to sort this input array points in ascending order based on the starting index so first this balloon will appear because its starting index is one next this will appear and then this will appear so I'll use the ar. sort method to sort the input array points given to us and we have to compare the starting index of a 2d AR right so I use two objects A and B and then use the integer. compare method and we have to compare the starting index of these two objects and this A and B are array objects and we are starting the zeroth index position of array a and zero index position of array B this will sort this entire array points in ascending order now let's declare our output variable which is an integer I'm going to name it arrows which will represent the number of arrows we need and initially we started with one because we need at least one to burst one balloon in the minimum so it means we need at least one Arrow if there is at least one balloon present inside the inur AR and now we start from index position one because we compare with its previous uh balloon so we start with this balloon after sorting so after sorting we start with the second balloon so we start with index position I where I will iterate until the end of the points are and now we need to get the start and end points of the previous balloon right so I create a variable previous start and our current balloon is starting with index position I equal to 1 so we check its previous balloon which is at index position 0 and for that balloon the start index is at 0a 0 and we have to get the end index of the previous balloon that is previous end and this is initially points of zero that is a previous balloons index and the end index is at index position one so for example if this is the current balloon the previous balloon is this one right so we are getting the previous balloon here and this will be the previous start and previous end is going to be this which is at index position one and start is at index position zero and now let's do the same for the current balloon so I copy these two variables and paste it here and I rename this to current start and I'll rename this to current end and we are going to access the balloon at the I index position so this will be I of0 and this will be I of 1 now we have the current start end and have the previous start and end now we need a new arror to be burst if the current start is greater than its previous end so if current start is greater than its previous end then we need a new Arrow to burst this new balloon so first increment this arrow and now we have to change the previous start and previous end right and these are going to be the current start and current end because we now need a new arrow and for the next iteration we need to change the previous start so previous start is equal to current start and previous end is equal to current end and now in the else block it means we can burst the current balloon with the with this Arrow itself so we need to find the new previous start and previous head so previous start is going to be updated and previous end is also going to be updated so previous start is going to be the maximum of so mt. max previous start or current start and previous end is going to be the minimum of M do Min of previous end and current end and this for Loop will iterate till the end of the points array and we accessed all the balloons and we have our answer present inside this variable arrows which is updated here so return arrows now let's try to run the code the test case are being accepted let's submit the code and the solution is accepted
Minimum Number of Arrows to Burst Balloons
minimum-number-of-arrows-to-burst-balloons
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches between `xstart` and `xend`. You do not know the exact y-coordinates of the balloons. Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with `xstart` and `xend` is **burst** by an arrow shot at `x` if `xstart <= x <= xend`. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_. **Example 1:** **Input:** points = \[\[10,16\],\[2,8\],\[1,6\],\[7,12\]\] **Output:** 2 **Explanation:** The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons \[2,8\] and \[1,6\]. - Shoot an arrow at x = 11, bursting the balloons \[10,16\] and \[7,12\]. **Example 2:** **Input:** points = \[\[1,2\],\[3,4\],\[5,6\],\[7,8\]\] **Output:** 4 **Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows. **Example 3:** **Input:** points = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\]\] **Output:** 2 **Explanation:** The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons \[1,2\] and \[2,3\]. - Shoot an arrow at x = 4, bursting the balloons \[3,4\] and \[4,5\]. **Constraints:** * `1 <= points.length <= 105` * `points[i].length == 2` * `-231 <= xstart < xend <= 231 - 1`
null
Array,Greedy,Sorting
Medium
253,435
278
given a series of product versions and also an API is bad version which returns true or false you are asked to find the very first bad version and also keep in mind you should minimize the number of API calls to this operation how can you do that best today's video let's get into it hi everyone my name is Steve today we are going through a local problem 278 first bad version let's go through in the problem description first you're a product manager and currently leading a team to develop a new product unfortunately latest version of your product fails the quality check since each version is developed on top of the previous version all of the versions after bad version are also considered back suppose you have n versions basically from 1 to n and you only find the first the very first bad one which causes all of the following ones to be bad you are given that API bull is bad version which takes the version parameter which is basically just an integer which stands for the version number will return whether this version is bad or not implement a function to find the very first veneration you should minimize the number of calls to this API for example we're given n is equal to 5 and version 4 is the very first bad one how can we reach that conclusion that is because we obtain these 3 API calls we can figure that out so first we call is bad version 3 we check if version 3 is bad or not and this API gives us false which means in version 3 is not a bad version and then we check version 5 which is the last one which is n right and then which gives us 5 is the bad version and then between 3 and 5 we're missing a 4 so because it's asking us to find the very first bad version of so we want to check when the fault is bad or not because if form n is the case 4 is before 5 so we should return 4 in this case because it says since each version is developed based on the previous version which means if 4 is bad 5 6 7 everything at 4 is also bad so what we wanted to find is the very first one in this case and naturally and that should come into our mind is that by no research what we can do is that we can always check the middle point say from one to five we check three if we check the middle point if this one is bad we can directly drop the second half which means because we know all of the second half all of them are bad so the first version will not come out of the second half and then we narrow with just a cut the entire array by half now in the second iteration we only need to check the very first half right now we can keep doing this until we find the very first back version right before the first bad version that means that version is good by applying binary search to this problem we're meeting the problem requirement here which is you should minimize the number of calls to this API the time complexity for this algorithm is going to be old log and because this is binary search now let's put the idea into the actual code let's see the binary search is always it started and we always have a left and the right pointer you can call it whatever you want me on max left all right my habit is to call it left and right so in this case since it begins from one non zero one to n naught 0 to n minus 1 so I have left it goes to 1 and right equals to u equals to n while we'll have a while loop while left is smaller than right well we'll always find the middle one and then use the middle 1 2 comma is bad version you can to check if the middle one is a bad version ok this is the boilerplate code what just use left + right - - left / - what just use left + right - - left / - what just use left + right - - left / - a common pitfall is that if another way to calculate mid is just a left a plus or right and then / - right or right and then / - right or right and then / - right this one is going to cause time limited exception because this one potentially it could left to press the right this one could go over the max value of integer in Java or in other languages which is going to end up an infinite loop that's why we always prefer to use this one mathematically if this one is exactly equivalent in this one but this one could avoid integer overflow because we do the subtraction first and then we do plus all right with that set okay or what do and then is if we'll call this API if this one is bad that means everything after this is also bad so the very first bad version as we just described will not come out of the later half so what do in this case is that well put what assignment to beat the right boundary then we only need to check and laughter to write the new right boundary here right otherwise what's else means that in this myth is already a bad version so what we can do is that we will use mid plus one house means that this minimax is not the bad version which means it's still a good version so everything before that before this midpoint from nafta to mid is all good all of them are good so we can discount this half then we'll assign mid class want to be the new left because MIT is still good we don't need to care about that and then we'll mid plus one to be the new left will care about the new left to the right this portion this half which we should continue to look through to do binary search and then in the end we can just written in the left all right this is the entire algorithm now let's hit submit and see either you can either submit you can either return left accept it so when we turned left here or you can also return right in the case that's fine because they're brave the break case is left smaller than right as long as the left a small amount right we will just keep looping so left and right in the end when we break out is going to be equal so this is the entire algorithm time compactor again it's going to be old locking because this is binary search and we have minimized number of API cost this is the solution for this problem I hope this video helps you make sense of this problem and solution if you do just do me a favor and hit that and that's gonna help a lot with a YouTube app in them and don't forget to subscribe to my channel and tap the little bound application so that each time why not publish a new video you're not gonna miss out on anything right now while going through sorting and searching after this well go through a dynamic programming and then different combinations of data structures and algorithms do how people better prepare for their upcoming coding interviews or if you have any comments questions suggestions just comment down in the comment section below that's it for today's video I'll see you guys in the next one
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
438
going on everyone today we are looking at lead code number 438 find all anagrams in a string this is another question another string question that is frequently asked at a lot of companies so i highly recommend being familiar with it will show up out in the wild and um definitely want to know definitely want to be familiar with this pattern uh you can see facebook has asked it a lot in the last six months amazon bloomberg snapchat microsoft all the big companies like to ask this one okay so let's run through it's not too bad we're going to go through two approaches to solve this problem one we'll look at a brute force approach and then we will look at a more efficient approach and we'll go from there okay so find all anagrams in a string so it this problem is not too difficult to understand we have a string here and we want to find all the anagrams of this p string here so we're going to get two inputs a f string and a p string and this p string abc we want to iterate over this s string and find all the anagrams inside of this string that match to the p string so here we have cba that's an anagram and then we have bac that's an anagram and then we want to return we want to create a result array and return the starting index of the anagrams inside of that s string so here 0 is the starting index of cba and 6 is a starting index of bac push that into a result array and then return that okay so that's the question now some of the things that to think about when you look at this is that it's not a hard question to understand and it's not a hard question to implement a brute force solution that would most likely be the first guess on how to solve this and that's okay you know i mean you want to try to at least solve it first and then worry about how to move forward from there so now some clues in the prompt that might be important to recognize on why a brute force solution might not work for this is you can see here that the s p strings will not be larger than twenty thousand one hundred so you can't really get very uh inefficient time complexity it's gonna have to be efficient if the inputs are gonna be you know in the ten thousand twenty thousand uh range okay and so that's another thing to keep in mind uh when look when thinking about an approach to solving this but let's take a look at a brute force approach so here we have cba eba okay so we have our input string which is going to be um cba okay um eba bac e b a c uh and then d and then our p string is going to be abc okay so what is a brute force way we could approach this problem we need to figure out all the anagrams inside of s that equal p well a brute force would be to get all the substrings right we could get all the substrings in this s string and then we could iterate over each one of those substrings and check if it is an anagram of p right and then we would have to somehow get the indices of where those substrings are and then return push those into a result so for example what we could do is let's say we grab these three strings here and then we convert it into a hash we check are they anagrams r is that substring of cba um an anagram of p if it is then we go ahead and push in the ith index of where it's at okay then we come over here we do the same thing and so on and so forth right and so what would our time complexity be if we're trying to do that well we would have to iterate over everything once and then for each iteration we would have to go ahead and do an inner iteration where we have to convert it we could either sort it sort both sort p and sort uh the substring of s that's going to be an n log n operation or we could do it linear by hashing them we get hash p hash s and then check equality there again that would be an n operation so both of those we could either get if we use the sorting method we could do n times n log n or we could do n squared if we use the hashing method right for time okay and what if we wanted what about space how much space are we going to need well we're going to need new space for every single substring that we're creating right so we would probably have n squared on space as well okay so it works but it's not good and when we have an input of 20 100 it's not going to be inefficient enough to handle an input size of that capacity so you know we want to think of something better okay let's go ahead and clear this out and see if we can come up with a better solution to this okay we have cba eba let me do white here cba eba okay and then we have bacd let's go back here b a c d and then we have a b c okay this is going to equal our p string this is going to equal our s string okay so how could we approach this in linear time in linear space what could we do what approaches could we think about well we could do a sliding window approach right we could also we also know that in the input here it says that our strings are going to consist of lowercase english letters only okay lowercase english letters only that's really important because what we could do is we could create two arrays that map to every character in the lowercase english alphabet right so let's say we had a p array okay and we had index 0 1 2 3 4 and so forth all the way to 25 that's going to represent the 26 characters in the alphabet and here we have the string abc right so what is the frequency of abc in the p array well there's one a we can map a to zero that's going to be one b to one so we'll have one b there and c to two and we'll have one c there what we could do then is also create an s array okay and just doing the same thing 0 1 2 3 4 map all the way to 25 okay we're going to have an ith index that we're going to be iterating over our s string so what we can do is we can iterate i over here okay and then we're going to since we have c we can map 1 to that c index we move i over now we have b we have 1 here in b we update the s array we move i over here and now we have one a and what we check is if i is greater than or equal to p dot length right p dot ln minus one so if p dot len is three okay and here we're at one zero one two three minus one is two and if i is greater than or equal to two then we check are these two arrays equal do they have equal values right and they do you can see that p array has one at zeroth index one at one index one at two index and this s array has the same values right and so then we can just go ahead and push i minus p dot length minus 1 so i minus 2 so i is going to be 2 minus 2 which is going to be 0 and we can go ahead and push that 0 into a results array right and now we move over one we move i over here now we check before we do this we actually want to check before that we're going to check if i is greater than p dot len minus 1 right and if i is greater than that means it's outside of the window range that means we are outside of the length so what do we want to do normally sliding window when we get outside of the window range we want to delete from the beginning right and so what we can do is whatever i is at and the p dot length is we can subtract those two and figure out what was at the beginning and it's going to be zero and we decrement this c here we get the charcoal for c and we decrement it in the array there in the b from the beginning right and then we go ahead and check again what is i at and is it greater than or equal to p dot len it is and is bae we're going to also have e here so a b c d e is going to be 1. we can then check are these arrays equal and they're not and so we just move forward we just move i okay and again when we get to that iteration i will be outside of the range okay i is greater than p dot len minus 1. and so again we're going to decrement this b here we're going to subtract i from p dot len and we're going to decrement b back to zero right and so forth and so on and we get when we get to index six okay we're going to find that um well actually when we get to index 6 7 8 and we run this if statement right here we're going to also find that 6 is also valid because at that point p array and s array will equal each other okay so that's our conceptual strategy on solving this problem let's go ahead and code this up okay so what do we want to create two arrays one for s and one for p and those arrays are going to be frequency counts for lowercase alphabetical characters okay so we can do const s array which is going to be new array for 26 characters the length and we're going to just fill it with zero okay and we're going to do the same thing for the p array what else are we going to need well we're going to need a result over here right we want to return a result so we want to also go ahead and have a result and just set it to an empty array okay now what do we want to iterate over our p string and calculate the frequencies mapped to each character to the index of our p array now something to note here how do we get the index a to match 0 and so forth well we can use something we can get you can use a helper method in javascript called char code at and that will give us the char code of that particular character and what we can do is just mod that by 26 because there's 26 characters in the alphabet so whatever the char code is it'll throw us a number between 0 and 26 and we can mod it we can uh we can then map that to the p array so we can do four let i equals zero i is less than p dot length i plus okay and then we want to get the index and the way we're going to do that is we're going to do our pstring dot char code at it's a built-in javascript method it's a built-in javascript method it's a built-in javascript method of i and then we're going to just mod that by 26. okay so charcoal of a i believe is 97 mod 26 should give us zero okay and so now what we're going to do in our p array the index here we're just going to increment it whatever is at the index okay so the p array at index 0 we're going to increment at 1 for a we're going to increment at 1 for b and we're going to increment at 1 for c as we iterate over these three characters okay so now let's go over our sra iteration okay and now what do we want to do we'll do the same thing we want to get our index and we're going to do s dot charcoal at and here we're going to do it for i mod 26 okay and then our s array at index we're going to increment that okay so now what do we want to check if we are outside of the range first okay so is i outside of the range are we outside of the window range our target window range so we can do if i is greater than p dot length minus 1. what do we want to decrement the head right so we want to get the head index and that's going to be s at char code at i minus p dot length mod 26. and what are we doing here we're getting the ith index the charcoal of that and we're subtracting p dot length from it okay and then we're modding it by 26. so that should give us what is at the head what is at the beginning of uh of our s array and then what we're going to do is our p our s array at head index we're going to just go ahead and decrement that okay so that should keep our window where it needs to be and now we just need to check if i is greater than or equal to p dot length minus 1 what do we want to check if and we'll have to do a helper function here array values equal and we're going to do our s array and our p array and if they are equal what do we want to push into our results so we can do result push and we want to push the beginning so we want to do i minus p dot length minus 1. okay and then we just want to return our result and let's just go ahead and code out this helper function this is a very um uh bare-bones helper function if you uh bare-bones helper function if you uh bare-bones helper function if you really want to check array equality on values uh you would have to also do edge cases for length but i think for the context of this problem that's not necessary because we're only checking uh two arrays that we know are of equal length so you can do const r arrays r array values equal and we'll have array one and array two okay and all we're doing here is just gonna we can just iterate over this array one and then we just want to say if array one at index i does not equal array 2 at index i return false else we just return true okay and that should do it let's go ahead and run this let's see here where are we not pushing slight bug here and if you can see here on line eight we have a bug here where we have a one and what we want here is we want to make sure we have an i okay now if we run this code it should work and then we can run that and yes we have success and so that is leap code 438 let's just quickly go over time and space complexity for this so what is our time complexity uh and space complexity well we saw with the brute force our time complexity was n times n log n because we were going to sort everything in there and then we could get it down to n squared if we used a hash with this our time complexity is actually n it's o of n we can do this in linear time because we're just going over each array once and then on each iteration we're just doing some constant time operations which is decrementing from the front adding to it all of that is just our constant time operation so we can say that our time complexity with this is going to be o of n time and then what is our space is also going to be o of n okay because we're going to return a result array that worst case every element you know could be a p like if p is just the same thing as s uh we could have a worst case of n and so time and space is o of n which is pretty good um so that is lead code 438 find all anagrams in a string i hope you enjoyed it highly recommend getting familiar with this uh with this question and also familiar with the pattern that this is using a sliding window pattern and so again this is a question this is a pattern that helps you solve a lot of problems that are frequently asked and so it's a good practice problem to be familiar with that pattern okay that's all i got for this one i will see you on the next one
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
1,519
hey everybody this is Larry this is day 12 of the legal daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's Forum 1519 number of notes in the sub tree with the same label hit the like button hit the Subscribe button join me on Discord and let's take a look at this poem seems like we're getting a couple of three problems today uh the ratio is a little sad so we'll see what the problem is so you're giving it a tree we know what a tree is maybe um with n minus one edges okay the root of the tree is node zero and you know that the tree has a label which is a lower case given the string labels uh what does that mean okay so just the index correspondent you could have just okay fine I mean again this is not a binary tree it seems like just to kind of even though this one they drew it as a binary tree but you can see that this is not a binary train the other one uh okay yes this is an edge let's discriminate we turn away of size n where answer sub I is the number of nodes in the subtrip I which has the same label as node I okay so that means that 0 would contain all the A's um twos would contain all the B's and so forth hmm I think this one has so you could do it in two ways I think it depends on whether you care about time more or space more um yeah uh and what I mean by that is that one way you can do it is of course just do 26 depth first search right one for each character and then so that would be the time uh the one that you pay for in time because that would be linear space um the other one I mean I guess the other one is linear space as well but the other one you can do is just return say an array of 26 elements and then you keep on merging right that will also be linear space but it'll be 26 times n so yeah so in both cases it'll probably take um and even then in that case technically the time is also I mean I guess yeah the time is also 26 times n or whatever because that's the Technically when you return and then you do copy and stuff like that it'll be all up 26 anyway right so yeah so both Solutions are probably okay I'm curious I'm giving it 10 as you go to or n is equal to 10 to the fifth it may be a little bit slow because the code doesn't uh the code does not have love for python so that's where I feel a little sketch but should be okay like even uh if not maybe that's where the download is coming from I don't know I don't get where the downward's coming from though I mean it's not seems pretty straight forward per se um if a little bit annoying but all right let's think about it uh let's start implementing it as we said um I'm going to do I mean you'll see what I do uh but I am going to create an adjacency list first what default take this list and this is just very standard uh adjacency list doing so that basically for index you we get a list of uh things that it is connected to right okay so then now um kind of a little bit thirsty I wish I'd kind of got a little bit of water beforehand but let's see like a powerful uh okay so then now we just do a recursional is it always zeros to no the wood of the tree is the node zero okay so yeah so then you do maybe something like you know let's go Traverse I think I'm going to just right um zero right yeah and that's pretty much it and then maybe you could return it then so after that's pretty much it uh the easy part is done the hard part is done and now you just have to fill in the code right now um but yeah but then now so basically we get the current we don't even have to get the label quite yet we could just um for free and node and of course this is a tree so we don't want we're going to go for parent as same thing we did yesterday um definitely check that out I think the same idea anyway uh if we is not equal to parent well let's go a child I use real a lot because of the UV notation um that comes up in graph Theory a lot uh for edges that's just a short hand um but yeah so basically we have uh Julius Child and a node is the parent what do we return a list of um 26 things so maybe I'll call it f for frequency and then maybe like a current f for current frequency which is 0 times 26 oops and then here then just for line range of 26 F of I of current f i Implement by that maybe there's another thing where and then we return current F and of course we do uh is zip code 2 current F of um what was it label sub node uh minus out of a very slower case yep um and that should be mostly good except for we didn't do the base case of incrementing so yeah so here we would have I guess this thing uh Does it include itself I guess so because the answer contains one okay um oh whoops I like to write it that way hmm oh hmm what I assignment oh or did I did anything oh whoops why do I do it like this I mean probably quite none so that if we don't Traverse for some reason but what's the labels oh actually they keep you in as you know I like big end so um okay yeah that looks good uh let's just give it some of it the only thing I worry about is maybe tle but it seems like it's okay tell you big time limit exceed it but obviously it seems okay 10 17 day streak I'm really tired today I did my gym day a little bit or my gym portion overlay um so I'm not gonna do an extra one but like I said before and this is what most people should do to be honest which is um and I think about and maybe I explain it in a different order but um what you should normally do is obviously know the complexity and before you implement it sometimes you can explore things if you punch you and that's fine part of learning exploration and playing around different things and trying to see how things gel together and also like um figuring out what doesn't work is also important but um you know what if you're in the business of actually solving things and not just learning then um you know preemptively figuring out is a little bit good and here it's like I said it's going to be o of alpha times n space and of alpha times and time right you can is explicit here in the for Loop here um yeah and you may you know you may um I think the one thing that I always say for this one is that you know you have a function there's you know you can call once for each node but you but there's a follow-up there right there's a follow-up there right there's a follow-up there right there's a Fallout there uh isn't this n square or something like that instead of just open well no because the answer is going to be that um I mean the short answer is amortization but you can think about it as what you know um because you can call each node at most once because this is a tree that means that this function chord will happen only once as a parent and that means that this will only happen once per thing right uh per node and so yeah so this is going to be all of alpha times n because we do a full opinion for time and space yeah um because we allocate stuff on we allocate 26 things on a stack and it could be 20 you know Alpha things in a stack um yeah another way you can think about all these actually this is that you know well what I do you know uh E1 is the number of edges that are Z zero I suppose um uh is the number of edges going out of E1 or node one plus C1 plus C2 the number of edges going out of node two uh node three no four dot right and this is going to be o of n or would you want to say uh the total number of edges is e which is n minus one which is all of n right so in that way you know that this for Loop if you want to sum up all the edges together will only be all of n so that's basically why this is um given though you know if you're um still learning amortization this is one way to kind of think about it and how you would get from you know like the two four or there's a functional folder why is this you know not n square right so yeah uh hopefully you'll play around with that a little bit more I'm so tired friends uh that's all I have for today uh let me know what you think stay good stay healthy take your mental health uh have a good rest of the week I'll see you later and yeah goodbye and take care bye
Number of Nodes in the Sub-Tree With the Same Label
minimum-subsequence-in-non-increasing-order
You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` `edges`. The **root** of the tree is the node `0`, and each node of the tree has **a label** which is a lower-case character given in the string `labels` (i.e. The node with the number `i` has the label `labels[i]`). The `edges` array is given on the form `edges[i] = [ai, bi]`, which means there is an edge between nodes `ai` and `bi` in the tree. Return _an array of size `n`_ where `ans[i]` is the number of nodes in the subtree of the `ith` node which have the same label as node `i`. A subtree of a tree `T` is the tree consisting of a node in `T` and all of its descendant nodes. **Example 1:** **Input:** n = 7, edges = \[\[0,1\],\[0,2\],\[1,4\],\[1,5\],\[2,3\],\[2,6\]\], labels = "abaedcd " **Output:** \[2,1,1,1,1,1,1\] **Explanation:** Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree. Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself). **Example 2:** **Input:** n = 4, edges = \[\[0,1\],\[1,2\],\[0,3\]\], labels = "bbbb " **Output:** \[4,2,1,1\] **Explanation:** The sub-tree of node 2 contains only node 2, so the answer is 1. The sub-tree of node 3 contains only node 3, so the answer is 1. The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2. The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4. **Example 3:** **Input:** n = 5, edges = \[\[0,1\],\[0,2\],\[1,3\],\[0,4\]\], labels = "aabab " **Output:** \[3,2,1,1,1\] **Constraints:** * `1 <= n <= 105` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * `labels.length == n` * `labels` is consisting of only of lowercase English letters.
Sort elements and take each element from the largest until accomplish the conditions.
Array,Greedy,Sorting
Easy
2316
933
Hello Hi Everyone Welcome To My Channel Today We Are One Of October Channel And Problems Number Of Recent Call 100 You Have A Reception Counter Class Which Country Number Of This And Requested In A Certain Time Frame Implement Vriksha Encounter Class Which Has One Constructor Festival Hours Or Se Request and Third in Pinty Addison Uric Acid Time TV Presenter Sometime in Recent Times The Number of Requests Happened in Defiance z10 Request Liter Number of Questions Left Her Bewildered in Devotion - छु गुरानेटी Data Use Turns Out Will Solve This Problem - छु गुरानेटी Data Use Turns Out Will Solve This Problem - छु गुरानेटी Data Use Turns Out Will Solve This Problem A Vector Problem It's All Right Light We Have Two Designer Blouse And This Encounter Which Will Maintain Counter Which Holds Data From The Time Team The Current Time TV Were With Vipin Method 250 - 300 Method 250 - 300 Method 250 - 300 A &amp; B Happy Return Number Of Seats And A &amp; B Happy Return Number Of Seats And A &amp; B Happy Return Number Of Seats And Calls In This Time Frame Show Which Is The Best Latest Structure Tuesday Skin Problem To Maintain Range Some Window Of Time All Schools In The Mid-1960s Very All Schools In The Mid-1960s Very All Schools In The Mid-1960s Very Straightforward Problem Fennel First Will Take Place On Tuesday 09 Constructor I Was Using All In Place Implementation Of Winter Fees And Hair First Hindi You Will Get Current Call Time They Are Getting Call An Also Been To Check 100 Nursing College Time Way Randy Orton Impatient And Do That Hand With Water Quality More Than 300 Yes 80 To 100 No More Than 300 No Interview After - More Than 300 30 To This Movement After - More Than 300 30 To This Movement After - More Than 300 30 To This Movement Will Stop This Is Not in the movie and subscribe our who's who zoom subscribe to that doctor element on the front part plus will check key element of the key discrepancy - 30 check key element of the key discrepancy - 30 check key element of the key discrepancy - 30 will remove that element content will remove all elements and number of schools in the see that show It's working and submit decode key settings accept what is the time complexity pure time complexity of this solution is life but and holding maximum cases and why sudesh mil we are the number like wolves is solid will be minimum of the time complexity of solution is this of Minimum of 10.30 Reply Skin 600 of Minimum of 10.30 Reply Skin 600 of Minimum of 10.30 Reply Skin 600 Increase in comment section and subscribe the Channel Solution Using The Way Did Not Be No Data Structure But He Is Very Good Channel Like Entry 830 Set Super Series And A Documentation Over Of Rescue And Her Recent Visit In View of the nutrition to be set Limits of Greater Noida Poultry Form Elements and Returns Back Wali Most of How Works Let's Understand in More Detail Over 100 Ko Ki Fasal You Know What Is presets Utri Set Basicly Maintain That Them Shoulder Midding Midning Internal Function of the Day A Key Tech CEO Of Law And Time To Add Any Key Into Your Website Similarly From One Side 30 Ki 24 Filmy Set Something Like It Na Is I Mean To Say Zor Return The Number Of Girls From 302 - 302 - 30 From 302 - 302 - 30 From 302 - 302 - 30 Hai Tu Play 302 Sudesh Virendra Kushwaha 2302 Soen Swiss Roll Receive The Tales Them Will Return From Share Subscribe Agree With All Will Be Aided For B.Sc Foreign Minister Nutri Set That Now First Will Be Treated Water And Current Element In the written test 110 set dad detail set from BBT - 110 set dad detail set from BBT - 110 set dad detail set from BBT - more than 300 developed so let's compiled this code that Nitish is compiling and where getting correct answer so let's now this code yo honey discharging nadu and not accepted so what is the time complexity Of dissolution short dresses will take to you login time no time i a little bit of rotting hormone login time and soil time complexity of login to hang space complexity is the number of element total number of elements time from being added in ahmedabad The Work Set From Starting Of This Recent Class 10 Will Meet Saunf Hai 200 Feet Like My Solution For Kids Like Button Unfriend YouTube Channel subscribe and press the Bell Icon to get Notification One Act Videos Thanks for Watching
Number of Recent Calls
increasing-order-search-tree
You have a `RecentCounter` class which counts the number of recent requests within a certain time frame. Implement the `RecentCounter` class: * `RecentCounter()` Initializes the counter with zero recent requests. * `int ping(int t)` Adds a new request at time `t`, where `t` represents some time in milliseconds, and returns the number of requests that has happened in the past `3000` milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range `[t - 3000, t]`. It is **guaranteed** that every call to `ping` uses a strictly larger value of `t` than the previous call. **Example 1:** **Input** \[ "RecentCounter ", "ping ", "ping ", "ping ", "ping "\] \[\[\], \[1\], \[100\], \[3001\], \[3002\]\] **Output** \[null, 1, 2, 3, 3\] **Explanation** RecentCounter recentCounter = new RecentCounter(); recentCounter.ping(1); // requests = \[1\], range is \[-2999,1\], return 1 recentCounter.ping(100); // requests = \[1, 100\], range is \[-2900,100\], return 2 recentCounter.ping(3001); // requests = \[1, 100, 3001\], range is \[1,3001\], return 3 recentCounter.ping(3002); // requests = \[1, 100, 3001, 3002\], range is \[2,3002\], return 3 **Constraints:** * `1 <= t <= 109` * Each test case will call `ping` with **strictly increasing** values of `t`. * At most `104` calls will be made to `ping`.
null
Stack,Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
null
1,793
Today's question is we have maximum score of good sub array problem statement what is given to us in the problem statement we are given an array of numbers and an integer we are given a score we are defined what is the score in the problem statement Meaning of Array: If we Meaning of Array: If we Meaning of Array: If we extract any sub array from this given array whose start is from i and end index is p then what will be the score of that sub array it will be equal to the length of the sub array multiplied By the minimum element of the sub array and that sub array will be a good sub array if it is satisfying this condition i.e. satisfying this condition i.e. satisfying this condition i.e. its start should be at or before k and its end should be at or after k and we will get such a good sub array. To return the maximum possible score of the sub array, if we can choose any good sub array from the array, then which one will have the maximum possible score among all those good sub arrays and what will be that score, we have to return it after seeing the example. First let us see what is a sub array. Sub array is basically a continuous part of any given array. So if we have any given array, what will be the sub array in it? We can take any continuous part of the array from two to four. Take from three to five, take from one to five, take any part, but the elements present in it should be found in continuous order and this cannot happen simultaneously, some of the elements may be missing in the middle, if we start from So we will take all the elements till the end in our sub array. For example 1 5 Now in 135 we know that two are missing and four is missing then we will say that this sub array is not ours. 2 3 4 5 All our elements are coming in it. From two to five means we are taking a continuous part of the array, so yes this is all the array, then we have 152, so we know that the first thing is that the order is not maintained here, 2 is before 5 in our given array. I and this are given later and secondly, the elements in between are also missing so this is also not our sub array. Now let us understand this question through an example. We are given this array Namas and we are given the value of k. Now we have to tell what can be the maximum possible score in this. Now to get the score of a good sub array, first we have to get the good sub array. To get the good sub array, we have to satisfy a condition. Now what is the condition? The condition is given that we are given the index of which, right, the sub array always starts from that or the previous element and always ends at that or the next element. This is the condition, so what do we do? You can see, to satisfy this condition, we have divided our given array into three parts, the first part of the elements to the left of k, the second part of the elements to the right of k and the third part of itself. We know that now any good sub If we take out an array, K will definitely come in it because I know whether it has to start from K or the elements to the left of K and all the array has to be done at the end of K or the elements after K, then in these short K will definitely come in between. K will definitely come in our sub array, so this is the condition of being a good sub array because if we divide it into three parts then it will be easy for us to visualize the question, hence we divided it into three parts. First left part, second right part and third own K meaning index. Now we have to calculate the score. I know to calculate the score I need two things, first is the length of the sub array and second is the minimum element lens. So my problem will come out because. If I select any sub array, I will have its indexes, start index will be aa and end index will be j then length will be easily found j - aa p 1 Now my second j - aa p 1 Now my second j - aa p 1 Now my second task is I have to find the minimum element of that array. Now if I select any Also, if I select an array, then I will have to find out its minimum element and how can I find it. Suppose I have selected all the arrays from the first index to the sixth index. Now what will be its minimum element? What will be its minimum element? Simply minimum of left part compared by kth element minimum of right part so in short we will compare three minimums we will find minimum of left part which is four we will compare it with kth index which is f then we will compare that From the minimum of the right part, what is the minimum of these three elements, that is, neither 4, nor, these three elements, we have to compare, and this will give us the minimum of the complete sub array. So, if four of the 4, F, and Na are minimum, then we have to You will find that the minimum of this sub array is four, so in this way the minimum can be found, but for these three minimums also, I will have to traverse the entire sub array, so if I go on traversing it completely for each sub array. To find the minimum, considering the constraints of my time complex and solution, it will give an error of time limit exceeded. So with the help of quadratic time, can I find the minimum element only with the help of indices in this case that if I Given the index, my left sub array is going till the first index, so can I find the minimum of my left part by looking at the first index and similarly if I know that my right part means which is my right end? That's mine, it's ending till six, so can I find my minimum from four to six just by looking at six, like I can find my length by looking at I and J, can I also find my minimum by just looking at I index and Jth index? In this case, yes, we can find out why because our sub array is the contiguous portion, so what is the meaning of array, what can I do, I will create a new vector of my own, prefix vector or let's say create any vector with the name minimum. And what will I do in that, I will start storing the minimum from here, that means I will start storing the minimum of the left part from here and I will start storing the minimum of the right part from here, then I will keep seeing that if my left array reaches to two. So, what will be the minimum in it? If only eight is till one, then I will compare it with this. If four is smaller than eight, then the minimum till one will be updated and will become four. In this way, I will store the minimum in it so that I can also keep my minimum element. I can access it only and only through indexes. I do not need to reverse the entire sequence. Let's understand from draw run how to extract it. We had this given array, we have created a new array and now we have to store the minimums in it. How to store: Now first of all let's store: Now first of all let's store: Now first of all let's start finding the minimum of the right portion. So as it is, you copy the value. And I have to store the minimum of the right portion. So first of all I looked at the fourth index and I stored only 10 in my array. I did that if my right part is ending only at four, that means my sub array is ending at four, then what will be the minimum of the right part, 10 will come, there is only one element, 10, then I saw five that if my right part is four. If it is from 1 to 5 then what will be the minimum element? Compared with 10, 9 is smaller than 10, so I updated it from 9 to 5. I saw that if my sub array is ending at the 6th index, then in the right part only four to six. If there are elements till then what will be the minimum then the minimum will be nine, I compared 11 with nine, still the minimum is nine, then similarly if I am ending at the seventh index then what will happen then my minimum will be four because Four is even smaller than nine then my update is done. Similarly, I started traversing for the left, starting from two, then at the second index, if I say that my left part is only till two, it means everything is mine, starting from here. If this is happening, then I have only A, how much will be the minimum out of eight, then if I am saying it is up to one, then four and out of eight, how much will be the minimum, four and if I am saying it is up to zero, then how much? Minimum will come one, so in this way I have stored my minimums in a new array. Now whenever I want to find the minimum of any sub array, now if I guess again, I see again that we have so many sub arrays, now I get the complete sub array. There is no need to reverse the array, what will I see, I have all the arrays from one to six, I have to see what is my value at one is fo, then value at one, my value at one is fo, then I have to see what is the value at my six, there is six in this array. My value is the third at the last because if we have not included it in the minimum then also we will have to see separately what is the value of the Earth Index. Now see the minimum of these three which will come out in OFV, then the minimum of these three. is four i.e. the minimum of these three. is four i.e. the minimum of these three. is four i.e. the minimum of the complete sub array will come to us fo so the minimum we have taken out the minimum we can now access only from this array now the second thing we have to solve is that we have to maximize the score first of all the score We solved the problem of finding how to find the score. Now how to maximize the score in less time complexity. To maximize the score, two things need to be maximized. Firstly, the number of elements of the sub array because they are getting multiplied. Secondly, the sub array. Minimum element of Because two things have to be multiplied, firstly we have to multiply the length, secondly we have to multiply the minimum element, so my effort will be to maximize both the things, so I will choose any sabre, while choosing it, I will keep two things in mind, first. So I can maximize its minimum element, secondly I can maximize the length of that sub array, now how can I do that, I know what I will do is that I will check all the possible values ​​of my left pointer I will check all the possible values ​​of my left pointer I will check all the possible values ​​of my left pointer and I have taken out its corresponding lines and calculated the score, then I will take the maximum of all of them, what do I want to say, basically here I know that which is the start of my sub array, it can have only four possible values, in this case it means any. If we have a given array and we have given the value of k in it, I know that I can start my sub array only from the elements to the left of k and end it only from the elements to the left or from k. So if I am fixing my left pointer, if I am telling my left pointer that my array will start from zero, then I can find the end of its correspondence optimal subarray and then I have come here. And now I can easily extract the minimum element from the indices because I have created a prefix array or an array with minimum, the end length will also be extracted from the indices, so what will I do? All the start and end of the sub-array are All the start and end of the sub-array are All the start and end of the sub-array are possible. I will check and see how many scores are coming from the start and end of all those arrays and then I will return the maximum score possible out of all those scores. Now here this thing can come in our mind. That is, if I start looking at all the pairs of a and h, then we are seeing only the possibilities of time complex separately, that is, in the loop, we will see what are the possibilities of quadratic and time complex and in the correspondence of that left, we will see what are the possibilities of right. Maybe we will calculate the correspondence of those right points and get the score from it. Now if I am saying that I want to start my sub array from zero index then its correspondence can be five values ​​or else my sub array can be five values ​​or else my sub array can be five values ​​or else my sub array ends at third. It may end on four or on five or on six or on seven. These can be only five values. So what will be the most optimal value for the zero index? I have to see that thing about the right index now. For this, it is necessary to have maximum elements in the array. Now maximum elements are fine and along with this I also have to see that my minimum element should also be max to max. Now I am seeing all the possibilities from the left part. Then why should I take a value smaller than that value in the right portion if I am selecting one from the left, if this is because it is my prefix array then if I am saying that I am starting the value from such an index where The minimum value of the left array up to is one, so I know that the minimum value of the left part is one. If I choose an element smaller than one from the right, then the minimum will become even less, so my score will be even higher. It will reduce but I want to maximize my score, so in the correspondence of one, find such an index from the right side where all the elements in the right part are equal to one or greater than one, so that my minimum is the highest one. It should not be smaller than this so that my score does not go down further, then the corresponding index of one will be in the right part where the minimum of all the elements is greater than one or equal to one so that my minimum is now not less than one. If possible, we have to compare and third, because it is not in our control, otherwise we will have to include it. If there is no wish then what will I do, first of all I will make a left pointer equal to zero and I will run till K are possible i.e. we can start possible from zero till K and possible i.e. we can start possible from zero till K and will search its cusp right index and then I will take the minimum of all three then I can easily calculate from the prefix array left comma right comma kth value. Out of these, the minimum has come to the minimum and from this I will calculate the score. Similarly, now we have seen the possibilities on the left. Now we will have to see the possibilities on the right too. Do you know if there is any possibility on the right which is not covered in the left one? I will then see from the right that I used my right index or right pointer. All possible sub-arrays right pointer. All possible sub-arrays could have corresponding ends. First of all, linear search. We can think that yes, if we have one here, if we If we are starting from forest, then do a linear search in the right part as to where forest is coming. We know that if forest comes wherever we are, then we will include all the sub-arrays from there till there forest comes wherever we are, then we will include all the sub-arrays from there till there forest comes wherever we are, then we will include all the sub-arrays from there till there because on the left side of it All the elements in the right part till that particular index, all of them are greater than one, so we will include them all. Do a linear search and then if we are starting from four, then find Where is the four in this right part? What is the problem in doing linear search? Basically the problem will be that we will get time complex, hence we cannot do linear search, then what should we search? Then it should come in our mind that when we have taken out the prefix array. Is it or have we extracted the minimum array? In it, the right part is sorted in itself and the left part is sorted in itself because as we were traversing, the minimum could be less, it could not be more, so because of this the right and left part If we get sorted in ourselves then because we have sorted parts then we will simply use binary search. Why should we use linear search? Now let us understand with the help of dry run how we can do it. So I said first I will sort all the parts. Possibilities I will see on the left that if my sub array starts from here then what will be its possible end. So if I fix that my sub array will start from row 2 then I want to see its correspondence. So we have got four, so we have got four. So now all the elements up to four, I know in the right part must be one or greater than one, equal to one or greater than one because I have seen the element just bigger than that, I have seen the index and it is in decreasing order so that's why I am assured that all the elements around this four will be greater than one, so on the left, if mine is zero, then I searched one with binary search. In the right part, its index is seven, so now I have to find the minimum. I will see what is the one at the zero index, what is the three at the kth index, what is the four at the seventh index, what is the minimum of these three, what will be the one, the score will be calculated from it, similarly if I fix my pointer at one at the end of the sub array. Now I fix the number and its corresponding number is coming. Now we have to take care of this also. Now we find out its score and it comes to 28, which is the second thing, neither is there a second index, nor is there an A in it. Now it is bigger than at, just big or at. Equal to, there is nine in the right part, naan is also this and nine is also this, which nine do we have to take, if we have to include max to max elements in our array, then we have to take the right most na in this array, so that If max to max elements come in my sub array, then I will take this nine, I will take this index, so what is the minimum in this, now I have the minimum and from cut to six, this is the sub array of six. What is the minimum of 8 f and na. F has come, so now its score has been calculated. Similarly, now I will fix the right pointer. My left pointer is as possible. I have seen the case of K, we will handle it last, so now we look at the right, then right, if I four. If I fix on the fourth index then I will search on the left, what is the element greater than 10 or what is the element equal to 10, then we don't have that one, I will ignore this case, so this case is that. Maybe basically in which we are starting our sub array from the same, but because we will handle that K part separately, then in this case we can say that we are not considering this one, so if I now If I am ending on fifth then what could be its possible start. Similarly ninth is also not in the left part or any bigger element. Similarly for sixth also I am not getting anything but for seventh index I searched for four on the left and that is one index. Then again if my right seven is coming and left one is coming then I took out the minimum and took out its score. Out of all these, what is the maximum coming to me is 28 then my answer which will be returned should be 28. Before returning but one more case we have to check is that if my left pointer is at K then what can be the cusp right? What can be the optimal and second case we have to check that if my left pointer is at K then what can be the cusp left. We can check both these cases once and after that we can compare and return our answer. Now let us see its code. So what we did is we created a vector in which we will be storing the minimum. So first of all we have We have stored the minimums from 1 to zero i.e. i.e. i.e. we have stored the minimums of the left part, after that we have stored the minimums of the right part. Now I know that the minimums of my left part will be coming in increasing order and that of the right part will be in decreasing order. Must be coming in order but because I am using lower bound function here to do binary search, hence what I did was I reversed my right part because it was coming in decreasing order so I made it in increasing order. So I know that if I make it in increasing order then there will be difference of some indexes. The index which was being made earlier may be becoming six, later it may be becoming nine, so what did I do due to which my indexes got reversed. I stored them in a map so that if any index appears on my right when I search, then I do not use that index in the score while multiplying. If I see from the map what index was corresponding to it, then I can do the same. If I use it then what did I do after that, I initialized the answer from numbers K to numbers K, why the initialism is also on k and the right is also on k, that is, if there is only one and only k in the sub array, then there is only one element, then multiply by that. The value will be in the case that we have the answer of numbers, then to compare it also we are doing the initial is same of numbers, then we have run the first for loop in which we are fixing left that if the value of left is zero. Meaning we are traversing from K to left then we are going to store its corresponding answer and at last we are handling the two cases in which we are saying that if our kth element is on the left. And if our kth element is on the right, then we are returning the last answer. What is the actual thing in this that if our kth element is we are fixing, that means, sorry, we are fixing left or right on k, then that's it. Just fixed its correspondence that the array will start from k only. We always know that there can be some values ​​for the right, all the values ​​after k can be the some values ​​for the right, all the values ​​after k can be the possibilities for the right. We have those possibilities. Just try it out and keep updating your answer and at last we will return whatever value is stored in the answer. Let's run it and see. If you like the explanation, please like, share and subscribe.
Maximum Score of a Good Subarray
minimum-moves-to-make-array-complementary
You are given an array of integers `nums` **(0-indexed)** and an integer `k`. The **score** of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A **good** subarray is a subarray where `i <= k <= j`. Return _the maximum possible **score** of a **good** subarray._ **Example 1:** **Input:** nums = \[1,4,3,7,4,5\], k = 3 **Output:** 15 **Explanation:** The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) \* (5-1+1) = 3 \* 5 = 15. **Example 2:** **Input:** nums = \[5,5,4,5,4,1,1,1\], k = 0 **Output:** 20 **Explanation:** The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) \* (4-0+1) = 4 \* 5 = 20. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 2 * 104` * `0 <= k < nums.length`
Given a target sum x, each pair of nums[i] and nums[n-1-i] would either need 0, 1, or 2 modifications. Can you find the optimal target sum x value such that the sum of modifications is minimized? Create a difference array to efficiently sum all the modifications.
Array,Hash Table,Prefix Sum
Medium
null
1,631
the problem 1631 and we are trying to find the root effort which is defined as a maximum absolute difference between any consecutive cells and we want to return the minimum effort here so for example one three five the minimum effort here will be two since uh the absolute difference maximum will be two here and if we go from one to two to five in this path the maximum absolute effort will be 3 because it's capped by 5 minus 2 or 2 minus 5 absolute so first of all to this problem we can think of the dffs in this uh first look because um if we are using a dfs then for each cell we have to decide whether we want to use this cell or we don't want to use this cell which is uh 2 which is the time complexity will be 2 to the n if n is the number of cells which is uh not acceptable we have to think of a method that we can go through each cell in just once just the ones so this is uh this is remind us about the minimum spanning tree which is we can use a bfs and a priority queue to maintain this bfs so if we are initial q here and we maintain the priority q by the current max this is a current max means the current maximum absolute difference in this path and if we ever see a node for example the node 5 here we don't have to go through this node again since as you know we first time we seen a note means from the start to this note we have the uh using the mean minimum effort that's the reason why we're using a priority q to maintain it so in this way we can go through each node just once if we ever meet the uh if we first time made the right the last corner here which is 5 then we directly return the current max and if we ever seen this node before we just do continue for each node we have to see the or consecutive nodes of it first of all we have to make sure the node is valid and to maintain the heap cue we are doing calculating the current div which is whether is in this path whether it's a current max or not and we define as a current div and push it to the heap cube so the total complexity here will be n times log n if n is the cardinality of an or the number of nodes the m means we can go through each node only one only once and log n means the time to maintain the heat pq the hip q which is uh tp5 but when we take a second look we can see the heights here are constrained from 1 to 10 to the 6. the thing is here the thing here is uh we can define a height a constant height here and for any constant height or for any constant effort i'm saying for any constant effort we can say whether this is a valid effort or not for example if i give the maximum effort as five so then one two to five is a valid path since we're only using for three here so in this way we can doing a binary search to see which effort is the minimum effort we want so that introduced to a second method here which is uh the lower bound will be zero or lower bound will be actually one here and upper bound should be 10 to the 6 that's the uh bound of the efforts and the only thing for each effort we want to see whether this is a valid f4 or not if it's a valid afford means the effort can be smaller than the right equal to mid to find the weather is a valid effort we can either using a dfs or bfs i'm using abfs here and one thing i have to mention here the reason why we give a fixed effort is we can determine whether this is a whether we can find a valid path using this effort by going the whole graph only once that's the key idea here which is how can we make sure that for each node we can just go through it once so using dq to maintain it once we can see that i j equal to the mn which is uh this node then we can return true otherwise we cannot meet the last node so we will return false here
Path With Minimum Effort
number-of-sub-arrays-with-odd-sum
You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e., **0-indexed**). You can move **up**, **down**, **left**, or **right**, and you wish to find a route that requires the minimum **effort**. A route's **effort** is the **maximum absolute difference** in heights between two consecutive cells of the route. Return _the minimum **effort** required to travel from the top-left cell to the bottom-right cell._ **Example 1:** **Input:** heights = \[\[1,2,2\],\[3,8,2\],\[5,3,5\]\] **Output:** 2 **Explanation:** The route of \[1,3,5,3,5\] has a maximum absolute difference of 2 in consecutive cells. This is better than the route of \[1,2,2,2,5\], where the maximum absolute difference is 3. **Example 2:** **Input:** heights = \[\[1,2,3\],\[3,8,4\],\[5,3,5\]\] **Output:** 1 **Explanation:** The route of \[1,2,3,4,5\] has a maximum absolute difference of 1 in consecutive cells, which is better than route \[1,3,5,3,5\]. **Example 3:** **Input:** heights = \[\[1,2,1,1,1\],\[1,2,1,2,1\],\[1,2,1,2,1\],\[1,2,1,2,1\],\[1,1,1,2,1\]\] **Output:** 0 **Explanation:** This route does not require any effort. **Constraints:** * `rows == heights.length` * `columns == heights[i].length` * `1 <= rows, columns <= 100` * `1 <= heights[i][j] <= 106`
Can we use the accumulative sum to keep track of all the odd-sum sub-arrays ? if the current accu sum is odd, we care only about previous even accu sums and vice versa.
Array,Math,Dynamic Programming,Prefix Sum
Medium
2242
934
There are six things to do, look, there are a lot of questions, there is nothing to stress you, what do you have to keep in mind here you have to keep two most important things in mind, first of all, make yourself clear here. It is given that there are exactly two islands, exactly how many islands are there in our grate, okay, so what can we do in this, the simplest thing is that we will start it once, you can start it, you said, okay, as soon as you Encounter happened on one story also, one way present student like he will encounter himself there, he will do it here, from there he will run one of his DFS that yes, which lenses are connected to this one, all the lenses are absolutely correct, now you can do that. Mark anything, exercise date means you have to make it like how to make it, forgive him and keep it's okay, after that what do you have to find, after that you have to find the step of the nearest land, you have started, its big. A little bit friends, now where will the most romantic night start that as soon as you got one and once up connect, all the lunches you were getting, what did you do with all of them, you stored their pointers and then you moved their pointers. You will try and see, okay, think a little about it, but it will become a very easy question. Okay, those of you who have not understood this problem, there is no need to take tension. First of all, you are going to understand this question very easily. Tell me what was the six, after that we will approach it and give the final bill set implementation. Look, there was six to understand. Look, I said my question, okay now example one and what you are is very simple, I am not understanding anything in it. That's why we are not doing it, I said in an attempt to understand, okay, here is a matrix of life, what should we do in this matrix, try to understand carefully, the one in this matrix is ​​representing it. If one in this matrix is ​​representing it. If one in this matrix is ​​representing it. If you say land, then what is this, what should you say? If this land is in its four directions, that means it is the land, its upset side, left side, right side, if there is any other land in its four directions, then what does it mean? That they are connected to each other, so it was to the right of this, okay, so what has become of this saree of sarees, as well as this is also connected to this, said yes, whenever you are absolutely right, along with that, this is also connected to this. He said, yes, it is a matter of Jabal itself and it is also connected to it. JB, it is absolutely correct, it is correct, yes, now this entire land is connected to each other, which means that the land is made like this and what is the water in it in between? Okay, there should not be any doubt in this, now there is water in the middle of that there is one more land built here, this land here is another one built here, now it was not necessary here that you just It is possible that it is made up of only one line, if it is like this, then actually it must be connected. If there is one line here also, suggest what happens to this land, if it is connected, then this land will become something like this. This is absolutely correct, now what was given to Apna in the question that whatever matrix life Apna will have, there will always be two different land lives along with the hobby Apna has, this much was already given in the question that in this There should be no doubt, it's okay, these are separate lands of ours, life will always be there, so one line is this and one land is ours, okay, and there will always be only two, sometimes we will be more than friends, and sometimes we will be less than two. Now what you have to do is you have to make a simple form, you have to turn that this land and this land, if you want to connect these two, then what is the minimum number of lands? Now you will have to insert in the middle. Now what does it mean for the lands to come in the middle of all these, what will you have to do by flipping the 0, like if you flip this zero and make your band, then what happened is that these are also connected together, even if Do this to zero or do it to zero, read it to anyone, what will happen in this way, I used to have answers from every side, there was only one A, then that one of mine is gone, now let's just accept this land of ours. Something like this happens here and yes, just join it like this is your last one, it is okay, it is your zero and this is also yours, propose it is okay and this is also your zero, one line. He comes from here and he said that he has got one land here, it is absolutely correct, he has two lands How many flips will have to be done, how many flips will have to be done, he said, okay, it is absolutely correct, so let's see, to reach here, you may have a method that if you reach from here, then to reach from here, you will only have to do one and one or two. So one, you have option A, and one, if you go from here, you will have to flip your three, one, three and two, everything is tight, it is absolutely right, if you go from here, then flip your two from here also. If you feel like it, then you will have to do this also, give me this, then tell me to you, now there is no less story than that, what is happening at this point of time pass, you are understanding that we were giving different answers from here, we saw it from here. From this side, we have seen two A's. From here, we have seen three A's. Then what will we do? Two means the minimum answer, whatever is our answer, we will always return it. A simple thing should be clear now the question. Understanding of the question becomes clear here below and still there is any diet then the answer is given by watching the one minute video once. Understanding of the question is very important and still I have doubt then the version which is written in the comment box is ok now. Here you have understood the question very well, there is no doubt in the question, so how will you approach it, now you will have to do it simply, here you have a grid, it is matrix form, that is, you have 2d matrix c1, it is very simple. It's a matter, there is nothing else, okay, now I can do what is found in today's matrix, I said, yes, I put a loop, put another four's look inside it, you can travel on the entire matrix, it is not a matter of phone, okay Now as soon as I started Matrix and I got the land on the story once, I got the line on the story once, I said, it is a simple thing, there should be no doubt in it is a simple thing, there is no doubt in it. This is the place where I will get my first time line, I am there, the tower is here, now as if I got the land, I did five here, now how can I forgive this, am I marking it as minus one because I have this line now What I'm going to do is I'm going to go to all the lands on the connector and I'll talk to you guys. Okay, so I marked mine here, mine one here, -1 here, -1 here and y7, I marked mine -1 here, -1 here and y7, I marked mine -1 here, -1 here and y7, I marked mine around it. It is said that wherever there is one connection, it is okay, wherever the direction is coming, direct connection has been given, we have marked all of us as minus one - we have marked all of us as minus one - we have marked all of us as minus one - What is the reason for marking 1 - What is the reason for marking 1 - What is the reason for marking 1 - Some reasons for marking 1, this is a simple reason that our All I had to do was to install here that Apna has already been visited, now there could have been many methods for this, either what Apna does is that Apna creates another matrix, so Apna did not create this disloyal thing there, okay and any other Why can't you do anything in this, just keep in mind that you have already been visited, so apart from zero and one, you will have to make some marks there or if you do not want markers then what else will you do? Make a matrix and store inside it that you have visited this position, what did you do, wherever you visited, were you completing one line, were you completing all your places, what will you do at this point of time. Now it is very simple, what will we do that this one is minus one, okay, first we will see from here that if our one step story goes in any direction from here, okay then what should be the direction, Shakti is upset left. Side, Right, Side, Dr. Side, it is okay, it should be only one direction from all four directions, Shakti said, it is absolutely correct, it was not possible to go to its website, so please check yourself, it is not possible to go to your side, it is not possible to go to the left side, it is still possible. No, there is a bunny on the right side, so leave the right one too. What is there on the right side? This one is okay, leave this one too, so you can't even go to this point, leave this one, then I was making my first one. The line was that they all do n't know what all has been given now because they were not going to tell their story from this position so why will they remove it from it then because this position is of high quality, what happened in this position, you saw it. Maybe it is not possible. It is not possible on the left side. Vanita is not there. This is not possible on the right side. Vanita will not go. There is zero on the Dr side. Here, Apna can, what will we do? From here, we are trying to reach Apna second line. Okay. He said, it is absolutely correct, so you could have reached on the second line and now you have reached here in the first step. Also first step here you were coming, I am fine then here you have done mines one, in this also here you were coming, you will take out from every condition that if you move forward one step in every condition, then how far will you reach. You have reached among all the heroes, it is true that you will take one more step forward, as soon as you reach the second step, now look, you have got 1. He said, yes brother, you reach the second step, if you have got one, then your number is How big do you have, what will you do, you will make the mines one, it means that it is absolutely right, it will become your answer, once you have tried it a little, what you do is that you remove these minds, sorry, where you get one. I went from there, what did I do? From there, I took out all the connections of the land. Okay, I took out all these connections. I stored all the positions of these connections, there should be no problem. Said, yes brother, it is clear, then what did you do after that, from this forest, you saw that there is no present on the left, now there is no present on the side, you will not take the right side, then you came to this forest, ahead of this forest, you made yourself in this position. You could have forgiven all these settings, then what did you do, go back one more step, now one more like this, when you move ahead from here, you turned around when you reach here, if you move forward from here, you just reached here. If we move forward from here, we will reach here. But if we move forward from here, if we read this, then we are reaching straight. If we move forward from here, we will reach straight. This one is correct. Yes, now just tell your total number of steps, no matter how many steps, three steps too, what will we say out of three steps, one step - do it, what will we say out of three steps, one step - do it, what will we say out of three steps, one step - do it, because in that you have already done 5. Said, it is absolutely correct, then how many steps back has the number of steps gone? You also had to do your turn. It's a simple thing. It's very easy in MP. Look, come here, this was my function which had to be built. I have come here, what have I made, why have I made mine? What is the store, but what all should I list? Firstly, restore your weight, that is, you had said that on the point of time, you will store it, you will put it in its position, you will solve all the positions of Arun Saare, absolutely correct. I will come after that, I have made it a variable, what will you store in the open middle, the punishment in this is the total number of Stephanie in the bullet, okay, I have stored it, okay once more, what is important here is that the grid you have is always there. Will be found in square form, meaning N will be found in cross N only. Okay, her number of days and number of following are sufficient. She is that girl. Okay, tell me, if the numbers of days and columns are different, would you have changed your approach? Did you say absolutely not? There is no video friends in hoti approach, ok, it is a simple thing, then what have you made, ok, true, what is this, what should I tell you here, understand this carefully, what did you say, I did not find a pen in which Apna Supose Variety, then Apun will come to the other. Apna wants this, he trades on Puri Matrix, it is absolutely right, now what will happen here, as if Apna got it, okay propose, Apna will come here, then let's meet, then what would Apna wish that you ever do? He also said that it is absolutely correct, how will you know from the look of this phone that if you do not do any research on it then have you made cake woolen true there then have you taken it as true that you have not found it yet then right now You are giving him till then, he said, okay, so let's go, what did you say that right now what is your number of followers, keep attracting them, within that, how much number of followers keep retrieving on them and you also check yourself whether the great one. Is it done ? As soon as the value of the grid becomes one, we will connect all the lenses and once the point of time will be reached, there will be a condition like land once, okay yes brother, do this, it is clear in this. There is no doubt, now let's understand what we are doing in this VFX function. It was our quality affairs function. The first thing in this is the pen. What did you say that just now our pen and pen have come and what is the pen? And what is the position of the one who has come? Is his position completely correct? Yes, on the position, Apna told him it is okay, so I have come and sent the position to his position, why did he send it? What is the meaning of Apna, what are you doing in the position, that Apna Jo is crying, 10 scope. It will not work or it will not work out of scope or it is not ready because what you said is that it is already connected, how will we do both of these, what will we do and will we return it is absolutely correct that you have considered this condition here. You could have written also, I have written below, not that one, it is fine, what happened after that, I came to know that now I am not at zero, I am out of my scope, I am guested, what would mean that it is land connected. So, if he is land connected then what will you say that why would I push him? They had already discussed his position with this cheese, they are talking to him and what have you done, marked him as guest, made him minus one, tell me. This is absolutely correct, then what did you do with the DFS function, meaning, with this, you changed the function back to yesterday, now once you have minus one from your, that means R is representing, wait -1, what does it mean, you have wait -1, what does it mean, you have wait -1, what does it mean, you have gone in the above direction. I told you that you can go in this direction. I went to check the upper direction. I went to check the lower direction. Once I went to check what happened to me, I went to the left to check what I did. I went to check what I did to the right. I wrote plus one in the pen and said. It is absolutely correct, so now I am understanding the condition here that I had to put myself because as soon as I had automatically got 1 on the first position, I said, it is absolutely correct and now will you go to check above here? It is possible to go above D, so if it is not that then it will go out of D of the matrix. It is not going much, isn't it? Okay, if this phone is going out of D, then what will we do with it? The entire connection of one land has been taken out. Now what you have to do is you have to move one step forward from all the connections you have in the line and first of all check yourself, whatever you get on the other steps is absolutely correct. Well, now one more thing is important, why are the elders looking at the steps, look at the steps, you will do everything as your own, then it is not necessary, is there a minimum in this, can there be a minimum from this, can there be a minimum, what will everyone do? First of all we will teach each step one by one and then we will see if the fan has reached there and if it has not reached then we will give one more step to all the steps, then as the total increases to four steps, it is absolutely correct, then on the third step we will bring this type till What will we do till we reach our mother, we will move one step at a time, but everyone said yes, when it is clear, then you come to your place, till whatever is yours becomes empty, then keep moving, he said, ok. It is absolutely correct, then what did Apna say because perhaps Apna has taken it and made the answer plus. What does it mean to make the answer plus that the one who took one step forward said this is absolutely correct, meaning Apna because perhaps Why did he know that all his people were going to run low, there should be no problem, then what did he do so that he would take the role of what he would do, if he would come up, what would he do when he would come up and when his own third position and his also in third position? If you take a position then what will you do, you will move to the side but there should not be any doubt, then what did you do to become, on top of this, on top of S means all of them, as many as possible, from there on all the steps. What did you say to run it? I said it's okay so whatever it is, first of all take the ITM because it is in the front and pop it. First of all it is absolutely correct. It has two values and what is there in the second part of the ID. So your What did you do to represent him from the current foreign, it is absolutely right, now your tax condition is possible from there, you side dr side website right will not work then what did you do, inside him there are two interiors - NC and Nar said ok two interiors - NC and Nar said ok two interiors - NC and Nar said ok what in Nar What will happen in the e-mail of your new robot? If there will be a new pen, then the new What will happen in the e-mail of your new robot? If there will be a new pen, then the new What will happen in the e-mail of your new robot? If there will be a new pen, then the new Nokia Current Plus will automatically check all the conditions which I told you about the UPSIDC Dr. Set i.e. told you about the UPSIDC Dr. Set i.e. told you about the UPSIDC Dr. Set i.e. conditions, then I checked the story of this. The condition is, first of all, tell me whether she has gone out of the spoke or she has not gone, if she has not gone out from now on, then what did you say that if yours is zero, then what will yours do? If zero comes, when will you push her? Will do this and will also mark 0. One of the mines means that its own has been selected, that is fine. There five will mark only one. Now what will we do here, we will talk about zero. This is absolutely correct and if our zero is No, okay, what condition can it come in, either it is -1 or it will what condition can it come in, either it is -1 or it will what condition can it come in, either it is -1 or it will become, he said, okay, when will -1 come, then I become, he said, okay, when will -1 come, then I become, he said, okay, when will -1 come, then I checked whether the minus is one or it is one, then I checked the specification here. Leave this function in the function, he said, it is absolutely correct, then Apna started one, so here Apna time blaksiti talk, Apna first look at the space, is it six or Paneer total, how many spaces do it have, then see Apna space. There was no space of our own in it, everything is constant over there, it is happening here, why in making our items, worship is also the power, oh, so what will we say, how much of our space has become, how will we equal our time, how much is ours? If you are running and v2, then it is correct that N* is smaller than N because N* is smaller than N because N* is smaller than N because even if the number of columns is A, there cannot be any more. Said, it is absolutely correct, then it would not be the same. Actually, you must have understood it. Thank you, thank you
Shortest Bridge
bitwise-ors-of-subarrays
You are given an `n x n` binary matrix `grid` where `1` represents land and `0` represents water. An **island** is a 4-directionally connected group of `1`'s not connected to any other `1`'s. There are **exactly two islands** in `grid`. You may change `0`'s to `1`'s to connect the two islands to form **one island**. Return _the smallest number of_ `0`_'s you must flip to connect the two islands_. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** 1 **Example 2:** **Input:** grid = \[\[0,1,0\],\[0,0,0\],\[0,0,1\]\] **Output:** 2 **Example 3:** **Input:** grid = \[\[1,1,1,1,1\],\[1,0,0,0,1\],\[1,0,1,0,1\],\[1,0,0,0,1\],\[1,1,1,1,1\]\] **Output:** 1 **Constraints:** * `n == grid.length == grid[i].length` * `2 <= n <= 100` * `grid[i][j]` is either `0` or `1`. * There are exactly two islands in `grid`.
null
Array,Dynamic Programming,Bit Manipulation
Medium
null
41
welcome to september's leco challenge the last question of the month today's problem is first missing positive given an unsorted integer array find the smallest missing positive integer example one two zero the smallest positive integer would be three example three four minus one the smallest positive integer would be two and the example seven eight nine eleven twelve the smallest positive integer would be one now they want our algorithm to run in oven time and use constant space so that's going to be tricky but let's initially start with how we might just solve this brute force well we might think well we can sort this array and check to see which is going to be the not the increasing by one positive integer or something like that but that's not very efficient let's think about how could we do that um using extra space instead one of the ways you can do that is by having some sort of set that's going to keep track of what we've seen so far so we'll have a set called scene and what we'll do is set our output as one at first because that's going to be the minimum positive integer possible and we'll say 4n and nums we'll add it to our scene set and while output is still in scene we will increase our output and doing this is actually going to return the right answer and it's actually quite fast surprisingly but is this o of n time and technically it's not right because it's o n here but we'll have this while loop being multiplied by however many numbers that we might have would be the range of o of n so it ends up being like basically n squared so how could we do better well let's think about like if we had an array like this one two three four one things you might notice pretty quickly is our minimum positive integer will be in between the range of one all the way to n plus one inclusive and the reason for that is this is kind of the maximum posit like numbers that we could have right so here the exam the answer would be five and that would be indeed four plus one that would be five now it doesn't matter what the numbers in here are if they're like negative 3 40. regardless the number for the least positive integer has to be within this range here the answer would be 3 and that indeed is still in between one and n plus one so how can we use this knowledge to take advantage of um going through our array just one time to figure out what is the minimum positive integer and we could do that by having some sort of array that's going to be represented by all zeros at first and each one of these indexes is going to represent a number it'll be like one two three four and we actually need one more for five and what we'll do is go through our array and just mark these if we've seen them before so we've seen one so we'll mark it scene two we've marked it negative three i mean the negative negatives and numbers out of this range don't matter so we don't care about those and then we just go through our array and say oh three is our minimum one so the answer is three so we can do that and that would be o event time right so let's do that first we need to append one more number to our nums let's make it zero because it doesn't really matter there and what we'll do is initialize n as length of nums and we'll set an array this array is going to be all 0s at first for blank and range of n now what we want to do is go through our nums and just mark these this array if we've seen the number before so what we'll do is say for i and range of n if the number is within this range so if numbers that i is what if it's greater than zero and less or equal to n then what we'll do is take this number and update our array so we'll say numsai increase it now once we're finished there actually i need to subtract one here because the one is actually going to be represented by the zero index right so make sure you know that and then we'll just go through our array and say if dot array.i equals zero that's going to dot array.i equals zero that's going to dot array.i equals zero that's going to be our minimum one so just return the i plus one and let's see if this works and that works now this is great this is oven time yes we make two passes technically three but whatever um it's still oven but this uses extra space right uses on space so the hint here was well using this approach how could we solve it without using extra space and that's difficult that is very difficult because if we had some example like um like this we might go through it and keep track of like what's the minimum number so far and say well one it's gonna be one here but once we reach one we have to increase it to 2 right but unfortunately we kind of lost track of the fact that 2 still exists and unless we go back and search the entire array again we can't figure that out so you so using like just integers is going to be using just integer variables is gonna be really hard to like what if this was like a three here you know it has to go up one two three four five all the way up so what could we use to store that information well what about the array nums itself could we somehow tinker with that without losing information from the original nums but mark somehow that yes we've seen this number because we could use this array to mark as these representing these the range right one two three four all those numbers could be represented inside of this array but the trick is how can we make sure to keep this information of the number itself and add that it's been marked well one of the ways we can do that is we can add the length of this whole array which would be what nine and have use a modular every time we check to still keep the information of what the original number was but each time we like updated with n we can say that yes we have marked this position so if it's greater than n than we've seen this number before so we can actually use the number array itself to do this okay so knowing that's going to make it a lot easier but the trick is it gets tricky because we want to make sure to keep that information so let's first go through our um so let me delete this let's first go through our nums and what we're going to do is first get rid of the numbers outside of our range like just make them zeros because we don't care about those what we're going to do is say all right if the nums i if it's what less than zero or nums i is greater than n then just mark it as zero because why do we care about these numbers they're not going to make any difference now only numbers that are greater than zero are are what matters here right so i should say within the range but basically at this point it's going to be greater than zero so for i and range of m we'll say if our num is not i if it's greater than zero then we want to mark our number itself using the number as an index but don't lose the original information so to do that we're going to use the modular function i'll show you what i mean we'll get nums num is i it has to be subtracted by 1 remember and we're going to just add n here and to make sure to account for like duplicates and stuff we'll do the modular n in case we've been updating this number multiple times so at this point these numbers that we've seen before we're going to get marked up and now all we need to do is go through our nums again and what we'll do is say okay look if nums dot i divided by n okay if it's basically less than n since if we've seen it should be greater than n then return the i plus one right because it's zero index then we want to return the number itself otherwise if we can get this whole thing then just return n that's going to be the maximum number here so let me see if this works i forgot there is one weird edge case where the very first number the zero index should be representing one but there are cases where that number could actually be equal to n uh so when that happens like that kind of throws a little screwball so what we'll have to do is store that as a temp variable and say all right num0 store that here and just check at the very end look if nums at zero still equals the temp meaning we haven't touched it then we know the answer is one so that's just to take care of the use case um weird edge case i mean all right so let me submit that i'm not positive i did this right looks like i did great so this is all event time yes we passed it three times but we use no extra space we've just been updating our nums instead and we got the right answer so this was a pretty hard one i think this right here is quite brilliant if you can realize that yes we can mark this array index uh without losing the information this is like what's key here and this kind of reminds me it's like a mishmash of pigeonholing of hashing there's a lot of interesting things going on here so i definitely recommend taking a look into this more that's it thanks for watching my channel and remember do not trust me i know nothing
First Missing Positive
first-missing-positive
Given an unsorted integer array `nums`, return the smallest missing positive integer. You must implement an algorithm that runs in `O(n)` time and uses constant extra space. **Example 1:** **Input:** nums = \[1,2,0\] **Output:** 3 **Explanation:** The numbers in the range \[1,2\] are all in the array. **Example 2:** **Input:** nums = \[3,4,-1,1\] **Output:** 2 **Explanation:** 1 is in the array but 2 is missing. **Example 3:** **Input:** nums = \[7,8,9,11,12\] **Output:** 1 **Explanation:** The smallest positive integer 1 is missing. **Constraints:** * `1 <= nums.length <= 105` * `-231 <= nums[i] <= 231 - 1`
Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)
Array,Hash Table
Hard
268,287,448,770
332
hello friends today that's over reconstruct itinerary given a list of airline tickets represented by pairs of departure in the arrival airports thrown to reconstructed the itinerary in order all of the tickets belong to a man who departs from JFK thus the ident itinerary must begin with JFK and the problem also mentions that we need return lexicographically smallest order so if there is a time let's see this example we first start from JFK and there is only one ticket depart from JFK so we go to UMUC next and then there is also one ticket from M you see to AOH R so we go to this place and the we keep going in the finally we go to SJC so this is owning order we can construct from these four tickets so there is a place and there is a directional this there is a direction so bases this is a directional age and this is a vertex so this relation can be represented by a graph and usually we will we use agency lists and in this problem we also needed to return Alex Cole graphically smallest order so we paid her use a priority queue here as there are no more lists because when we try to get the arrival we can quickly get the lexicographic smallest string okay this is the data structure and I think this problem has some similarity with the public so 2/3 EFS similarity with the public so 2/3 EFS similarity with the public so 2/3 EFS the implementation let's first test see the visualization listen the graph and then we try to get other talk topological odor from this graph so how to get that we go from here and we keep into DFS and we put it is 7 and then we put 4 in the to 0 and the 1 and the 3 so we basically we start from one vertex and we keep doing DFS until there is no other neighbor vertexes we push that to know the into the stack and we then push the 4 right and then 2 and then 0 and then 1 and we keep do the DFS from the 3 and we put these three and five and six and the way we try to get them topological order we pop the notes of thrown the stack so in this problem is the same we start from JFK and then we find there is Lester there is two places which is ATO and the SFO and as a TL is the lexical graphical smallest so he called you ATL and at the same time we cut this H which means we remove this know the from its list and then we'll keep doing DFS and then we go to JFK and we go JFK and there is only one node in this list so we caught us f o and so on so forth and when we finally go to the SFO there is no other neighbors so we push this as they fall to their stack and then the ATL and the songs of force so finally the result just popped the notes in order from the stack so this is a final order okay so now let's write the code and I say that we need the first to write the result which is already and we need a map so this is a string and this is a priority cube it's a string a street new hash map and we call a build across function we pass the G into the tickets okay and we also need attack we try to construct the result code a stack array oh sorry array tech and we do the DFS will pass their stack in the graph and the first is JFK finally we try to generate a result so while this stack is not empty we result ads as a stack pop finally we'll return this result so now we needed to write Q function which is GFS and this place should be tagged string ah yes stack and the map string and fry already queue try rtq string which is G and this is the throne someplace from and the we also needed to write the Butte across the first parameter is map string and a priority queue G and this is us our tickets please lease three tickets so for every travel or every ticket the first item is from which place right travel get 0 and the 2 is travel get 1 so if the G does not condense from we should put the from and put a new priority queue this + put a new priority queue this + put a new priority queue this + G we get the from and the we offer to just place okay so how about the FS is that we needed to change the graph so we first get the priority try all right priority queue stream which is arrivals new to get the from so while these arrivals not equal to no and the arrivals is not empty we get a tattoo which is from G gets from and we pull from the priority queue and we keep doing the DFS right which is a stack and G and another from is the two this is an access tower while this they had this place had no neighbors so we push the Artic to the stack we push the front to the stack okay so there should be finished okay but we can do a little team ization and you can see the function of this stack is just to change the order of the changes of older is like a reverse order so actually we can do not add the place to the end of the stack we can add it directly to the beginning of the result so we can just use a linked list the holing Lister has a method of air the first link the list so we do not need a district which has a pass this result and this place we can give it eight so currently this is linked list we could result and the result so now we just need a result at first the from so this basically is the same function actually you can also use a release that you can add a zero into the place okay thank you for watching and the Happy New Year see you next year
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
67
Hey hey what's up guys Nick white here I detect OD stuff on Twitch on YouTube haven't posted in a day or two we're gonna get back on it right now check the description for all my information I do premium leak Oh problems on patreon and join my discord this is ad binary this is easy problem got a lot of likes if you don't know a binary is it's like the first thing you learn in computer science is that there's more than one number system so we use a decimal base number system base 10 which is you know 1 2 3 4 5 6 7 8 9 so there's like 9/10 1 2 3 4 5 6 7 8 9 so there's like 9/10 1 2 3 4 5 6 7 8 9 so there's like 9/10 you know up to 10 different numbers right but for binary it's actually base 2 so there's 2 different numbers there's 0 and then there's one that's what binary is computer science binaries is made up a bunch of zeros and ones you might have heard that before but decimal and binary can both represent the same thing the number 3 in decimal is equivalent to the number 1 or 11 in binary and that's because this is how binary works so that the least significant digit is worth this is worth a value of 1 and then it goes up its exponents it's a exponents of 2 so then this is worth 2 then this is worth 4 then this is worth 8 then 16 32 64 etc so least significant digit is worth 1 and then it goes up by exponents of 2 each time you go to the left so this is the idea here what we want to do is given 2 binary strings so we're given two strings that represent binary numbers then return there some so also a binary string so we want to return the sum as a binary string the input strings are both non empty and contain characters 1 or 0 okay so they're not and there's no empty strings either so let's see for the example what we're dealing with here so this like I said at least there's only one digit so it's the least significant so this represents one it's just one this represents three because it's one plus two when it's a one in that place so yeah when it's a zero it still means zero but when it's a one it counts as that factor of two so this counts as one if this was the number it would still be 1 but this is 3 because this counts as 2 in that case ok so this is you know 2 plus 1 which is 3 plus 1 which is 4 so you can't represent 4 with just 2 characters so we need another character and so we have a 0 here 0 in the ones place here on the twos place and then one in the forest place so it's 4 there you go so you might notice and then you can go through this example if you want to but you might notice that the way that we want to do these in almost when you're doing all these number problems are adding numbers of strings or there's actually a lot if you didn't notice but um you want to start in addition especially you're starting at the least significant digit when you do addition if you're doing addition just on paper if you're doing like 436 you know plus whatever plus you know 49 you're gonna start and you're gonna do 9 plus 6 you're gonna carry the 1 and then you're gonna do 4 plus 3 plus that 1 and etc and you're gonna fill out the number from least significant digit to most significant digit and that's what we're gonna do here so we're gonna go backwards we're gonna check ok 1 plus 1 and we're gonna say ok if it's greater it only goes up to 1 so if it's 1 to ones then we're gonna have to that's going to be a 0 and then we carry the 1 over and then it's 1 and 1 again and that's a 0 and we carry the 1 over and that's how we get 100 so to do this we need a stringbuilder because we're doing this in Java and that's how you construct strings so let's just start writing that out I'm gonna do string builder SB equals new string builder it's just a class we're gonna loop backwards so we're gonna set our indexes for each of the strings so we'll say I is equal to a dot length i's gonna be the pointer and each character and the a string going backwards so a dot length minus one in that J is gonna be the pointer in these going through the B string backwards so we set it to the last character of each index we're gonna initialize a variable called carry this is going to handle when we add a 1 and a 1 we want 1 plus 1 is 0 it's gonna be 2 but we carry we turn it into a 0 and we carry the 1 because there is no 2 in binary so what we're gonna do is we're gonna have this while loop will say while I is greater than or equal to 0 we're gonna go backwards like I said through the string or j is greater than equals 0 and we do or because we want to traverse them both completely we don't want to break when one of them is finished right if we're doing like I said 436 plus 49 you know you do the addition but you even if there's no number if this was a and this was B even if there's no numbers left here you keep traversing because you want to add up this you know with nothing so that's it we for the rest of this will set our sum equal to carry and then what we're gonna do is we're going to calculate the current sum of the two digits that we're looking at so sum will be plus equal to the current character we're looking at an A which I is the pointer so a dot char I minus the character 0 to get the value 1 minus 0 is 1 0 minus 0 is 0 so this is gonna give us the value either way but what it's doing is converting a character to a number here so this is the idea we're gonna do some plus equals B char at J minus 0 and then what we're gonna do is if there we're gonna do SB dot append some mod to so why do we do this why do we append a the modulus well if both of the current characters were looking at like in these strings so we look at this example if both of these should do this to make it more even so we're doing the addition between 1 and 1 it's 2 so we carry the 1 and turn this into a 0 so what we're doing is if they're both 1 then sub mod 2 will be 0 so we append a zero for that particular index we're looking at which is right because we want to turn this into a 0 and then we want to set carry equal to sum divided by 2 and what this is going to do is it is going to tell us if it was 2 so if it's 1 + 1 - 2 divided if it was 2 so if it's 1 + 1 - 2 divided if it was 2 so if it's 1 + 1 - 2 divided by 2 is 1 so we carry a 1 which is exactly what we want to do right in our output string when we compare the last characters and it's 1 and 1 we will say okay we add the sum so we add some one we had some now we have to sum mod 2 to mod 2 is 0 so we append a zero to the string and then we carry the one over to our next addition and that's exactly the strategy that we want to do here so that's what we're doing we set the carry also you have to decrement your point pointers each time always got to do that and at the end of this the only thing that we have to worry about is append is actually going forward so for the next edition so we carried the 1 right now we have to add the ones again and we get 1 plus 1 is 2 again so we carry the 1 again and we got another 0 but we're appending it like this and then the last addition is 1 so what's happening is this is our answer but it's backwards so we want a hundred but it's 0 1 because append puts things at the end there's not string builder dot put to the front so what we actually have to do is we have to when we return we have to do SB dot reverse dot two string so that's the whole thing and the other thing is if there's a carry left over at the end of this loop we want to add it at the end so we can do if carry is not equal to zero then we can just append that to our string sb depend carry so this should be good the only thing that you might want to do is if one string ends before the other like I could finish before J you want to make sure you're not gonna try and keep adding the current character because it'll be index out of bounds so actually you want to add conditions here to make sure that we're still equal you want to say okay if I is equal greater than or equal to zero and zero just to ensure because one of them will finish first Kenza since it's an order condition so this should be fine I would assume there we go so that's the whole idea it's kind of just scanning through both of the strings and doing the addition little binary calculations if you don't understand maybe lookup binary a little bit more I tried to explain it pretty well but um I think I did pretty good let me know in the comments if you don't understand anything but yeah good solution pretty quick good problem and thank you guys for watching I really appreciate anyone to watch the videos and supports me I love you guys and I will see you in the next video All Right see ya
Add Binary
add-binary
Given two binary strings `a` and `b`, return _their sum as a binary string_. **Example 1:** **Input:** a = "11", b = "1" **Output:** "100" **Example 2:** **Input:** a = "1010", b = "1011" **Output:** "10101" **Constraints:** * `1 <= a.length, b.length <= 104` * `a` and `b` consist only of `'0'` or `'1'` characters. * Each string does not contain leading zeros except for the zero itself.
null
Math,String,Bit Manipulation,Simulation
Easy
2,43,66,1031
1,051
hey welcome guys so that song is one zero five one high checker so school is trying to end your photo of all students right so you have a photo a student i'll ask the standard single file a line of non-decreasing order for non-decreasing non-decreasing order for non-decreasing non-decreasing order for non-decreasing okay now this probabilities is probably important but uh okay so you're giving a very highs represent the current order extend in and whatever and then you need to return a number of indices which they do not miss do not mismatch so this is expected okay so one four two one three if you sort it you get one two three four so you get a mismatch there are three mismatch and for this one everything is mismatched so you get five and for this one it's not mismatched everyone's perfect okay so uh the very simple ways to just sort it is expect sorted it's original height and it goes through the array right and again okay so this will be unloaded right because uh you use the sorting so unknown but you see you can see this problem is basically only 100 right so the standard approach uh when this is very small you can use a counting sort right you can use a counting sort okay so counting so it's very easy you define h to be zero to be one hundred zero and one because i mean you have one i mean and you start from the heights and uh you count how many uh different heights with the same height so for example there will be three one and a one two one three one four now we need initialize the answer right and you basically you go through it and then you just check you just get a you just sort it right so after these parts your answer will be well released your answer will be expected right so this one is answer will be expected so this is just the standard counting sort okay so now uh you compute the length and uh define the answer to be zero and go through each one by one so this is linear time uh it should be m plus 101 so it's linear time and uh check where they are if there are difference then you add one right so basically it is just the counting sort okay very simple okay so see you guys next week
Height Checker
shortest-way-to-form-string
A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in **non-decreasing order** by height. Let this ordering be represented by the integer array `expected` where `expected[i]` is the expected height of the `ith` student in line. You are given an integer array `heights` representing the **current order** that the students are standing in. Each `heights[i]` is the height of the `ith` student in line (**0-indexed**). Return _the **number of indices** where_ `heights[i] != expected[i]`. **Example 1:** **Input:** heights = \[1,1,4,2,1,3\] **Output:** 3 **Explanation:** heights: \[1,1,4,2,1,3\] expected: \[1,1,1,2,3,4\] Indices 2, 4, and 5 do not match. **Example 2:** **Input:** heights = \[5,1,2,3,4\] **Output:** 5 **Explanation:** heights: \[5,1,2,3,4\] expected: \[1,2,3,4,5\] All indices do not match. **Example 3:** **Input:** heights = \[1,2,3,4,5\] **Output:** 0 **Explanation:** heights: \[1,2,3,4,5\] expected: \[1,2,3,4,5\] All indices match. **Constraints:** * `1 <= heights.length <= 100` * `1 <= heights[i] <= 100`
Which conditions have to been met in order to be impossible to form the target string? If there exists a character in the target string which doesn't exist in the source string then it will be impossible to form the target string. Assuming we are in the case which is possible to form the target string, how can we assure the minimum number of used subsequences of source? For each used subsequence try to match the leftmost character of the current subsequence with the leftmost character of the target string, if they match then erase both character otherwise erase just the subsequence character whenever the current subsequence gets empty, reset it to a new copy of subsequence and increment the count, do this until the target sequence gets empty. Finally return the count.
String,Dynamic Programming,Greedy
Medium
392,808
1,822
let's solve sine of the products of an array so we have a function it's called array sign it has a parameter which is a vector of integers by reference it's called nums and we have to find the products of all the values in the array and determine the sign of the results so if the result is positive that is the products of all the values if it's positive then we have to return 1. otherwise if it's negative we have to return negative one in any other case it's zero so we have to return 0. first I have a result variable you can use a long type if you intend to get the actual products of all the values but then again it's a bit risky because if you look at the constraints here the values range from negative 100 all the way to positive 100 and we have anywhere between 1 and 1000 values so it's likely that you're going to run into an integer overflow meaning that the value is going to be too large to be stored in any kind of integer in this case it's simply better if I change this to a short integer to store A1 and then I change my Approach so I'm not actually going to find the products of all the values but instead I'm going to concentrate on the sign of the results and to do this I can actually substitute the values in this for Loop here you can see what I'm doing Lane to avoid integer overflow I'm substituting all the values with a 1 a 0 or a negative one so if the value in my array at index I is a positive value I'm just going to multiply my results by one if it's a negative value I'm going to multiply my results by negative 1. in any other case I multiply by zero now I can focus on the sign of the results by having this conditional statement here if the value is greater than 0 then I've written one otherwise if it's negative I return negative one in any other case we return is zero so this matches the conditions that they have here and it also prevents this solution from running into any form of issues such as an integer overflow so let me run this we pass the three sample test cases you can see what they look like here we have very small values same thing for here and here as well I'm sure that if you check the other values in here you can check with very large numbers and this code should still be fine so let me submit this now so that we can check what happens and we've passed everything without any issue so that's it for this lead code coding challenge it's called sign of the products of an array if you like my C plus Solutions Please Subscribe and I'll 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
69
so welcome to my channel doctor today we are going to solve a problem called square root of x so the main intention is to understand what are the intuition behind this problem so when somebody asks you sk find the square root of x or find the cube root of x or find the power of x there is a common algorithm or you can say it's common cracks or the problem is same so we need to implement a square root and we have given input integer as x and given output should return type should also be integer okay so what does that mean if you have 8 the square root of 8 is 2.82 so we are the square root of 8 is 2.82 so we are the square root of 8 is 2.82 so we are only interested in integer part of it square root of 4 is 2. so yeah that's the problem is now take an example as 16. so you need to find the square root of 16 which is actually 4. so let's say you have numbers like 1 2 3 then 8 9 and then 16 right so we can use something called binary search approach here we look for the middle element so when we see it now 8 is the middle element of a range of number from 16 so 8 square it square is actually greater than 16 right that means we can we cannot find a square root of 16 on the right side of it we can always find on the left side of it so in that case the next numbers will look for this range now next we will look for mid which is 4 and the 4 square is equals to 16 right here we can return four so that's the basically uh binary search approach you look for the middle element and just square it and compare with the given input if it is equals to the x then you can return the value otherwise you check if it is greater than or if it is less than if you say if it is less than bit square value is less than value of x then you look for the right side of it and you need to store uh you need to store your output when you go for a right side so you uh let me just walk through it so the base case will be if the x value is 0 or x value is 1 then we can just written x then we can start value we can have n value now in binary search we do something like this we have a start and end now we try to find the mid value which is start plus and divide by 2 we can find the mid square which is mid multiply mid then we check if the mid square is equals to given value then we can just return bit but if this mid square value is less than x then our start will become mid plus one and we can store the answer value estimate else and should become bit minus 1 that's it so you can see for the case of eight if you have eight then let's say you have one two you go up to four and then you go to eight so first you check for four now four square is actually greater than eight you look for the left half then you have number this so we can say one two three four now the middle element is let's say 2 the 2 square is 2 squared is 4 which is less right so look for the right so that is you look for only 3 and 4 but you already stored answer here the answer value is 2 now the mid square is 3 square which is greater than that so you just stop it there the recursion will get stopped not the recursion just the while loop will get stopped so the time complexity will be log of n because every time we uh reduce our domain or the range of input by half and the space complexity will be big of one because we are just storing variables let's do an ansi perfect thanks for watching this video please subscribe to my channel for the upcoming videos see you soon
Sqrt(x)
sqrtx
Given a non-negative integer `x`, return _the square root of_ `x` _rounded down to the nearest integer_. The returned integer should be **non-negative** as well. You **must not use** any built-in exponent function or operator. * For example, do not use `pow(x, 0.5)` in c++ or `x ** 0.5` in python. **Example 1:** **Input:** x = 4 **Output:** 2 **Explanation:** The square root of 4 is 2, so we return 2. **Example 2:** **Input:** x = 8 **Output:** 2 **Explanation:** The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned. **Constraints:** * `0 <= x <= 231 - 1`
Try exploring all integers. (Credits: @annujoshi) Use the sorted property of integers to reduced the search space. (Credits: @annujoshi)
Math,Binary Search
Easy
50,367
148
Loot Oil Welcome To Learn Repeat Today Bill Boxing Day Thirteen Update Change The Name Of The Problem Me Shot Latest Updates Login Problem Only Problem States Give The Head Of Liquids Return Delhi Starter Shopping Destination Digger Inform This Can Us For Telling List In Open Login Time and open memory is a subject was it has been provided with the earliest and to samples for telling class 10 english not regret and uses in this world and give the sorted out now i am shocked we are the uses of marks for teachers from his master and The can give one login time at 10 also login this sense pimples approach is but this tree is useless news18 approach and will give one piece brigade and login piece end of in login time in female cover dhawan page reach so lets technocrat example2 421 More Subscribe So Let's Check The 421302 Divide The Mid Point Of The Parts Of The Day Dividing A Pan From South Africa Fashion Show Basically Into Divider First Epistle To Find Them And Tried So Let's Say Medical To Get Midnight Shri Rampal Singh Two Hey And List In Inox List 16 Right Down List Sarfaz Let's Get The Mid Point Sode From This My Deposit In RK Judgment Is The Head Of The Right Most Part Right Surya The Head Of The Rebel Swift So Let's Have This Is My Short In Threat And This Is my node's and list node in the basis of Notre Dame flashlights is not soiled comment part and again call the short and will give me a short for the lift key and similarly salute for the white part super soft pad right text start with them And Sorry For The Life What Will Start With Head Panel Districts Of Clans What Will Happen In His First Time Dividing This Is The Mid Point And Dividing This Link List That Aapke Is Ras Indian Elections And Dividing This After Removing This Connection Between The End Elements Of the left most part and support element with right system limited by it is amazing hair same remove in this connection as well so fog clear force faith for 2 and 134 a tourist ok and again din will call record only after procedure for left and right 200 Again Will Tree To Find Them And Chairman Balbir Das's Beautiful Successful Point To Them And End University Part Right To Boss Again 10 Connection With Broken Down And Will Be Left With Part--24 Will Be Left With Part--24 Will Be Left With Part--24 This Morning Online With Sprite You To That We Can Us this element and white pleasure in which can check which means Greater Noida and formed during according to som rate that alcohol ten march on left and right and women are equal in the forest and check which means Greater Noida accordingly for telling light solution for this great Going to Sleep for Telling 10th 2.2 410 Left to Sleep for Telling 10th 2.2 410 Left to Sleep for Telling 10th 2.2 410 Left Most Parts Taken Care of OK Similar War Recessive Column 10 Man Ko Matri Exploitation Synthesis 30 Function Letter Foreign Minister OK Should Here It Will Have to List Thought Shot Also Its Life Present Shot Left Side Health Subcenter Temporary And right left can have attempted that and between bill check but I want to become a smaller and attempt by point to that smaller element wash nipple turn a smaller and smaller wrist take daina but umpire Dinesh Maurya made at feminine point this model school end Businesses to return time don't next who tempered with this particular slot 1234 ok khuda lut singh dhindsa and district so basically spoon dry ginger 6 two step obscene divide and other sources of vitamin D and sorry intake it's getting divide in the morning Dividing Africa Sunlight Se Of Log In Operation In The Morning Good Morning For All Elements And Operation Of Doing Log In Time In The Sky Itself In Log In A Time Complexity For Short Ok Software Doing A Division Respectively In The Divided They Can Visit Saturday Inspection Morning Meat Divide Sudhir and Two Yesterday Morning Rubber Stamp of Dividing Weight and the Second Step for Morning and Dividing Vansh Divide Vacancy in This Spot with Division Divine Virtues Develop Liquid Form Dividing in This Thought Exist Rate That Your Northern Parts in Trivandrum and Spiderman White Amazing Link List How They Find The Best All The Best Values For All Dual Gautam Basis Of Hair And What Is Approach White Dawood 642 Entry L'Liquid 22.81 Slow At The Time Of Annual Fest File 22.81 Slow At The Time Of Annual Fest File 22.81 Slow At The Time Of Annual Fest File First 5210 Dubai Journal 1.5 And Subscribe First 5210 Dubai Journal 1.5 And Subscribe First 5210 Dubai Journal 1.5 And Subscribe Remove They Should First Point To Who Is The current noose dot nik at that time first point will appear and at the same time snow point will move to this particular position ok dena and check the fast does not and dinesh elements is not educated channel motu next sweet will move to point here Which adds patient channel and the same time s loop control movie will share this point to so I bulbs current position will start from here.the principal da start from here.the principal da start from here.the principal da ghar ke members benefit jai hind jai maharashtra and finally on 10th select evening descending according will see How the Made and Yadav present Operation Bill Book not the best condition will be since falling short list developed take right for the left and right with your introduction to pain additional and dont national leaders in the written head no sense of just condition bound to get The put and dum and what should declare get me in third famous head that 501 atom and right som from a downwards plenty of beating them don't worry morning i left side effect and breaking the in between connection rate is so let's no difficult to unknown person's body Remove SIM Slot Matter For Self Ghrit Samaya Right From Wrong Words Ki And Dad I Can Simply March Left And Right And The Return Dashami Ki Sabzi Me Simple Model Online Payment The Great Indian Middle Head 2.5 Inch Le In-Between Loop Middle Head 2.5 Inch Le In-Between Loop Middle Head 2.5 Inch Le In-Between Loop Fast Food And to the villagers 209 slow will be apps lo who is equal to good night good initiative in all in that case and points lo to end me help point myself to be introduced and fast will be the fast mixed dot next to solve valuable items will know Point to the mid point night show the best person whole moon start with right notes with them and not require a i made you this slot next okay so what everyone else has value from mother mine in this whole thing which is nothing but the right sub list and idliyan Be Are Not Only Dividing But Voice Of Breaking The Connection Between To The Connection M6 Lottery Ticket Na Sula Debit The Connection Haridwar Se Padhare Wedding The List In To-Do List Servi Returning To Make Sure That Were Written The List In To-Do List Servi Returning To Make Sure That Were Written The List In To-Do List Servi Returning To Make Sure That Were Written Media Which Nothing But Head Of The List Of The Time Passing Year Alarm Set Bill With Head Of The Laptop List And With Us List Sonu Yadav Improvement And Get Married Life In The Dreamhouse Method Well Mash Ghr Temporary Is Right And The Bell's Petra To Stay Dynamic Distance From This Point To That's The Role Of The Subscribe Now To The List Of The Volume This Question This Lineage Notification All And It's Not Good Humor Very Challenging Character Point Absolutely No Beat Them Zara Play List Play To Find The total classified.in Play To Find The total classified.in Play To Find The total classified.in dot next equal to play list on what and want to two in treatments - 500 what and want to two in treatments - 500 what and want to two in treatments - 500 list are and now this water to two laxman dots are and now this water to two laxman dots are and now this water to two laxman dots next9 signinfreeman man tells pelican 210 returned next exact something in to-do list tools Listen To Share There to-do list tools Listen To Share There to-do list tools Listen To Share There Domestic To-Do List Do Domestic To-Do List Do Domestic To-Do List Do A Matter Of Industrial Control Student Next Mere Dil Ko Dean Student Welfare And Can Happen But If One Has More Element And List You Have More Element Site Record Swine Flu And Antill After Off List For All Students Not A Good But As Soon As One Of The National It Back Right Said That They Can See The Table Spoon In Us And Elements And Plants In The List Limit Side 100g Dashrath Elements And Directly Sign To The Telegraph Vinod Art 2064 Elements Which Can Directly Bless it will dot next that equal to swift playlist one is not equal to null in that case i first become scientist and say scientists to show share name section or buddha fun shot at least they can return the time set dot next flight development block tools list total so Will Return Attempt Dots Next Name Person Minute Fun Yes Of course Vihar Went To Meet The Division Part Between Getting Them And The Are Not Getting Comment But After Dividing Diet And The Bear Exists Hit The Hunt Operation Namo Sop And The Write The Code People On Diligence So let's share your answer of Radhe Ki according to Bigg Boss Vihar Terminal Pradesh SP Sudhir Pani has added 154 additional and don't have national then button Vatavriksha head down so let's stay in get again so the are getting back paper result Platform Add Us Dental College Chapter Member Post Speed ​​Mode 2 Hit The Like Chapter Member Post Speed ​​Mode 2 Hit The Like Chapter Member Post Speed ​​Mode 2 Hit The Like Button And Subscribe To This Channel Thank You
Sort List
sort-list
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the list is in the range `[0, 5 * 104]`. * `-105 <= Node.val <= 105` **Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
null
Linked List,Two Pointers,Divide and Conquer,Sorting,Merge Sort
Medium
21,75,147,1992
368
hello everyone welcome to date night 15th of november challenge and today's question is largest divisible subset in this question we are given an array of positive integers and we need to identify the largest subset as an answer such that each pair entry that exist in that subset satisfies this property either a modulus b is equal to 0 or b modulus a is equal to 0. if you sort that subset in increasing order then one after the other each one will be divisible with each other i'll tell about it more in the presentation so hold on without much to do let's look at the ppt that i have created for this and i'll walk you through the question as well as the solution in bpd itself largest divisible subset lead code 389 and let's take a very simple example here in this case we have four elements in our input data set one two three and six what is the possible solution with respect to this data set there are two possible solutions that exist first one is one two six and other one is one three six and it the answer could be any permutation of uh these three elements and any permutation of these three elements however once we sort both of them what do we get the elements in this fashion one two and six one three and six so what is interesting about this sorted answer the interesting thing is if you go pairwise each one will be divisible with each other for example the first pair is one comma two is divisible by one and as you progress ahead next pair is 2 comma 6 is divisible by 2 and it will progress so as we have more elements in our answer data set similarly the first pair is 1 comma 3 is divisible by 1 and as we progress ahead we have 6 comma 3 6 is divisible by 3 and there could be more elements depending on the size of our answer data set so this gives us a very interesting hint that we can use to come up with an approach which is longest increasing subsequence we have solved plenty of questions in the past on the basis of longest increasing subsequence problem and we'll be using the same technique to actually come up with an approach so without much to do let's talk about this approach as a default case what is what would be let's try and identify the length of the longest increasing subsequence that exists in this input array and we'll follow the same approach as we usually do in lis problems we'll take two pointers the first one starting from the zeroth index which is represented by j the other one for each element considered individually so let's point this as i and as a default case when we consider each element separately what is the length of the maximum possible largest size that could be formed it is one because you have you don't have any more elements you are only considering each element individualistically so let's start the iteration we are intending and finding out the length of the longest increasing sub sequence out of this given array right now the ith pointer is pointing to 2 and jth pointer is pointing at 1. let's check whether it meets a condition or not 2 modulus 1 is 0 that means the condition is met so what do we do in such cases we utilize the value that is set at the jth index and add 1 to it so what is the value set at the jth index it's 1 so 1 plus 1 gives us 2 so we go and update this with 2. let's proceed ahead and this time the is pointer moves to second index and let's start the iteration js pointer again moves from the zeroth index and here what do we see the current element is one the ith element is three it's again a matching case three modulus one is zero so we simply go and update the value at the second index to the value at the js index plus 1 which gives us 2 1 plus 1 gives us 2. let's proceed ahead and this time j is pointing at 1 is the condition met 3 modulus 2 divisible by 0 no the condition is not met we again proceed with j to a higher value and this time i and j becomes equal we are about the process let's proceed ahead next i comes at the third index and we see six here so let's start the iteration let me just change the color of pen and we have g are zero is the condition met 6 modulus 1 is it 0 the answer is yes so we'll utilize the value that is set as j and add 1 to it so we get 2 here let's proceed ahead and next we have is 2 is 6 divisible by 2 the answer is yes so we'll reutilize the value that is set at the dp of jth index the dp of the 8th index is 2 so we'll go and update it with 2 plus one which is three let's proceed ahead next we see is three so is three modulus a six modulus three is zero is it zero the answer is yes so we'll reutilize the value we'll update uh this with 2 plus 1 which is 3 so it won't make any difference the answer still says 3 so what is the updated state of the dp that we have filled in we have 1 here we have 2 here we have 3 here what is the largest entry that was found in the dp array the largest entry is 3 so that means the length of the longest increasing subsequence with respect to this input array is 3 i hope we are good so far now how is this three helping us in identifying the answer it's pretty simple and straight forward it's similar to narc problem how let's talk about it so we will go search for that index where this maximum value is occurring the maximum value is occurring at the third index and what is the value there is 6 that means this will be possible contender for our answer so we add 6 to our answer and we'll simply reduce the max value maximum value gets reduced by one and it gets updated to two we'll reduce the pointer as well so the next element that we foresee towards left is three and at three we have we see that the dp value is two so it's again a matching case since it's a matching case we will check whatever previous value we witnessed which was 6 and where the condition was met or finding the largest element whether that value is divisible by this current value or not you can see that value is divisible by the current value 6 modulus 3 is divisible that means this becomes part of our answer so we will simply go and add 6 to our answer data 3 to our answer data set and again we'll simply reduce the max value by one max value gets updated to one and let's proceed here towards left is the condition met what is the db value at two at this particular index it is 2 so this value doesn't sound equal to the max value we'll ignore this let's proceed ahead towards further left and what is the current dp value at this particular index the current dp value is 1 is this equal to the max value yes that it's equal so what do we simply go and check what was the previous last value that we saw that was matching the previous last value was 3 so 3 was the previous last value and is was it divisible is it divisible by 1 the answer is yes so we'll add 1 to it so one possible solution that turns out to be is 1 3 and 6. now someone may question that what about the other case one two and six how can we arrive at that particular solution let's reiterate the dp table once more we have one two three and six and what were the dp entries one two and three so let's start the iteration from the last entry and the maximum length of li that we found out was three so it's a matching case we fill in our answer data set with six and we will simply reduce the maximum length by one the maximum length gets updated to two and six gets added as our answer data set we move towards left and we by chance there could have been case where uh instead of the value 2 here we could have got some other value so for let's hypothetically forget that here we had to let's assume uh there was no two here so let's again progress towards uh the left most entry and what is the db value here the db value is two it's a matching case these two matches so we simply go and check what was the previous entry in our answer data set the answer data set has six is it divisible by two yes it is divisible by two we'll simply go and add two to our answer data set and reduce the max length value the max length gets reduced to one and let's further proceed towards left what do we see one and at one we the dp entry is again one so it's a matching case what was the previously uh last entry that was added in our answer data set it was 2. so we check whether 2 is divisible by 1 yes so we'll add it to an answer data set and it gets added the length gets reduced to 0. in this way we found out that 1 two and six does exist in an answer data set it was a matter of chance that we gave more priority uh to 136 by coincidence we were not aware that whether two will exist later in the iteration or not we greedily accepted the one that was giving us one possible solution so as the question said we are not interested in identifying all the possible solutions we are interested in identifying just one of them so we greedily pick one without much ado let's look at the coding section and i'll be walking through the different parts of code in exactly the same manner as i've done here i've defined a dp array of size nums.length and i have defined a nums.length and i have defined a nums.length and i have defined a construct lds helper method even before going on to the details of this helper method we are internally invoking get largest lds size which is giving us the length of the longest lds possible in this complete input array so let's walk through this helper method first in the first place i sorted this input array then i filled in the dpr with one and i initialized the maximum lds size or the ldsi helper variable as one because default would be that and let's start the iteration it's a typical lis approach that we usually do i started with i equals 1 up till nums dot length j starts from 0 up till j is less than i and i check whether the ith element is divisible by jth element if that is the case then i update my dp array to math.max of dp at the is index array to math.max of dp at the is index array to math.max of dp at the is index comma db of j plus 1 and i update my lds size variable to math.max ldsi command dp of i math.max ldsi command dp of i math.max ldsi command dp of i once we iterate through this complete two loops i return the lds size variable that gives us the maximum possible size of longest divisible subset let's now walk through the construct lds helper method it's pretty simple and straightforward and it's exactly doing the same thing as i talked about in the presentation so i have defined a previous uh variable which is -1 because we are uh variable which is -1 because we are uh variable which is -1 because we are going to fill the first element first i'm storing all the elements in the form of a linked list and i'll tell you the reason why i start the iteration in the reverse direction going from the last entry to the first one because we want to pick choose the one which is of higher amount while traversing back so let's check if my dp at the ith index is equal to lds size or and my previous happens to be equal to -1 if that is the case i go and add to -1 if that is the case i go and add to -1 if that is the case i go and add lds uh the current element in my lds answer set i reduce the value and assign the previous one to the current element that we have recently added for the next comparison to hartman and what is that comparison that the previous element is divisible by num at the its index we keep on going till the time the value of lds doesn't reduce to zero and that will only happen once we have iterated through the complete input array in the end i simply return the lds linked list that i have created why i am using linked list here because it supports add first method that adds the element at the zeroth index let's try this up accepted this brings me to the end of 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 being it have a great day and stay tuned for more updates from coding decoded i'll see you tomorrow with another fresh question but till then good bye
Largest Divisible Subset
largest-divisible-subset
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies: * `answer[i] % answer[j] == 0`, or * `answer[j] % answer[i] == 0` If there are multiple solutions, return any of them. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[1,2\] **Explanation:** \[1,3\] is also accepted. **Example 2:** **Input:** nums = \[1,2,4,8\] **Output:** \[1,2,4,8\] **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 2 * 109` * All the integers in `nums` are **unique**.
null
Array,Math,Dynamic Programming,Sorting
Medium
null
388
in this video we're going to be looking at this problem longest absolute file path so we're given a file system that stores both files and directories here's an example of that file system so you have dir then subdir1 file1.ext have dir then subdir1 file1.ext have dir then subdir1 file1.ext sub subdir1 subner2 sub subner2 and file2.ext file2.ext file2.ext and here is that in text form so you'll see that everything is on a new line and the level of the directory or file is the number of tab characters so this is that as a string slash n and slash t are the new line and tab characters so keep in mind these are individual characters every file and directory has a unique absolute path in the file system which is all the directories names concatenated with slashes and then the file name so the absolute path of file1.txext would be file1.txext would be file1.txext would be dur subdir1 file1.ext file1.ext file1.ext the absolute path of subsubter2 would be dir subter2 subsubdir2 and all the directories in this problem uh their names only consist of letters digits and or spaces whereas the file names will always be in the form name.extension like this name.extension like this name.extension like this so obviously this is not true in real file systems in real life but this problem is a simplification ultimately the goal is that given one of these strings representing the file system we want to return the longest absolute path to a file keep in mind this is not the longest absolute path to a directory we're only looking at files let's look at the examples so for the first one the longest absolute file path should be dur subdir2 file.ext so if you count the number of file.ext so if you count the number of file.ext so if you count the number of characters including the slashes it has length 20. for the second one we have two files file1.ext and file2.ext file1.ext and file2.ext file1.ext and file2.ext but file2.ext obviously has the longest but file2.ext obviously has the longest but file2.ext obviously has the longest absolute file path which is dur subdir2 slash sub sub32 file2.ext file2.ext file2.ext and this has length 32 and then for the last one so this kind of represents the kinds of edge cases where the file system only has directories and no files in which case we return zero okay let's break this question down from the string that's given obviously the first thing that we want to do is split it by newlines and then we would end up with something like this where every directory or file is on its own new line each preceded with tab characters now we can iterate through this file system line by line but how do we keep track of the current absolute path let's think about how we would iterate through this by hand so first we're then we go to subdir1 then we go to file1.ext then we go to file1.ext then we go to file1.ext and then when we go to sub subner1 we have to remove file1.ext have to remove file1.ext have to remove file1.ext and then add sub subner1 and then when we go to subdoor 2 we have to remove these two items and add subdir2 and then subsub 32 and the file2.ext and then subsub 32 and the file2.ext and then subsub 32 and the file2.ext at this point should be pretty clear that we are exactly describing a stack as we move deeper into the directory structure we push each subdirectory or file onto the stack and as we move out of each subdirectory we pop them from the stack the question is how many items do we pump so let's look at the example of when we go from sub 1 to subdir2 so at sub 1 the stack with three items there subter 1 and sub subner1 and at subject 2 we want to pop two items since we want to remove sub 1 and subdirt 1. so if you try some more examples you'll see that you'll want to pop sizeofstack minus currentlevel number of items from the stack where level is just the depth of the current directory or file it's essentially the number of tab characters proceeding let's add this to the pseudocode let's initialize the stack and then for each line if we're going deeper into the directory structure we're going to push the directory or file onto the stack and then otherwise we're going to pop as we said this number of items from the stack then if the line is a file well we're going to keep track of the current longest absolute file path so this is a great start but we actually come into a bit of a problem the thing is that we only care about the length of the longest absolute file path but right now in the stack we're keeping track of the file path itself so meaning the names of its directories and files the issue is at this line when we encounter a file we try to compute the length of its path we have to traverse through the entire stack summing up the lengths of each directory and then adding the additional lengths with the slashes let's try something slightly different in the stack instead of keeping track of the names of the directories or files let's keep track of the current file path length so far so let's see this in action and this will probably become more clear so one tidbit is we're going to initialize the stack with zero to indicate that starting from the root of the file system the length is zero let's also have a variable keeping track of the max length to a file so far once we get to dur instead of pushing dirt onto the stack we push three since that's the current length once we get the sub door one we first take a peek at the stack to get the length so far which is three then do three plus the length of subdue one which is three plus seven and then plus one since with every level we introduce a slash in the file path so we push three plus seven plus one which is 11. once we get to file1.ext we do the same once we get to file1.ext we do the same once we get to file1.ext we do the same thing so we peak the stack see that's 11 at the length of file 1. ext which is 9 then plus 1. so we're going to push 11 plus 9 plus 1 which equals 21. and since this is a file we keep track of this length so we update max to be 21. once we get to sub subter one well we're gonna have to pop from the stack but this time we're going to pop size of stack minus current level minus one so the minus one is because we initially initialized the stack with zero then we push 11 plus the length of subdur1 which is 10 then plus 1 which is 22 onto the stack so then once we get to subdirt 2 we pop two items from the stack and then we push three plus the length of sub two which is seven plus one which is eleven onto the stack once we get to sub subner two we push 11 plus the length of sub 2 which is 10 plus 1 which is 22 onto the stack once we get to file2.ext once we get to file2.ext once we get to file2.ext we push 22 plus length of file2.ext we push 22 plus length of file2.ext we push 22 plus length of file2.ext which is 9 plus one which is 32 onto the stack since this is a file we update max to be 32 and then finally we return max which is 32 and that's the correct answer let's update our pseudo code a little bit so we're going to initialize the stack with zero here and then instead of pushing the director or file into the stack let's instead push this value stack.peak stack.peak stack.peak plus the length of directory or file plus one onto the stack and then we're going to pop size of stack minus current level minus one items from stack and if line is a file we keep track of the current longest absolute file path so this looks fine okay great so we have a working solution let's look at the time complexity so we have a loop iterating through n lines pushing an item onto the stack is o1 popping is o1 but we're not popping one item we're popping size of stack minus current level minus one which is essentially on the order of the number of levels which can be arbitrarily deep so in our worst place we pop from an arbitrarily deep level to zero so our time complexity is going to be o of n times l where n is the number of lines and l is the maximum level depth we use space with the stack and the stack grows as we get deeper into the directory structure in the worst case the stack rose to the maximum level depth so the space complexity is ol okay now let's implement this in java start off with a stack then we're going to initially push 0 onto the stack and we're going to also have a variable keeping track of the max length so far and we're going to iterate through this input but we're also going to split it by that those new lines now the level is going to be the number of tabs so one way we can compute it is do last index of the tab character and then plus one then we're going to pop those items from the stack it's going to be wild levels less than stack dot size that's one stack upon now we're going to push the current length onto the stack so as we said the length is going to be we're going to peak and take the current length minus the level plus 1. so we're going to do s dot length minus level because if you think about it if we try to just push the length of the string it's also going to include those tab characters so we do need to subtract them from that calculation and we're going to push that onto the stack the way we're going to check if it's a file is that we're just going to check if the period exists in this string that contains period then we know that it's a file so that we're going to update the maximum length and at this point we're going to return the maximum length okay let's submit this great and you'll see that it passes and that's how you solve this problem longest absolute file path
Longest Absolute File Path
longest-absolute-file-path
Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture: Here, we have `dir` as the only directory in the root. `dir` contains two subdirectories, `subdir1` and `subdir2`. `subdir1` contains a file `file1.ext` and subdirectory `subsubdir1`. `subdir2` contains a subdirectory `subsubdir2`, which contains a file `file2.ext`. In text form, it looks like this (with ⟶ representing the tab character): dir ⟶ subdir1 ⟶ ⟶ file1.ext ⟶ ⟶ subsubdir1 ⟶ subdir2 ⟶ ⟶ subsubdir2 ⟶ ⟶ ⟶ file2.ext If we were to write this representation in code, it will look like this: `"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext "`. Note that the `'\n'` and `'\t'` are the new-line and tab characters. Every file and directory has a unique **absolute path** in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by `'/'s`. Using the above example, the **absolute path** to `file2.ext` is `"dir/subdir2/subsubdir2/file2.ext "`. Each directory name consists of letters, digits, and/or spaces. Each file name is of the form `name.extension`, where `name` and `extension` consist of letters, digits, and/or spaces. Given a string `input` representing the file system in the explained format, return _the length of the **longest absolute path** to a **file** in the abstracted file system_. If there is no file in the system, return `0`. **Note** that the testcases are generated such that the file system is valid and no file or directory name has length 0. **Example 1:** **Input:** input = "dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext " **Output:** 20 **Explanation:** We have only one file, and the absolute path is "dir/subdir2/file.ext " of length 20. **Example 2:** **Input:** input = "dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext " **Output:** 32 **Explanation:** We have two files: "dir/subdir1/file1.ext " of length 21 "dir/subdir2/subsubdir2/file2.ext " of length 32. We return 32 since it is the longest absolute path to a file. **Example 3:** **Input:** input = "a " **Output:** 0 **Explanation:** We do not have any files, just a single directory named "a ". **Constraints:** * `1 <= input.length <= 104` * `input` may contain lowercase or uppercase English letters, a new line character `'\n'`, a tab character `'\t'`, a dot `'.'`, a space `' '`, and digits. * All file and directory names have **positive** length.
null
String,Stack,Depth-First Search
Medium
null
187
Hello Hi Everyone Welcome To My Channel Today Vishal's Problem Repeated DNA Sequence Sold In Is Composed Of A Series Of Nucleotides Every Son CET For Example A CGTTCE Web Streaming DLNA Mitti Sometime Useful To Identify Repeat Sequences With Tel Function To Find All The Channel Subscribe Indian molecule for example subscribe and subscribe the letter sequences and 181 others like this candy crush off switch off but also let this is the worst thing is formed with this CGT characters in the at all the possible like starting from here.the possible like starting from here.the possible like starting from here.the time During and latest ringtone from one to 1100 21000 tenth wicket all subscribe key basic of the subscribe person that updates of string and will be taking up this will increment account plus other wise will continue to deal with account in this live with great all the frequency of All the sub strings of passion from distic head from death will pick put do subscription death in the frequency grade one hour is to one hour is to one hour is to hair is the code implementation of the approach explain just suffers death system app created during this time later skin hair Cutting All The Subscribe From Wearing His Client 10 Likes Decide So I'll Get Destroyed Loop - The Video then subscribe to the Page Send This Five Line Of Food Which Can Also Write In One Line Using Java Apps Peene Par So This Is And Hair Soft Created and decided in Ubuntu from this cream and after that all the best ringtone all entries from main entry set between frequency like person written in the map tours and collected all the giver list subscribe like this is the solution we need to check justin bieber Accounting also role frequency business needs to check weather the sequence like it servi gas so let's move with string of 1000 cc interference rather edison has one set between is not same set thursday decide which will be repeated-repeated subscribe and repeated-repeated subscribe and repeated-repeated subscribe and subscribe the Channel and subscribe this Video is not servi for all Dual is so let's implemented solution is 42% is so let's implemented solution is 42% is so let's implemented solution is 42% solution first is looted call the scene in Amla from is set up that hindi setting set is later call repeated in this worthy place this is wealth from that nobody will treat all The Magic York New 8 - Northern Region At All The Serving Of 8 - Northern Region At All The Serving Of 8 - Northern Region At All The Serving Of 70 Plus No Will Cut First Tasting Labs King A Visual Vs Dot String Of Islands Of Two That I Plus Time When Will Check If Scene Contains Lots Of String Till Arab Skin Already Brainwashed This Point to the key repeated set else will always keep adding to the scene on 220 This is the case will get her so she will be updated and will return the list of weights reduce by repeated on 210 Shetty implementation let's compile code and addya compiler my can Not find a simple typo scene repeated notice a c n letters in thoughts and specific btc not know d j i saudi shutbox networking sites of medicated that i have tractor pet so what is the time complexity of dissolution and you can see the Drawing for full length of verses in the hair for creating subscribe in a reader of complexity channel subscribe secure maximum different subscribe and subscribe the Channel thanks for watching
Repeated DNA Sequences
repeated-dna-sequences
The **DNA sequence** is composed of a series of nucleotides abbreviated as `'A'`, `'C'`, `'G'`, and `'T'`. * For example, `"ACGAATTCCG "` is a **DNA sequence**. When studying **DNA**, it is useful to identify repeated sequences within the DNA. Given a string `s` that represents a **DNA sequence**, return all the **`10`\-letter-long** sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in **any order**. **Example 1:** **Input:** s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" **Output:** \["AAAAACCCCC","CCCCCAAAAA"\] **Example 2:** **Input:** s = "AAAAAAAAAAAAA" **Output:** \["AAAAAAAAAA"\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'A'`, `'C'`, `'G'`, or `'T'`.
null
Hash Table,String,Bit Manipulation,Sliding Window,Rolling Hash,Hash Function
Medium
null
783
uh this question is a minimum difference between PST nodes so you're given a root of a PSD and then return the minimum difference between the value of any two different nodes in the tree so basically like you can Traverse the tree and then uh get your current now and then subtract by the previous node and then this will be the solution so how do you sort the tree I mean so sort the PST tree you are going to use in order traversal in order so if you know it's actually good to know then basically you are your time you try this to left then you try this to the right so uh like this the idea is like this right but what we need is we need to keep track of the previous node so actually no three right and now I need to know the minimum difference so in I'm going to call result so I'm going to initialize 3 equal to now uh result able to watch digital Max and now we're just calling order follow root and when I return and it will return the result right so um what I need is what uh and this is reverse all the way to the left in the tree then I need to make sure if the tree is not equal to no right then I would definitely know like I need to obtain my results right so it's going to be a lot of the current value minus the previous value okay and once I um uh once I take I mean once I know I'm not the first note right so if I'm one right I don't have a previous note right but if I'm at two I know my previous note is one right because the immortal traversal uh sorry I know you know the traverses go all the way to a lab and then go back to the period and go all the way to the right so once I know I'm in a parent of this one I need to know I need to update this to my previous right all right so I'll just say previous and this is pretty much it right so uh if the previous that's not equal to now you update the current value for result just run it so let's talk about the time in space this is a space so I would say it's constant this is a time right the time is actually all the same uh it's actually the number of notes in the tree and this is a pretty much a Time complexity so there's no other uh there's no other time complexity in this function so uh this is a solution so I'll see you next time bye
Minimum Distance Between BST Nodes
search-in-a-binary-search-tree
Given the `root` of a Binary Search Tree (BST), return _the minimum difference between the values of any two different nodes in the tree_. **Example 1:** **Input:** root = \[4,2,6,1,3\] **Output:** 1 **Example 2:** **Input:** root = \[1,0,48,null,null,12,49\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 100]`. * `0 <= Node.val <= 105` **Note:** This question is the same as 530: [https://leetcode.com/problems/minimum-absolute-difference-in-bst/](https://leetcode.com/problems/minimum-absolute-difference-in-bst/)
null
Tree,Binary Search Tree,Binary Tree
Easy
270,784
162
everyone it's Orkin welcome to my Channel today we are gonna solve a lead code 162 find Peak element problem so the problem statement is that we are given an input array and we need to find a peak element and return that Peak element in case if we have multiple Peaks we can return any pick um another important requirement is that the algorithm must run in log n time complexity uh so what's the peak element Peak element is the element that is more than its neighbors for example in the example one we have um three which is the peak element because it's more than two and the one it's neighbors so we can return it as a peak element the same way um in the example two we have six which is uh which is the peak element because it's more than five and the more than four and we need to return not the element but we need to return the index of the element and return its index okay uh so that's the problem let's see how we are gonna solve it um let's take example of one two three and one our first example and let's uh let's work on it so um by requirement we need to solve this problem with the log n time complexity and right away we can say that okay uh login time complexity we need to use a binary search here to find our uh to find our Peak element so what we need to do first we need to Mark left and right for the binary search um so our first element would be our left and our last element would be our right so let's do that in the iteration in the first iteration what we do we are finding a mid element which is equals to 2 and we are comparing the element that comes after it so basically whatever element comes after the mid we are comparing if it's more than our mid element then we are searching our uh for our Peak on the right side of our array in this case yes the three is more than two so we are selecting this part and the searching for our uh searching for our Peak element on the right side so in the second iteration so we are moving our left here and we are searching for our pick element on the right side in the second iteration what we do is we are our mid element is three so we are comparing if the element that comes uh the next element after our mid if it's more than three then we are searching on the second part for our um pick in this case it's not so we are selecting uh three as our Peak element and we are returning left as a result because it's the index of our Peak element okay let's actually take a look at the one more Corner case let's say that we don't have this um we don't have this example but we have something like one two uh two three uh four five something like this so in this case uh if we are gonna so in the first iteration we also move our left to the uh to the three but the hour in the as you can see here our array in the second part is just to keep increasing so how we can make sure that we are selecting our uh or on the right side we are going to find the peak element because it's just keep increasing well in that case we are marking five as a peak element because uh the in this case 5 has only one neighbor four and it's more than its neighbor and in this case we are marking as a peak element so that's how we are going to solve this problem yeah let's uh let's put our um this algorithm to code okay uh first thing that we need to do we need to Define our left uh is equals to zero because we are starting from the beginning of the array and we need to Define our right which is the end uh last element in the array so for that we are taking our length minus one okay so the net next thing that we need to do we need to while our left is less than our right so what we need to do we need to find first the mid element let's call it mid and left plus um right minus left divided by 2 so that's how we are finding our mid element and we are checking if our um nums uh mid element uh is if our next element that come after the mid if it's more than our mid element so meet a plus one if it's more than our mid element then we are searching for the our pick on the um on the right side of the array so for that we need to move our left pointer so our left is equals to Mid plus one okay so if not then we are searching for the uh our Peak element on the left side of the array for that we need to move our right pointer right is equals to Mid okay uh that's it um once we exit this Loop we have the you know we have our pick so for that we need to return uh our index so we are returning uh left uh we are returning index not the element itself because that's the requirement um that's it let's check our code okay it works as expected uh so let's go over the code one more time first we are defining left and right pointers then we are moving our left and right pointers until we find our Peak element for that we are defining a mid element and if our mid plus one the element that comes after the mid is more than our mid element then our we are moving our searching for the um pick element on the right side of the array the for that reason we are moving left otherwise we are searching for the Peak on the left side of the array and we are moving our right and at the end we are returning the index of the element that is the peak so that's it um hope you like my content if you like it please hit the like button and the Subscribe my channel that's it for today see you next time bye
Find Peak Element
find-peak-element
A peak element is an element that is strictly greater than its neighbors. Given a **0-indexed** integer array `nums`, find a peak element, and return its index. If the array contains multiple peaks, return the index to **any of the peaks**. You may imagine that `nums[-1] = nums[n] = -∞`. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in `O(log n)` time. **Example 1:** **Input:** nums = \[1,2,3,1\] **Output:** 2 **Explanation:** 3 is a peak element and your function should return the index number 2. **Example 2:** **Input:** nums = \[1,2,1,3,5,6,4\] **Output:** 5 **Explanation:** Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. **Constraints:** * `1 <= nums.length <= 1000` * `-231 <= nums[i] <= 231 - 1` * `nums[i] != nums[i + 1]` for all valid `i`.
null
Array,Binary Search
Medium
882,2047,2273,2316
401
Soon hello guys normal tell me their video line and liquid problem description And subscribe The Amazing hai kuch nahin soch raha hoon nine mostly ko Meghnad teri tarf and video arrow button like share subscribe 0nline Adhir Veerwati subscribe must subscribe channel Must listen, according to the blossom on the mango trees, on the important awards, lust, darkness, and maximum, 10 loot, subscribe, so that give this 100, today is Tuesday 2104, who is the appointment of Sirvi, the minimum is 200, hey brother, the maximum. Come to Lavai Shyam, reduce that Ravan, say something, the structure is at maximum, the boys Sudhir and the robbers should be subscribed to the maximum, do not forget to subscribe my channel, that Shivlinga demand, if you speak, your husband, Robert, you commit suicide, 609 construction, more than 100 quantity of salt, subscribe to that Ministry of External Affairs appointed on this number 12 that on Friday morning Pawan Dev Ji will take the road Swad 153 acting Purna Vaas Timed Kaboul Switch on the first number Kyun Loota Accused No. 90 Subscribe now He will start acting here and there Turn on the number one playlist to my channel number, make your own number one impatient person click the subscribe button on the side and subscribe my channel like and subscribe to loot jaane loot first for u The first formal mist and are wow last seeervi seervi subscribe do that in the number four hai fuel maang ki hai ok was so impressed upon it's very difficult to decide the 63.51 hai difficult to decide the 63.51 hai difficult to decide the 63.51 hai hua tha loot and dynasty chicken teaching be the richest person Half hour of crocodiles etc constipation and inside number school the said number of which keeping our personality business stuffed idli batter subscribe button maximum retail in is more that the said number 90 number one side someone young seervi subscribe to a New version of condition is voter who can get but when this 15 Avinash Dutt Mandir person must come subscribe with a single digit and went daily and do not forget to subscribe on Thursday and subscribe to soon ok WhatsApp Twitter Solid Waste Plant Money Problem Interview Subscribe Please subscribe this channel that a hua hai
Binary Watch
binary-watch
A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. * For example, the below binary watch reads `"4:51 "`. Given an integer `turnedOn` which represents the number of LEDs that are currently on (ignoring the PM), return _all possible times the watch could represent_. You may return the answer in **any order**. The hour must not contain a leading zero. * For example, `"01:00 "` is not valid. It should be `"1:00 "`. The minute must be consist of two digits and may contain a leading zero. * For example, `"10:2 "` is not valid. It should be `"10:02 "`. **Example 1:** **Input:** turnedOn = 1 **Output:** \["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"\] **Example 2:** **Input:** turnedOn = 9 **Output:** \[\] **Constraints:** * `0 <= turnedOn <= 10`
Simplify by seeking for solutions that involve comparing bit counts. Consider calculating all possible times for comparison purposes.
Backtracking,Bit Manipulation
Easy
17,191
1,752
hey guys how's everything going this is jayster in this video i'm going to solve another problem from lead code uh it's a one seven five three two check if array is sorted and rotated given an array nums return true if the array was originally soared in a non-decreasing soared in a non-decreasing soared in a non-decreasing non-decreasing order non-decreasing order non-decreasing order then the rotated then rotated some number position including zero otherwise return false there might be duplicates in your original array i see so because it's non-decreasing right so because it's non-decreasing right so because it's non-decreasing right okay an array a rotated by x position results in array b of the same length such as a i equals b i plus x mod by a to l where my module operation it's like three four five one two is this is original solid array and then rotate it by x three zero one two three rotate it by here hold it back here uh zx means i a i equals b i uh so 0 means nothing is changed right for multiply length so z okay wait a minute so a move actually is means okay a i equals i move left right move left for uh i uh for uh some positions like okay so one move forward we'll move backward for one position for two position for three position so three one two is here uh three four five is here great so let's do it so for the original array it's uh non-decreasing we could just check uh non-decreasing we could just check uh non-decreasing we could just check the item from uh with the previous one right see to see is if it is uh smarter than it if it is smarter then it's a downward slope so like we have an array and we find a position to rotate it so it will be split it into two parts a b and c d right and then it be become c d and a and b this is the uh arguments we get so there are several conditions we need to uh find it map being matched it means c is not decreasing to d and a not decreasing to b and b is smaller or equal to c right so yeah this is it so how do we uh find this and find this uh it means that uh we the d a is smaller than d am i equal to d yeah so these kind of downward slope like turning point their maximum should be one right it's only one or zero because if it is zero positions then the array is totally the same as the original one so yeah so the uh the condition here actually could be uh summarizing to one the turning point is maximum one if has turning point and b is must be not decreasing comparing to c right yeah so this is it let's do it uh we loop through the numbers we compare it with previous ones so actually we start from uh one in x1 if num oh and we can keep track of the uh turning point uh like what is it let turning points zero okay if i is smaller atoms numbs i negative one it's not decreasing equalness is okay uh we increment the turning points count and if there are over two turning points then we could just return right away it's not rotated okay and then at last we return that there if there's no turning points right or if there's one turning point and the last one is comparing to the first number it should not be non-decreasing number it should not be non-decreasing number it should not be non-decreasing it should be non-decreasing it should be non-decreasing it should be non-decreasing it should be no it should be non-decreasing yeah no it should be non-decreasing yeah no it should be non-decreasing yeah it should be yeah not decreasing uh returns nums uh nums.nth nums uh nums.nth nums uh nums.nth negative one it should be smaller or equal to nums zero right so this is it let's run the code looks great submit yeah passed so that's it's pretty simple uh but actually i failed for the first time uh yeah i need to pay more attention especially for the zero uh zero positions stuff okay so this is it helps you next time bye
Check if Array Is Sorted and Rotated
arithmetic-subarrays
Given an array `nums`, return `true` _if the array was originally sorted in non-decreasing order, then rotated **some** number of positions (including zero)_. Otherwise, return `false`. There may be **duplicates** in the original array. **Note:** An array `A` rotated by `x` positions results in an array `B` of the same length such that `A[i] == B[(i+x) % A.length]`, where `%` is the modulo operation. **Example 1:** **Input:** nums = \[3,4,5,1,2\] **Output:** true **Explanation:** \[1,2,3,4,5\] is the original sorted array. You can rotate the array by x = 3 positions to begin on the the element of value 3: \[3,4,5,1,2\]. **Example 2:** **Input:** nums = \[2,1,3,4\] **Output:** false **Explanation:** There is no sorted array once rotated that can make nums. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** true **Explanation:** \[1,2,3\] is the original sorted array. You can rotate the array by x = 0 positions (i.e. no rotation) to make nums. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arithmetic. For each query, get the corresponding set of numbers which will be the sub-array represented by the query, sort it, and check if the result sequence is arithmetic.
Array,Sorting
Medium
413,1626
301
and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 301 remove invalid parentheses given a string s that contains parentheses and letters remove the minimum number of invalid parentheses to make the input string valid return all possible results you may return the answer in any order let's look at an example say we're given this input here what would be our solution here well let's count the number of parentheses so for the left we have one two three left parenthesis for the right we have one two three four so obviously there's a mismatch between the left and the right parentheses so obviously we can't get rid of left parentheses because then we'll just have even left less left and we'd still have the same amount of right so clearly the right parentheses are the ones that we need to remove so as we can see there's this one right parenthesis which is oops let me change my color here so you can actually see this and we'll use green so there's this one right parenthesis which is invalid because it doesn't have a corresponding left parenthesis so we could remove it and then we'd get this as one answer so this would be closed so this is one potential answer or what we could do is we could remove one of the left that comes before it so for example we could remove um let's see one of these left ones or sorry one of these right ones we don't necessarily have to remove this right one it could be one of the ones earlier so we could remove this one and we'd get you know left and then the two rights right and then closed and that would be a valid answer and obviously in this case we've removed just one parentheses from both of these right in the first case we removed this one here this first one and then in the second one i believe we removed this one so in both those cases we just removed one obviously we could just remove every single parentheses but we're looking for the minimum number we need to remove so obviously that's not a good answer because we'll just end up removing everything so the way that we're going to solve this is actually using a backtracking dfs and what we're going to do is we're going to start at the beginning of the string and we're going to go to the left oh sorry to the from left to right and what we're going to do is that every iteration we're going to make a decision of whether or not we want to take the current parentheses or leave it those are our two options right we can either take the current parentheses or we can ignore it if it's going to be invalid so you know with other parentheses problems that we've done before we know that okay if you know the left count is actually less than the right count or equal to it then that means that we're not allowed to take any right parentheses because that would be invalid and there's no possible left parentheses that could close a right parenthesis if we took it if this statement is true so we can do some sort of validation as we go to basically make sure that our right parentheses don't ever exceed the left parenthesis before it so we can make sure that when we get to a right parenthesis we can do that check and that means that we'll need to keep track of our left parentheses count and our right parentheses count as we're going we don't know when we see a left parenthesis whether or not we're going to see a right parenthesis later that can close it so we're going to take all left parentheses greedily and we're also going to ignore it in the case that you weren't allowed to take it because we're not going to be able to go back and remove things we're simply going to evaluate once we get to the end of the string does the left count equal to the right count if it does then that means that we have found a valid parenthesis and we can double check whether that answer works so as we go from left to right we're going to build our strings using a string builder and you know in a backtracking manner and what we're going to do when we get to the end we're going to say okay does left equal right if it does then we want to look at the length of our string right we want the minimum number of parentheses removed so we're looking for the longest possible string at the end such that left equals right because if we the longer it is that means that we removed less items so if our new string let's say its length is five if that equals to the maximum length that we've seen so far for an answer then we can add it to our answer add to answer right if actually 5 is greater than our answer that we found so far then that means that everything in our last answer was invalid and we need to reset our answer to be whatever this new length is five and then just add that string to it so this is a little bit confusing i think once we go to the code editor you'll see exactly what i mean and we'll walk by everything line by line this question really isn't that complicated i think it's just a mishmash of backtracking plus knowing how to work with parentheses if this is confusing go watch some of my other videos and this should explain how to work with parentheses i've done a lot of questions before this one is really no different it just has that backtracking element to it so enough blabbing let's go to the code editor and we're going to type this up it's actually really not that bad and let's solve this question we're in the code editor let's type this up let me give us a little bit of extra room here because we don't actually care about the question prompt we just want to see the code so we need a few variables to help us with our solution like i mentioned we need to keep track of the longest string that we found so far that works as an answer and we also need to find our um you know our solution set so we're going to say self.longest string and we're to say self.longest string and we're to say self.longest string and we're just going to set this equal to -1 this just going to set this equal to -1 this just going to set this equal to -1 this is going to be our initial value and we're going to need some sort of result here and we're going to set this equal to a set um because we want the unique results we don't want to have duplicates in our results and we don't really care about the order so uh we can use a set here to basically take care of any duplicates now remember that we need to do a backtracking dfs so let's set that up and we're going to call our dfs function and we'll write this in a second but basically we're going to pass in the string s we're going to pass in the current index of our string remember that we're going over the string from left to right so we need to keep track of where we are we need to keep track of our current solution which is just going to be a string builder so we're going to pass in an empty list because obviously we don't have any answer yet and remember that we need to keep track of the left and right count for the parentheses so those are going to both be 0 because we haven't done any processing and we're going to call the dfs function with those initial arguments and at the end all we need to do is return self.res self.res self.res so sounds easy but now it's actually time to write the dfs function so let's define the function arguments and we just talked about them so the first argument is obviously going to be the string that we're working with second argument is going to be the current index the third argument is going to the current result which is going to represent the string builder of uh the result that we're building as we go through the backtracking and then we have our left count and we also have our right count so those are going to be our function arguments now obviously this is a backtracking dfs and we don't want our recursion to go on forever it has to end at some point so what is the endpoint is actually going to be when our current index is greater than or equal to the length of the string because that means that we have exhausted all the possible indices of our string so at this point we need to evaluate whether or not we actually have a solution so we're going to say if current index is greater than or equal to the length of the string now what we need to do is check whether or not our solution is valid and because we're going to be validating whether or not we're taking a correct left or right parenthesis as we go at the end all we need to do is check whether the left count equals the right count because that means that we will have removed invalid parentheses as we've gone through our solution and you'll see how we do that in a second this is really just building out the solution so we're going to say if the left count is equal to the right count what we want to do now is check whether or not we have a better solution remember that we're looking for the minimum that we have to remove right remove the minimum number of invalid parentheses right we could just literally remove all the parentheses and that would technically be a valid string but that's not the minimum remove so we want to make sure that our answer is actually the best answer that we can get and the way that we're going to do this is we're going to check whether or not our current result its length is actually longer than the best answer that we have so far because that means that we actually removed less parentheses and that where therefore we have a better answer so our previous answer is no longer valid so we need to actually overwrite it so we're going to now say if the length of the current result is actually greater than self.longest is actually greater than self.longest is actually greater than self.longest string so now we have a better answer we need to set our new longest string to be the length of whatever the current result is and we need to reset our result right so whatever result we had before is no longer valid because we now have a better solution so we're going to reset the result to an empty set and we're going to add to it our new result which is this current res but obviously it's a string builder so we actually need to join it together so we're going to say string.join and we're going to add the string.join and we're going to add the string.join and we're going to add the current result so that's the case where the current result is actually greater than our best result so far we could also have the case that our current result is equal to the best result that we have so far which means that we simply need to add our string to this result set because it's another valid answer so what we're going to do is we're going to say else if the length of the current result is equal to self the longest string now what we want to do is we just want to add the answer to it so we're going to say self.res.ad to say self.res.ad to say self.res.ad and then we're going to join our stringbuilder here to get our string because remember we're returning the actual string not the string builder so we're going to say join keras and that's how we basically uh take care of the case when we process the entire string otherwise if we haven't processed the entire string then we actually need to do our processing so let's get whatever the current value is at the current index so we're going to say the current character is going to be string of cur index so remember that there's three values it can take right our string can contain parentheses and letters if it's a letter we don't do anything we just take them and we continue we can't not take the letters we just ignore them and we just add them to the string builder and move on we only want to you know make a decision of whether to take or not to take in the case that we don't have in the case that we have a left or right parenthesis strings characters always get taken so we're going to say if the current character is actually a left parenthesis we don't know whether or not the left parentheses will ever be closed after it so we can't not take it because it could be the case that we needed it but we could actually accidentally take it so what we're going to do is we're going to have two things we do here right we're going to take the current character and we're also not going to take it so we're gonna do two backtracking one where we take it and one where we don't take it so let's do the one where we take it first so we're gonna say currentres.pend currentres.pend currentres.pend so we're gonna add it to our stringbuilder so we're gonna add the current character and then we're gonna go into our back tracking so we're going to call self.dfs it's our string our to call self.dfs it's our string our to call self.dfs it's our string our current index obviously we're going to move the index up by one our current result now we've taken a left parenthesis so we need to increment our left count oops left count by one and we need to keep our right count the same obviously it stays the same and now once that finishes we'll exit from the back tracking and remember that typical backtracking since we added it to our result we now need to remove itself oops not this isn't itself this should be pop yeah cares.pop yeah cares.pop yeah cares.pop so that's the case where we're taking it and then we also need to go through the backtracking where we actually ignore this current left parenthesis so we're not going to add anything to our stringbuilder because obviously we're ignoring it so we're simply just going to call the backtracking function with our string we're going to move the in we're going to move the index up by i index up by one we're going to pass in the current result oops current res oh geez i can't type today l count hasn't changed because we're ignoring the left parenthesis and obviously right count hasn't changed because we're not even working with the right parentheses so there's no reason it should have cool so that's the case where we have a left parenthesis what about the case where we have a right parenthesis so we now have a right parenthesis and remember that there's two cases again we can either ignore the right parenthesis or we can take it so let's do the case where we ignore it first because it's simpler so we're going to say self.dfs so string all we're going say self.dfs so string all we're going say self.dfs so string all we're going to do is move the current index up by one and we're going to pass in current res we're going to pass an l count and right count easy peasy now when it comes to taking a right parenthesis remember that we can't take right parentheses greedily because if we have something like this or is it going to autofill so if we have something like this right this is a balanced parenthesis right these two lefts are closed by these two rights but if we see another right now we can't take this parenthesis because it doesn't matter what comes after it we could have you know one million left parentheses they will never close this one right that came before it right lefts can only close a right parenthesis that comes after it so if this parentheses on the right is invalid then we can't take it because nothing will ever close it that right parenthesis needs to be closed by a left that comes before it so what we need to do is we need to check that the left count is currently greater than the right count because if it isn't that means that right parenthesis will never be closed and we can't take it so we need to make sure that left count is strictly greater than the right count otherwise it won't work so if we have the case where we can take the right parentheses we can basically do the same thing with the left that we did except for this time what's going to be with the right so we're going to say current res thought append we're going to take the current char we're going to say self.dfs we're going to say self.dfs we're going to say self.dfs string obviously the current index moves up by one we're going to pass in the current res left count stays the same except this time the right count gets incremented by one once that dfs finishes then we can say currentres.pop finishes then we can say currentres.pop finishes then we can say currentres.pop so we're going to pop from that and we're good to go cool so that's the case where we have the right parentheses so we've handled the left and the right and now i'll remember that we can have like english letters in here and in that case we just need to take it add it to the string builder and continue moving on so we have to take all of our uh right and all of our letters so what we're going to do is we're just going to say kerres.pen whatever the going to say kerres.pen whatever the going to say kerres.pen whatever the current character is uh we're going to say self.dfs we're uh we're going to say self.dfs we're uh we're going to say self.dfs we're going to go past the string in obviously we're going to pass curindex plus one uh plus one we're gonna say kurez obviously and then left count hasn't changed and right count hasn't changed and once we exit added this dfs all we need to do is remember this is a backtracking so we need to get rid of it so we simply say cares dot pop so that is what we do there and actually i don't think we even need this karez.pop because we always keep this karez.pop because we always keep this karez.pop because we always keep the letters so we can actually just leave that out uh there we go so let me just run this make sure i haven't made any bugs because it's quite a lot of code and i can catch it now okay let me submit it and hopefully this works and this is a long one um because there's a lot of test cases oh okay so i think we actually do need that uh kerrez.pop to actually do need that uh kerrez.pop to actually do need that uh kerrez.pop to make the backtracking correct so let me just add that back in and okay cool yeah okay nevermind it turns out we didn't need that all right uh anyway so that is how you solve this problem let us think about the time and space complexity so obviously this is a backtracking question and most backtracking questions are exponential uh run times right and the x the base for our exponential runtime is going to depend on how many things we can possibly do at each iteration of the backtracking so let's think about the worst case scenario here which is that our string that we're given is all left parentheses so the reason that this is the worst case is that because when we have something that's all left parentheses every single time we go into the backtracking we're always going to take the left parenthesis and we're always going to ignore it which means that there's two things that we could potentially do right if it's all right parentheses then we have you know one for sure that we do and then potentially two but we're not guaranteed to go into this block here so you know at a minimum we would do one same with if it was just all english characters it would just be one thing that we do each time but with left parentheses we always take it and we always ignore it which means that there's two things we can do each time and obviously there's n characters in our um string so that means that we have two to the n basically um operations so our time complexity here is going to be two to the n so our space complexity here is going to be big o of n and the reason for this is well we need to store our um you know our solution which you know could potentially just be the string that we're given if the string there's actually no characters that we need to remove then we're just going to end up storing the string in our result and then also each backtracking will finish you know itself before actually going to the next one so that depth is going to be big o of n because there's only n iterations we could possibly do so that is your time and space complexity for this algorithm just going over it again it's two to the n for the time because there's in the worst case our string is all left parentheses and we would have to do two operations at each of the n you know iterations through our back tracking so that's why it's two to the n and then for the space we have big o of n so that is how you solve this question not exactly the most complicated one is quite a lot of code to write and you know handling some of these cases can be a bit tricky but if you've seen you know your back tracking questions before it's really not that bad i think it's pretty straightforward uh how you actually solve this one you just have to have done a few parentheses ones and just be familiar with backtracking but otherwise like even if you haven't seen it before like this solution is pretty easy to memorize i haven't done this question in you know forever when was the last time i touched it in what is this like november and i it's what is it june now and i basically have it memorized so uh yeah this one's not really that hard anyway i'm gonna stop blabbering that's how you solve this problem lee code 301 remove invalid parentheses if you enjoyed this video please leave a like and a comment it really helps with the youtube algorithm if you want to see more content like this please subscribe to the channel i have a ton of videos already uploaded and i plan to make a whole lot more so subscribe to the channel and also leave in the comment section below what questions you want to see and i will add them to my work queue otherwise thank you so much for taking the time to watch this video have a great rest of your day
Remove Invalid Parentheses
remove-invalid-parentheses
Given a string `s` that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid. Return _a list of **unique strings** that are valid with the minimum number of removals_. You may return the answer in **any order**. **Example 1:** **Input:** s = "()())() " **Output:** \[ "(())() ", "()()() "\] **Example 2:** **Input:** s = "(a)())() " **Output:** \[ "(a())() ", "(a)()() "\] **Example 3:** **Input:** s = ")( " **Output:** \[ " "\] **Constraints:** * `1 <= s.length <= 25` * `s` consists of lowercase English letters and parentheses `'('` and `')'`. * There will be at most `20` parentheses in `s`.
Since we don't know which of the brackets can possibly be removed, we try out all the options! We can use recursion to try out all possibilities for the given expression. For each of the brackets, we have 2 options: We keep the bracket and add it to the expression that we are building on the fly during recursion. OR, we can discard the bracket and move on. The one thing all these valid expressions have in common is that they will all be of the same length i.e. as compared to the original expression, all of these expressions will have the same number of characters removed. Can we somehow find the number of misplaced parentheses and use it in our solution? For every left parenthesis, we should have a corresponding right parenthesis. We can make use of two counters which keep track of misplaced left and right parenthesis and in one iteration we can find out these two values. 0 1 2 3 4 5 6 7 ( ) ) ) ( ( ( ) i = 0, left = 1, right = 0 i = 1, left = 0, right = 0 i = 2, left = 0, right = 1 i = 3, left = 0, right = 2 i = 4, left = 1, right = 2 i = 5, left = 2, right = 2 i = 6, left = 3, right = 2 i = 7, left = 2, right = 2 We have 2 misplaced left and 2 misplaced right parentheses. We found out that the exact number of left and right parenthesis that has to be removed to get a valid expression. So, e.g. in a 1000 parentheses string, if there are 2 misplaced left and 2 misplaced right parentheses, after we are done discarding 2 left and 2 right parentheses, we will have only one option per remaining character in the expression i.e. to consider them. We can't discard them.
String,Backtracking,Breadth-First Search
Hard
20,2095
639
welcome to july's lee code challenge this problem is called decode ways 2. a message containing letters from a to z can be encoded into numbers using the following mapping a is 1 b is 2 z is 26. to decode an encoded message all the digits must be grouped together uh or grouped then mapped back into letters using the reverse of the mapping above so aajf with a grouping of one ten six and kjf with eleven ten six so notice how this string here can be mapped two different ways so in addition to the mapping above an encoded message may contain a uh what is this a star character which can represent any digit from one to nine zero is excluded so that's nice because zero would overcome complicated even more but for example if we had one star this could be represented by one two one three all the way to 1 9 so that means whatever you want whatever we have to figure out how many ways we can decode this okay so there's a decode ways problem one which is a pretty classic problem which i found very complicated but i basically went with that approach and you can see this was my solution and i did eventually get it to work um it took a lot of submissions and a lot of edge cases i had to take care of but after i finished solving it i realized i had no idea what i'm doing like this is not something i could really explain so that was a terrible approach don't do what i did this is not a good idea let's look at some of my code though and see if we can figure out some insights and then i'll go through a solution that i thought was the most clever um so one of the things we realize here is if it's a star um we basically have to take our number of waves that we decoded in our dp array so say that we had like uh one star something like that uh how many ways can we decode one here we already know that's going to be one right now what about here at the very least there's gonna be nine ways we can decode that so we have to multiply however many ways we decoded here with at least nine so that would be one times nine so this would be nine but keep in mind we also need to think about well what about the ways that we can decode to like 11 12 13 like those are all extra ways that we can decode so because of that uh depending on whether this is a one or a two we have to uh if it's a one we have to add another um basically multiply nine times however many ways we decoded when it was a one here so that's still a one so this would just be nine times one here but if this was a nine times one like this but this was a two that'd be different because we don't have nine ways we can do that we can't do we can't code 29 but we can encode 26 here as well as like two six right two and six like this so how many ways are there is up to twenty one twenty two twenty three twenty four twenty five six so if this was a two uh this would be actually six there'd be six ways now things get even more complicated if there's like an extra star here if there was an extra star uh we have to actually keep track of both those two ways because we know one and two are both possible so not only do we have to multiply whatever value we had here this would be what 15 we have to multiply that by nine but now we have to also multiply um the nine ways that we had right there so we have to do what 15 times 9 and then we also have to add i think it's going to be 15 times 9 plus 15 times 6 i believe right and i put that somewhere here i believe it's something like this and notice how in this dpoa we're looking back two spaces and the reason for that is like at this point here uh just imagine that we have like i don't know some values two three uh once we get to like one if we i don't know what these values are here but once we get like let's say this was a hundred um and now we have nine we know we have to multiply this by 900 but we also want to know okay how many ways were there to decode here okay because we have nine other ways to decode from this point so we have to add plus nine whatever this value is here so that's kind of like two states we have if this character is a one or a two we need to keep track of that previous one in case next time it's a star so if when that happens we have to keep track of that so that's kind of the key insight that i want to kind of dig in but otherwise i realize my the way i'm going to solve this right now isn't going to make much sense but i think if i want to really go deep into this just take too long so what we'll do is we'll just go with first creating a dp array okay and this dp array is going to contain three things the first thing is going to be the number of ways that we could decode uh regardless of whether it was a one or two okay so the previous dp value essentially so very first we'll start with one now these two values here are going to represent uh we're going to store one thing previous in case this character is a one or a two so this second position if the last character was a one we're gonna keep track of whatever the previous dp was in case we see a star and we want to figure out hey was the previous one and one if it was we need to also multiply that and same thing here that's going to be representing a 2. it's going to be 1 this will be a 2. i'll show you what i mean so we'll say 4c in string there's going to be two main cases that we have to take care of first i'm going to create a temporary dp array here and if c equals star we're going to let's see set a couple things here so in the beginning this would be what we'll start with 000. so temp zero at this point we will take our dp of zero and we'll multiply it by nine we'll also take our dp of 1 and add that and we have to also multiply that by 9 and take our dp of 2 right here and i think we have to multiply this by six okay now temp one this since this is a star that means a one and two are both possible so we just need to store these two here in case the next one comes up now otherwise uh this is where it gets complicated let's see so temp kind of doing the same thing at this point but we will uh take our dp of zero but we need to see if our character is um basically we need to make sure it's not a zero here if it's a zero it kind of changes things up we if it's a zero we have to only take the values here with one and two because remember if this value is a zero uh if we had like one zero like if the previous value was a nine or seven this wouldn't be possible we have to assume that one and two came before that otherwise there's nothing to add here so that's why we have these two states so what we'll say is c is greater than we can just use character 0 like this and we multiply that so as long as it's greater than 0 it's going to be 1 so we'll multiply that by dp 0. let's see and also we'll need to like the previous dp of one right here that as well as uh dp of two that is if the character is less or equal to six okay so c has to be less or equal to six here and we multiply that okay so now temp one this as long as c is equal to one then we'll just multiply that by t p of zero right here and temp two if character is equal to two then we'll multiply that by dp of zero i guess so this isn't really like multiplying it really it's just uh if it's not a one it's going to be zero if it's a one then we store it if it's a two we store it so that's really all it is and make sure to now make dp equal to temp and actually uh i think in order to get this to pass we have to do a modular here so seven and i guess we can say i mod for i n tip so that's going to be our new dp now finally once we get out here we just return our dp and the first value so um i hope i got this let's see if this works okay um i'm going to put in a couple test cases here see if i missed anything up okay it looks like it's working so it's going to submit it and there we go all right so this is much cleaner clearly and it's going to be a of n time complexity and of one space it's constant space because this would be just this and that so this is the best solution that i saw um you can certainly go my approach and do all those crazy efl statements you know it actually seemed to work a little bit faster but ultimately i hated the approach because i started to lose track of exactly what i was doing but this works i don't fully understand it i'll admit but um yeah hopefully you get the decent idea and you can start you know playing around with it yourself so okay thanks for watching my channel remember do not trust me i know nothing
Decode Ways II
decode-ways-ii
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into: * `"AAJF "` with the grouping `(1 1 10 6)` * `"KJF "` with the grouping `(11 10 6)` Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`. **In addition** to the mapping above, an encoded message may contain the `'*'` character, which can represent any digit from `'1'` to `'9'` (`'0'` is excluded). For example, the encoded message `"1* "` may represent any of the encoded messages `"11 "`, `"12 "`, `"13 "`, `"14 "`, `"15 "`, `"16 "`, `"17 "`, `"18 "`, or `"19 "`. Decoding `"1* "` is equivalent to decoding **any** of the encoded messages it can represent. Given a string `s` consisting of digits and `'*'` characters, return _the **number** of ways to **decode** it_. Since the answer may be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "\* " **Output:** 9 **Explanation:** The encoded message can represent any of the encoded messages "1 ", "2 ", "3 ", "4 ", "5 ", "6 ", "7 ", "8 ", or "9 ". Each of these can be decoded to the strings "A ", "B ", "C ", "D ", "E ", "F ", "G ", "H ", and "I " respectively. Hence, there are a total of 9 ways to decode "\* ". **Example 2:** **Input:** s = "1\* " **Output:** 18 **Explanation:** The encoded message can represent any of the encoded messages "11 ", "12 ", "13 ", "14 ", "15 ", "16 ", "17 ", "18 ", or "19 ". Each of these encoded messages have 2 ways to be decoded (e.g. "11 " can be decoded to "AA " or "K "). Hence, there are a total of 9 \* 2 = 18 ways to decode "1\* ". **Example 3:** **Input:** s = "2\* " **Output:** 15 **Explanation:** The encoded message can represent any of the encoded messages "21 ", "22 ", "23 ", "24 ", "25 ", "26 ", "27 ", "28 ", or "29 ". "21 ", "22 ", "23 ", "24 ", "25 ", and "26 " have 2 ways of being decoded, but "27 ", "28 ", and "29 " only have 1 way. Hence, there are a total of (6 \* 2) + (3 \* 1) = 12 + 3 = 15 ways to decode "2\* ". **Constraints:** * `1 <= s.length <= 105` * `s[i]` is a digit or `'*'`.
null
String,Dynamic Programming
Hard
91,2091,2251
630
hey everybody this is larry this is day 23 of the leeco day challenge hit the like button to subscribe on drum and discord let me know what you think about today's problem i have gotten comments recently about my mic being too low um i'm checking the levels and it does seem a little low i don't know what to make of it but um yeah let me know what you think in the comments whether the sound level is good enough i always find it okay but i always also max to the sound whenever i listen to stuff which is maybe a bad habit so let me know anyway today's prom is 630 course schedule three okay so the end courses from one to n you're given courses duration and last day that i of course could be and must finish the last day okay the maximum number of courses that i can take uh oh god so this is a hard problem or i mean like it's classified as hard um already i so one is i feel like i really have some idea about this but i don't remember how to do it so you know it's move um the second thing is that i have a feeling it's greedy but i think this is why i don't really like the current format of you know these weekly themed things is that you know i kind of have already have like a preconceived notion of how to solve it um only just because i know that it is uh heap week or maybe greedy week depending how you want to phrase it and as a result i'm like yeah you know maybe it's just that right like where i would much rather go into it without any bias of like hey it's a fresh problem it can be anything right so i think that makes it slightly easier and a little bit because i think this is a problem especially as i mentioned you know in previous in the previous days greedy is one of my weaknesses and i appreciate any effort to kind of practice greedy but mostly because of the proofs i would have to at least in my head there are ways about it but that's what i think right so okay so with all that being said let's think about this um so the last day that we can so are these sorted in any way so they're not sorted um the couple of ideas that i have and maybe they're related anyway my first idea is some sort of binary search i know i just said all that stuff about uh keep i mean maybe but there is a similar structure there so maybe there's something like that where for every if i sort this by the last day right the input if i sort it by the last day then i'm thinking that okay if for example just given a slice of time um if the last day is 1300 how many things can i fit in right and in that case we would um i think in that case we would try to really choose all the smaller classes or um or the smaller courses that could fit into 1300 right and what i mean by that is that in a greedy kind of way let's say we're given 1300 uh right then that means that we will only be able to fit one hundred and two hundred because inside the 300 units of time and it'll finish by then um and from that on basically doing variant there is just going from left to right from the number of time so i thought it may be binary search in that way but actually you just keep on building on right and as you so you the way that i think about it even though we spoiler alert we are going to use heap some of this because of how we talked about it but i think actually i think about this as a scanline algorithm right or sweep line algorithm if you will and my idea here is okay let me do some minor drawings because people always complain that i don't do enough drawing uh but also because i like i want to draw because uh because if it doesn't make sense to draw i'm not going to draw it just to whatever but basically for example hmm is that where i can just copy and paste this because these are just numbers let's see if that works nope cannot paste it um so basically the idea is this right so let's say we have a number line right this is why okay this is a okay i could just use a straight line too but right and then the question is okay uh i don't want to draw all the input but you could kind of see that i'll just talk about the input and then we'll see right let me actually move this a little bit so i could see it on my screen um okay so for example you're given for your friends you're given the last day being 200 and it takes 100 day uh so this is let's call it uh okay this is d for duration and the other one is d for last day no that's terrible larry uh let's just say l and d right and you have another event and i'm sorting them you know before you so you know on the last day so let's say the next one is 1250 and then 1000 1300 200 and then 3200 2000 right so these are just that's basically the example one that i'm doing the idea here for me is that okay so you know we put these numbers on the number line let's just say this is here-ish just say this is here-ish just say this is here-ish this is very hand you know but uh something like that right say um okay so then the idea is that going from oops going from left to right i can't even draw a straight line okay straighter um going from left to right let's say 200 right well now we know that we used a hundred of these right in terms of unit let's say we go to a thousand well now we use a thousand um oops what the hell what happened here i think maybe i have a bun home why is it so weird okay uh anyway sorry friends technical difficulties so 100 and a thousand roughly speaking right um and then now so that now we can do both events before 1250 and now we look at 1300 we could do 200 does that fit actually no yeah actually it fits exactly actually something like magnetic interference or something i think so weird okay actually this is a wait is that true maybe i did the math well one hundred one thousand thirteen hundred right so why is oh well two thousand is the one that doesn't fit okay and then now we have 2000 and obviously it doesn't fit so this is actually a terrible example sorry friends but let me just rewrite some of these real quick um but the idea that i wanted to convey was this is a terrible example but let's say we have something like this right let's say this is the first box this is the second capacity because in a greedy kind of way you always want to take it near the beginning and then now let's say in the dirt box it's re it's too long well what happens well now we know that we cannot fit three classes right so let's say we get rid of one well which one do you want to get rid of in a greedy way you always want to get rid of the most expensive class in terms of time so it'll be this one but let's say you know and if of course if it was like this if this is really long and this is just a little bit more then of course you get rid of the middle one right so this is greedy in a way and of course that's greedy and part of that greedy is yeah so that's the greedy part of it and part of the greedy implementation is what you're doing what are you asking all the time and what you're asking all the time is get remove the max element and what happens when you want to remove the max element use a heap to get the max element every time or repeatedly right so that's basically the idea and then it becomes bookkeeping after that um and what i mean by bookkeeping is just keeping track of numbers and so forth and we'll see in a second so if you're if i'm a little bit unclear well we'll be okay alrighty so yeah so first we sort courses by um by the finish time so that we can go from left to right as we said and then now we just do for what was it a duration and last day in courses uh of course we have to set up our heap and here we again just like yesterday we want the max heap right because we only repeatedly get the max number so let's also the way that i think i like to do it this way a little bit better but you feel free to do whatever you like at home um and the way that i said this yesterday and i feel like i've said this something a few times today or this week rather um the way the reason is because in python it's a min heap in a lot of languages you actually get a maxi by default but in python it's a min heap so then to get the max we just take a negative of every popular possible number uh input um and then you know return it and keep it consistent which is why i have some abstraction here because then now i don't have to worry about it later on or if it's typo i can fix it in one place instead of many places so okay so then now we also want to keep track the total and this is just the sum of all the numbers that are in the heap which are all the courses we took uh and maybe our best thing um to just keep track of best in case we need it i think this but i think this is monotonically increasing so i cuz so the two things my one thing i want to say is that especially if i'm on a competitive you know like a contest i sometimes do things that i do things in a way that i don't have to prove uh meaning that in this case every time i add a thing it should be monotonically increasing because at the worst case you will just get rid of the course that you just got and then you have the same amount of courses as before so in that case we actually don't have to but i would say like but i would also like if i was in a competition i would maybe like i'll be like oh i don't want to prove that i would just have to do something like this after everything and even though this is my time like this h should be monotonically increasing i would just keep it like this because then i don't have to worry about you know i don't have to worry about anything really right like i just know that in a way it is like a brute force and that i check it every time so i don't have to worry about it but in this case we actually don't need to do it because everything in the heap will be the classes we take so we should be good um and here we go okay let's um let's sign let's try to sign up for this class right so then total we sign up for the duration uh heap we push d yeah and then now we go okay is total greater than uh the last day right because if this is if the total is greater than last day that means that your current set of classes will go past the last day so that's no bueno and then you pop and of course some someone in the comments will be like oh this can actually be an if statement because of the invariant that we set so but yeah i'm okay you know it's fine i like my get a while because then here we can prove that the invariant is true afterwards if i do something here um then i know that the invariant is true and it just again i think i said this yesterday as well just fewer things to prove right um but yeah i think that's oh and here while we pop we remove that from the total obviously otherwise it would just be an infinite loop let me give it a quick spin and then see how that goes uh yeah maximum number of courses right oh i think i made the same mistake yesterday heap syntax in python is just very awkward but yeah okay that's pretty much hopefully that's the idea let's give it some minute of oh i got one as a choice last time hopefully this time i don't yes who why did i get one into twice last time 814 day streak uh yeah so if you want to look at complexity this is actually straightforward for space we only have h and h is of course um uh what i was going to say this is just of n right and because we have a sword this is o n log n but after that this will be also o of n log n right i suppose because this thing can have n elements um so yeah so n log n time and like oh sorry linear space is the idea behind this one um that's pretty much what i have i'm going to take a look in the past larry to see why he got the wrong answer oh it seems like i did the same i don't know why just as well but i did do this thing that i was talking yesterday uh even but i guess i'm doing factor into i think i made this i think the mystic that's here is the same mistake that i'm oh i did it by duration i did greedy by duration does that work i don't know that works so maybe that's what's wrong did i is that the fixed data and then i sorted again but by the other direction i did i tried to greedy by the other direction and then at the way and i sorted by the finishing time which is what i did today and then it worked but it also has some of the stuff that we talk about just best human though it should be monotonically increasing but like i said fewer proofs so it's but that also comes to wow it took me 17 minutes after the first two long and so i was very bad last time i ran on this but this time i feel like i did a bit better so thank you uh especially since most of it was explanation but also show i just want to point out though like it's very easy to make greedy mistakes as you can see from last year maybe not this year you want to see those mistakes check it out and see how i can um improve on it but you know past larry i beat you one more time but though sometimes i don't and then i get sad anyway uh that's all i have for today let me know what you think stay good stay healthy take good mental health and i'll see y'all soon bye
Course Schedule III
course-schedule-iii
There are `n` different online courses numbered from `1` to `n`. You are given an array `courses` where `courses[i] = [durationi, lastDayi]` indicate that the `ith` course should be taken **continuously** for `durationi` days and must be finished before or on `lastDayi`. You will start on the `1st` day and you cannot take two or more courses simultaneously. Return _the maximum number of courses that you can take_. **Example 1:** **Input:** courses = \[\[100,200\],\[200,1300\],\[1000,1250\],\[2000,3200\]\] **Output:** 3 Explanation: There are totally 4 courses, but you can take 3 courses at most: First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day. Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date. **Example 2:** **Input:** courses = \[\[1,2\]\] **Output:** 1 **Example 3:** **Input:** courses = \[\[3,2\],\[4,3\]\] **Output:** 0 **Constraints:** * `1 <= courses.length <= 104` * `1 <= durationi, lastDayi <= 104`
During iteration, say I want to add the current course, currentTotalTime being total time of all courses taken till now, but adding the current course might exceed my deadline or it doesn’t. 1. If it doesn’t, then I have added one new course. Increment the currentTotalTime with duration of current course. 2. If it exceeds deadline, I can swap current course with current courses that has biggest duration. * No harm done and I might have just reduced the currentTotalTime, right? * What preprocessing do I need to do on my course processing order so that this swap is always legal?
Array,Greedy,Heap (Priority Queue)
Hard
207,210,2176
151
hey friends welcome to the new episode of Kult was just and today we're going to do lead code number 151 reverse words English training if the input is the sky is blue and alpha will be blue is sky and we can see the edge cases includes the leading and trailing spaces and we need to delete all the actual spaces in between two words so before use this as example the result will be world so my approach is to reverse the stray and it will look like this and as we go through the list we reverse each word and escape this spaces so I have left pointer in the right pointer if the left pointer is pointing to an empty space we move both pointers forward like so if we see the left pointer is pointing to a non empty character then we move the right pointer until the red pointer hits in space that means that we have a valid word so we reverse the word and put it to our result string after that we set the left pointer to the right pointers position and we check full of spaces again and again the left pointer riched to a non space character then we move the right pointer until it hits a space then we reverse the string after that we set the left pointer to the right pointer and keep moving towards the end of the stream and that's how we get the result however if we have this case and when the right pointer is pointing to the last character of the string our loop ends so that makes us will have to check after the iteration and see if we reaching this scenario then we'll have to do the reverse again now let's code this problem so before everything I will check if the input is valid if the string is null or it doesn't have anything we return itself otherwise let me create a stream motor to hold our result and I'll have these two pointers pointing to the beginning of the string next step we're going to reverse the string we will need a river string method after that we iterate through each character off the string was well loop we check if the left pointer is pointing to empty space if so we'll move both left and right pointer otherwise it means that the left pointer is not pointing to a space so we just need to check if the right pointer is pointing to the empty space if it's not then we move the right pointer otherwise that means the left pointer is not pointing to an empty space but the right pointer is pointing to a empty space like so that means we have a complete word and we want to reverse it and put it in to our result don't forget to space then remove the left pointer to the right pointers position so after this iteration we need to check one more edge case that's when the left is pointing to a valid character and the right pointer is pointing to the end of the word that means we also need to reverse this word so we check if left is less than right you know so left pointer is not pointing to a space then we do this again now we're ready to return the result so if the string voters length is greater than one because it's also possible with that we have empty string like this if we have an empty string like this our string builder will look like empty string so if the string builder is length is greater than one then we return string builder to string but we need to exclude the last empty space that we added otherwise we return an empty now that we just need to write this reverse string method give it a string I converted into a character array and also used a left pointer in the right pointer but left pointer pointing to the beginning of the string and the right pointer pointing to the end of the string then we move the left pointer in the right pointer towards the center and switch the characters on the left position in the right position and after that weight return a new string was the reversed character array let's take a look at it from the top we get an input as a string we check if it's null or if has a valid length then we'll create a string builder to hold our results a left pointer in the right pointer and then we reverse the input string while right pointer is less than the string length we check the left pointer first to see if it's pointing to a space if it is then we move both left and the right pointer otherwise that means the left pointer is pointing to a valid character then we check the right pointer if it's also pointing to a valid character then we'll move the right pointer otherwise that means the left pointer is pointing to a valid character but the right pointer is pointing to an empty space in that case we reverse the word back and appended to our result then we move our left pointer to the right pointers position now when the right pointer is pointing to the very end of the string we check if the left pointer is less than right pointer and the left pointer is pointing to a valid character that means we need to do this append operation again with the reversed word by the end we check if the string builders length is greater than 1 if it is then we return the substring dot to string and remove the last empty space otherwise we return empty string so for this reverse stream method we have a string as input we convert it to a character array we have the left pointer pointing to the beginning of the string the right pointer pointing to the end of the string and while left is less than right we switch those two characters and move the pointers by the end we return the new strand was the reversed character array I'm sure we'll have a mistake here for this case the left pointer needs to pointing to a non empty space that means we have a valid word now let's run it okay this test case is valid let's try some more edge cases add some more empty spaces in between the words and also passes and what if I only have empty spaces that also works let me try a test case with trailing spaces it also worked let's submit it okay so since we're going through the string twice to reverse it and reverse it back the time complexity would be O two times n which is o N and that's it see you next time
Reverse Words in a String
reverse-words-in-a-string
Given an input string `s`, reverse the order of the **words**. A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by at least one space. Return _a string of the words in reverse order concatenated by a single space._ **Note** that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. **Example 1:** **Input:** s = "the sky is blue " **Output:** "blue is sky the " **Example 2:** **Input:** s = " hello world " **Output:** "world hello " **Explanation:** Your reversed string should not contain leading or trailing spaces. **Example 3:** **Input:** s = "a good example " **Output:** "example good a " **Explanation:** You need to reduce multiple spaces between two words to a single space in the reversed string. **Constraints:** * `1 <= s.length <= 104` * `s` contains English letters (upper-case and lower-case), digits, and spaces `' '`. * There is **at least one** word in `s`. **Follow-up:** If the string data type is mutable in your language, can you solve it **in-place** with `O(1)` extra space?
null
Two Pointers,String
Medium
186
221
all right let's talk about the maximum square so you're given an unbiased matrix so you have to return the largest square containing only one so you have to return the area so this question is supposed to be easy so um you are given a matrix like this so basically just create another matrix the same size is going to be um right and then if you see the one you consider one right um then you just what then you have to check uh the neighbor on what so if you see that one right over here if you see a one right over here right you have to check your neighbor so when i say neighbor this is going to be your top left and i mean top left and top left right so basically find out the minimum between this square so we already know these cells is already one right so we don't care about it so we have to find out the cells uh cells around me right so if the minimum is zero from these three right one two three right if this one is zero right then uh this is not a square right but what if the minimum of this of the square is one the minimum between the three spots is one then i know this one is supposed to be a square right so i would just update my uh my metric for this cell to two because i'm in this location right and so on right then just keep going on the bottom line right so uh this is uh there's the base case for i equal to zero and j equals zero so i put the zero represent what the rule and then j equals zero percent column right so again now we cannot actually find a square for i equals zero and j equals zero so we basically just append a value one zero to the uh to the new metric and one on one to the new metric so this is supposed to be the idea like for the i equal to zero and j equal to zero right and i know like this is a string right uh this is a chart right so i have to convert to the integer inside my 2d array and basically this is pretty much it for the best case then later on i will just have to traverse my current cell so my current cell is going to be like this so this is my current cell right so i will say okay for this one if this is one then i will have to traverse my square but this is zero right so i don't care what now i'm not at this one right this one is one so i traverse my neighbor so my neighbor is what the minimum of the neighbor is zero so i don't care about it i don't update so this is supposed to be what uh suppose uh the default value one right and then again then i would just keep moving on the uh on the rest of the column and reverse of the rolling columns so this is pretty much it right so let me start doing this so in an equal to matrix so this is a rolling high and i need to have a return value i'm going to call result this is going to be a length and at the end i will have to find out the area so the area of the squares is resource square right resultant result so now i traverse the square all right so if i equal to zero this is my new query right so i would say i j equal to what character dot uh what else get numerate value so i will say matrix ij right and like just for example like this is what the one resource is actually uh the area right so i can i have to update my results max.max result over 3 i j right all right so now this is the basic for the i 0 and j to 0 so i continue i know what if the i is not equal to zero or j is not equal to zero right i have to make sure i j is actually equal to one so if this is a one i could check my neighbor and i already know like my d uh my degree sorry my query ij since the current cell is one right so i have to say one plus and then the minimum between my neighbor so again so as i create the grid right and then by default it's actually zero right so i mean just for example this is zero right this is one zero one and by default this is supposed to be zero right but i know the metric and this cell is one right so i have to add one for uh for the cells which is already one so one plus a neighbor so the neighbor is this so the minimum between this is actually zero so one plus zero is actually one so this is it right so um this is going be three i minus one j minus one this is gonna be my top left and then three i j minus one this is gonna be my left right three i minus one okay this is my top right all right so after what i need to update my what my maximum value for the results right and this is supposed to be the solution so let me run it uh right so i have a mistake for the first piece what else oh sorry so uh in java you cannot have multiple value for the mean you can only have two so i would say i will have to have another math i mean and then this is it right so hopefully i don't need another typo all right so let me submit uh let's talk about the time and space all the time uh this is the time right to follow so it's going to be m times n all right well space is going to be the m times m as well so this is a solution and i was using this time
Maximal Square
maximal-square
Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square containing only_ `1`'s _and return its area_. **Example 1:** **Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ", "1 "\],\[ "1 ", "0 ", "0 ", "1 ", "0 "\]\] **Output:** 4 **Example 2:** **Input:** matrix = \[\[ "0 ", "1 "\],\[ "1 ", "0 "\]\] **Output:** 1 **Example 3:** **Input:** matrix = \[\[ "0 "\]\] **Output:** 0 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 300` * `matrix[i][j]` is `'0'` or `'1'`.
null
Array,Dynamic Programming,Matrix
Medium
85,769,1312,2200
67
Jai hind this video clip year digit code number 6 7 4 dictionary 2012 - ring return visam also this 2012 - ring return visam also this 2012 - ring return visam also this resting in posting and sense nine marks lead character 0512 subscribe video number two main one plus one two three and find to march 2018 live 1000 jawan superintendent how To Study From The Right Side Undeclare Variables And He Call To Take Tel Last Length Of This Data Length -1.2 Tel Last Length Of This Data Length -1.2 Tel Last Length Of This Data Length -1.2 World Class Loot Digit From Being This Example Jai Ho Om Ki And Faster Dry This Point Is Equally Gallant Of This Complete Singh - Book Point To Gallant Of This Complete Singh - Book Point To Gallant Of This Complete Singh - Book Point To That Was So They Decided To Reduce Collector Orders From This Character 24 Carat Against A This Amazing Aerial Act Flash Lights Jaipur To Bidders Length - Flash Lights Jaipur To Bidders Length - Flash Lights Jaipur To Bidders Length - Top Born Commander Objective To Lines On Which Theorem Per Tenth Westphal 111 A Variable Time 7 Minutes Swami Ko D0 Darshan Test Live Webcasting This Article 243 Ki Garlic Medicine Lo Paaye Is Greater Than Or Equal 10 Far From Andhra And Juice Kar Dena Record Biology Mobile During Fasting More Last Digit Subscribe To Seek Digit From This Now This Don't Care It Last Pinpoint Thursday Poem after reading Eye - 0 Poem after reading Eye - 0 Poem after reading Eye - 0 That on this technique to convert into individual soul will forget all SIM liquid form The last digit copy and economic plight Neil Let's Uday Singh loose if it is a greater than or equal to zero 2.1 Mon Possible To Date Craft zero 2.1 Mon Possible To Date Craft zero 2.1 Mon Possible To Date Craft Videos J Jo Person Sahi R Ajay Ko How To Hard Reset Udhar Bet Results Point Ricardo A Sanam 80 Mode Of Two Six Class 10th Result Adnan Sami Code To Mumbai To Red A Reminder Are Common Next 9 News Se Vinnie Degree Is The Value of by - manus and also given - - 9 Value of by - manus and also given - - 9 Value of by - manus and also given - - 9 how to hide your line vijendra a great sub plus 2 this - - 2 this - - 2 this - - that this - - and reduced to live for others on i that this - - and reduced to live for others on i that this - - and reduced to live for others on i finally got vijay kumar condition containing porn content value from his paternal record Battery 1008 To The Same Thing Like Result Some Research On I Finally Can Return With A 's Darshan Code On Resources Let's MP Ranbir Singh Bisht To Examples Yes That Akhilesh Kumawat It's Clear 2 Do Training Of Choice 12367 Code Of Platform Ad There is a recent version 17.82 Percentage of Violence a recent version 17.82 Percentage of Violence a recent version 17.82 Percentage of Violence Mission 10 Year 2009 Sir Verification Code part of which Language Presence Sir Pesh Till and that Global Anniversary Changer Share Price A Girl in This Country The Property Snow Damaged The Research of Some Balance Capsule It has Change Summary For the d s well yes string like fight on small ki decision clear vidmate user can reduce and several years by his intellect and use this a is scrub rocket and similarly e f and this vowel hua hai do hai coffee batting set proposal liquid lets Radhe has happened that as long as the loot was submitted the structures will remain 4 lessons for 94.20 to structures will remain 4 lessons for 94.20 to structures will remain 4 lessons for 94.20 to 0.5 inch video will solve different 0.5 inch video will solve different 0.5 inch video will solve different problem
Add Binary
add-binary
Given two binary strings `a` and `b`, return _their sum as a binary string_. **Example 1:** **Input:** a = "11", b = "1" **Output:** "100" **Example 2:** **Input:** a = "1010", b = "1011" **Output:** "10101" **Constraints:** * `1 <= a.length, b.length <= 104` * `a` and `b` consist only of `'0'` or `'1'` characters. * Each string does not contain leading zeros except for the zero itself.
null
Math,String,Bit Manipulation,Simulation
Easy
2,43,66,1031
115
we're going to take a look at a legal problem called distinct sub sequences so given two strings s and t return the number of distinct subsequence of s which equals t so a string subsequence is a new string formed from the original string by deleting some can be none of characters without disrupting the remaining characters relative or positions so you can see here we have an example right where uh let's say we have a c e is a subsequence of a b c d e because you can see a is come before c and c has come before e so in this case the subsequence is the same relative order as this original string right but the thing is that aec is not a subsequence of this because you can see here that a is come before e that's correct but c should not come after e right in this case you can see here e is comes after c but c should not come after e so in this case this is not a subsequence of this right so we must subsequence must uh follow the same relative positions as uh from the original string right so here you can see we have our s and we have our t right so in this case we have our s string and t string so in this case the output is three because there are three ways you can generate t from s right so in this case one subsequence from s could be this and a b here right r b and b i t r a b and b i t right so in this case another example would be r a b i t right another example would be r a b and i t right so you can see here we can generate three separate combination uh three separate subsequence from s that equal to t right so you can see that basically this is how we solve outward in this case this is basically what we want to output is a number that represents how many distinct subsequence in s that equals t so let's take a look at the constraints so the constraints here is you can see here that uh s length of s and length of t is between 1 to 1 000 and then s and t should consist of english letters so let's take a look at a couple of base cases here so let's say we have a situation where s is equal to empty string right and t is equal to an empty string as well so what's the output look like so the output is actually going to be one because you can see here an empty string is a subsequence in s and that subsequence is equal to t so therefore the output is one now however though let's say if s is equal to a and then t is equal to empty string we still output is equal to one right because you can see here that empty string is also a subsequence in s and that subsequence is equal to t so therefore the output is one now let's say if s is equal to an empty string but t is equal to a then the output is going to be zero right because you can see here that there is no subsequence in s that equal to t so therefore the output is zero so let's take a look at another example right so let's say we have two strains here a b and a b forget about how many distinct subsequence we can find in s that have that's equal to b let's take a look at how we can be able to find one subsequence in s that is equal to b right so you can see here what we can do is that we can basically have our pointer points to the last character in s and have another pointer point to the last character in t we're going to have our pointers go from the back to the front you can also go from the front to the back but basically you can see here we're basically comparing two characters right in this case that s at the last character in this case the current character in s and current character in t they do equal each other so we do is we move our pointer right so in this case we move our pointer one to the left and then we also move one of our pointers and t one to the left to compare to see if they're the same right in this case they are not the same so what we do is we basically move our pointer one to the left right for our t string in this case you can see this is basically what we're doing is that if they are the same right then what we're gonna do is that we're trying to figure out maybe how was the total distinct characters that we have for the remaining substrings right for the remaining substring right in this case you can see if they equal each other b and b they do equal each other so in this case if i want to find the total distinct subsequence for the current string if the current characters in s and current character and t they do equal each other so we do is we basically have our pointer right uh move one to the left to figure out how many distinct subsequence or how many unique subsequences that we have in a remaining string right and if they don't equal each other in this case uh we basically just going to uh move right in this case move the left pointer uh move the pointer for the s string one to the left to figure out what's the total distinct subsequence right but there could also be a situation here you can see at the end you can see we're going to get a and b here right from s but the thing is that there could also be a sub sequence that we could have a b right where we're starting our pointer at here right which is here we're starting our pointer here comparing with this pointer right character for this pointer you can see this b and this b right here they do equal to each other right so we don't have to just compare this character with this character we also have to compare the remaining substring for uh an s with the current substring in t right so you can see here we basically just go also going to uh get the total right distinct subsequence starting from the next character right the next character in or the next substring in s comparing with the current substring that we have in t right because you can see here we can also have b here and then a here right so that will be one substring that we can be able to generate so this is our recursion tree and then you can see s is a b and t is a b and then we can go down in this case we can there's two ways because now b they do equal each other right if they don't equal each other then we're just going to uh go down to s i minus one basically we're just going to uh look at the substring a remaining substring for s comparing with the current substring with t right so in this case they do match so we do is we're going down two pound one path is we're going to check the remaining substring and s and remaining substring in t to see what's the total distinct subsequence and the other path is we check the remaining substring in s and then the current substring in t right so you can see here for the current substring t and then the remaining substrate in s is a b and then current substring and t is a b right so in this case we're going to go down this path in this case we have a right we can also go down where in this case we're just going to take the remaining substrate in s and remaining substrate in t and then there is one path if i go down this path where i take the remaining substrate in s and the current substring t in this case there is no path and then now in this case if i backtrack and i go back go down this path then you can see here that if i take the remaining substrings in this case the remaining substrings in s and remaining substituency t there's one path where we can basically go down this way and then there's one pound and you can see that there's total of two distinct subsequence that we can generate uh for this input so now let's take a look at a bigger example right so let's say we have a b and a b okay so in this case this is our recursion tree and what we're expecting is we're expecting three right we can have a b as that's equal to t we can have a b like this where we can also have a b like this which is also equal to t so their total the output i'm expecting is three right so in this case you can see we're starting from the root and then in this case we have a b and it is a b so in this case we can go down two path because now the last characters do equal each other right so in this case what we can do is that we can go down this path where we're basically just focus on the remaining substring for s and the remaining substring of t is because we have a b8 and a right and in this case you can see we can go down this two path so in this case we can get the subcurrent substrings of uh in this case s and t right the current substrings occur remaining sub uh remaining substrings of s comparing with the remaining substring was t in this case an empty string was t and then we have a b and s this is one the reason why we have one just like i mentioned before right let's say if we have a situation where this is s and then we have empty string in t this is our s right in this case an empty string is a subsequence in s that is equal to t right so therefore in this case we're just going to return what but however though let's say we have an empty string in s and we have a and t there's no subsequence in a there's no subsequence in s that is equal to a that right that is equal to t so therefore there's no subsequence if we have a situation like this so therefore we're returning one uh so here you can see we can also go down another path where we're not taking the we're taking the current substring in t and we're taking the remaining substrings in s in this case a b comparing with the current substring and t in this case we can also go down this path where we can have a right because now these characters they don't equal each other so we take the remaining of s right and the current substring was t and then we're going down this path right so we have one so in this case so far we have two so we can backtrack to the root here and then we're going down the other path in this case you can see we can also have a b a and a b right so we're taking the remaining substring of s and then the current substring of t uh yeah so then in this case for this one right here you can see the last character doesn't equal each other so we're taking the remaining substring in s and then current substrate in t so we're going down this path so we have a b and a b in this case you can see we're taking the remaining substrings of s and t right to make it one path in this case we can have a which is one and then we can also have just like remaining substring of s and then the current substring of t in this case you can see here uh they don't equal each other for last characters so we're taking the remaining substrings of s which is just an empty string and then the remaining substring of t which is just a right uh sorry just a b because we cannot take the roommate we have to take the current substrings in t so in this case we have an empty string for s and then the current string and t is a b but you can see here just like i mentioned if s is empty string and then t is a character a or a b or the abc it doesn't matter so in this case there is zero because there's no way that there's no subsequence in s that is equal to t right so in this case we're outputting two we're outputting zero and then you can see if we collect all our ones here you can see we have three ones and the output is three right now as you can see here um this is our top down approach right this is our recursion tree and you can see here that this computation is computed multiple times right this computed it multiple times so what we can do is that we can basically just have a cache uh to basically cache the current index right the current index of s and current index of t in a 2d cache array so that if this is already computed before right we only have one character left with s and we only have one character left for t then we compute that pre-computed result then we compute that pre-computed result then we compute that pre-computed result in a 2d array so that if we visit that situation again we can basically retrieve that in the cache array right so now let's take a look at the top-down so now let's take a look at the top-down so now let's take a look at the top-down approach so you can see here this is our top-down so you can see here this is our top-down so you can see here this is our top-down approach right and this is our non-distinct non-distinct non-distinct function which takes the s string and the t string and then we're first creating some global variables here and then what we're going to do is we're going to define our base case and our base case is that if s is smaller than t that we know that there's no subsequence uh in s that we can generate that equals to t right because you can see this the size of s equal to t right is less than t so that we create our cash array and then in this case you can see here the cash array which basically is the size or basically is s times t right so in this case that's basically our space complexity as well and then we're calling this dfs dfx function uh dfs function and then we're passing in we're starting from the last character for both strings so this is the t index which is the last character initially and then this is the s index which is the last character initially and at first we define our base case right just like our recursion tree that we saw uh let's say we have a situation where s is not empty and t is empty right then we can be able to find a empty string an empty string is basically a subsequence in s that is equal to t so therefore we return one if they're all equal to empty string then in this case we can also equal we can also return one because s uh a uh empty string is a subsequence of s that is equal to t however though if t is not empty but s is empty so therefore there's no way that s can be able to generate t right there's no subsequence in s that's equal to t so therefore we're returning zero so once we have our three base case defined then what we're gonna do is we're gonna see if this current uh computation is already computed in our cache if it is then we're going to return that if not what we're going to do is we're going to compute it now just like i mentioned before there are two uh paths we can branch out to right but however it depends on the condition if the current character in s and current character in t is equal to each other so what we're going to do is we're going to compute the current position right the current position is basically either or sorry is we can go down one path where we're going to comparing the remaining substrings for both strings or we're going to comparing the remaining substrings in s uh and then the current substrings in t and then the other path is that if they don't equal each other we're basically just going to do this right we're going to compute the current position right the current situation where the current we're going to compare with the current sub current substrings in s with the current strings uh in t right current substrings and t with the remaining substrings in s right and we're going to save it in our cache and then we're going to return that as our result for the current position and this is basically how we're going to do it for how we solve this problem using a top-down approach so before we using a top-down approach so before we using a top-down approach so before we jump into the bottom-up approach i want to talk about bottom-up approach i want to talk about bottom-up approach i want to talk about the time complexity so time complexity is basically just going to be s times t right the size of our size of s times the size of our t and the space complexity because we're using our 2d cache array with t times s in this case we have a space complexity of s times t right so now let's take a look at a bottom up approach so for our bottom-up approach you can so for our bottom-up approach you can so for our bottom-up approach you can see on the right we have our 2d table right which is basically s times t but the thing is that you can see there's also an extra space there right this extra row and extra column is basically empty string this is our base case just like i mentioned before if our if we have let's say we have s which is equal to empty string and t right is equal to let's say a or something right in this case you can see we should have zero distinct subsequence right however though if s is equal to let's say a or let's say empty string and then t is equal to a empty string in this case there should be one solution right if it's an empty we're just going to have one distinct subsequence right and then if s is equal to let's say a right and that we're just we have t which is equal to empty string then there should be one distinct subsequence right because in this case an empty string and s is a this thing is a subsequence that is equal to t right so we're going to have that row that entire row to be one so that's what we're doing here we're building the first row and fill them up with just once and then the second row we're gonna you can see for nested loop we're actually starting at here because we already have the outer layer defined uh or the in this case the second row second column i should say so you can see here that we basically do our check if the current character doesn't equal each other then what we're going to do is we're basically just going to uh you know either take two paths right either take uh the remaining substrings right the remaining substrings of t oh sorry remaining substrings of t comparing with remaining substrings of s or i take the current substrings in t comparing with the remaining substrings at s which is basically those two positions right so that's basically the remaining substrings and s comparing with remaining substrings in t this position is basically remaining substrings in s comparing with the current substrings in t right so in this case there's one distinct subsequence here zero this thing subsequence here so i'm going to get the sum of that which is what right and then you can also see here we're basically building up our table here you can see that for b we know that the b in this case they don't equal each other right so if they if r and b doesn't equal each other so what we do is we basically inherit from the uh from this value right here right because in this case if they don't equal each other so we're just basically taking the remaining substrates the s comparing with the current substrings in t so which is basically just one we'll just inherit that value from here and same thing here if they don't equal each other we just inherit that value from the previous uh previous column same row and previous call right and then for this position for this row right same thing here in this case they don't equal each other so i'm going to inherit it from the previous column which is here in this case they don't they do equal each other so then what we're going to do is we're going to take that um in this case we're going to comparing with the remaining substrings which is basically one and zero right which is the sum of that which is one and now here you can see those two are equal to each other so in this case we're basically just taking the sum for those two right so in this case you can see the answer is just basically two and this is what we're doing here at the end we're basically just take returning the last element in the 2d array right so this is basically how we solve the problem the time complexity and space complexity it's basically just going to be t times s right so there you have it and thank you for watching
Distinct Subsequences
distinct-subsequences
Given two strings `s` and `t`, return _the number of distinct_ **_subsequences_** _of_ `s` _which equals_ `t`. The test cases are generated so that the answer fits on a 32-bit signed integer. **Example 1:** **Input:** s = "rabbbit ", t = "rabbit " **Output:** 3 **Explanation:** As shown below, there are 3 ways you can generate "rabbit " from s. `**rabb**b**it**` `**ra**b**bbit**` `**rab**b**bit**` **Example 2:** **Input:** s = "babgbag ", t = "bag " **Output:** 5 **Explanation:** As shown below, there are 5 ways you can generate "bag " from s. `**ba**b**g**bag` `**ba**bgba**g**` `**b**abgb**ag**` `ba**b**gb**ag**` `babg**bag**` **Constraints:** * `1 <= s.length, t.length <= 1000` * `s` and `t` consist of English letters.
null
String,Dynamic Programming
Hard
2115
1,317
elephants so today we are discuss this question on feed code 171 if you could bt 171 question number one three months if convert integer to the sum of non zero mission statement states that you are given and into the tent and you have to return two integers a and B says that the two a and B are the nonzero integers it means it doesn't contain any zeros it means a and B are the numbers which are formed from M should not contain any zero and the sum of TL plus B equal to them and it is also guaranteed at least one valid solution is like they exist a valid for it so as you can see in this example who can open into one plus one well into one and the solution is that one plus one is equal to and both are nonzero number same for this case if we subtract 1 it will become 10 and 1 and 10 has zero on it that's when I subtract 2 and it become to a 9 in this we can subtract 1 and this also we can subtract 1 so like if we do a brute force method is a very simple question but I have done this port I have taken both integers the first is 1 and the second is in minus 1 I just subtracted 1 because we want the sum to be equal to if we add a and B is equal to M then what I do I'll make a while loop and an admit a function and not has zero so I'll check is EA not has EO and all should be what has 0 if this statement true will break out of this pilot or else this while loop is always true and whenever I this condition is not true I will be payment K by 1 so that will become 2 and now P is the gripper 1 so that the sum always remain equal to and we iterate over this loop until a solution is found not a zero function is also simple we'll just in trade over the number such that it is not equal to zero and we check every digit of that number and if it has zero then we return false because my function is not has and it ought it not has zero false because that number has zero and if not has zero will return to because any digit in that number is not as you and if both are true then I will break order to break out of the loop and we'll return the list of LP which are the two back two numbers which equal which are whose sum equal to n and Booth has not your integer and I hope you understand the question thank you
Convert Integer to the Sum of Two No-Zero Integers
monthly-transactions-i
**No-Zero integer** is a positive integer that **does not contain any `0`** in its decimal representation. Given an integer `n`, return _a list of two integers_ `[a, b]` _where_: * `a` and `b` are **No-Zero integers**. * `a + b = n` The test cases are generated so that there is at least one valid solution. If there are many valid solutions, you can return any of them. **Example 1:** **Input:** n = 2 **Output:** \[1,1\] **Explanation:** Let a = 1 and b = 1. Both a and b are no-zero integers, and a + b = 2 = n. **Example 2:** **Input:** n = 11 **Output:** \[2,9\] **Explanation:** Let a = 2 and b = 9. Both a and b are no-zero integers, and a + b = 9 = n. Note that there are other valid answers as \[8, 3\] that can be accepted. **Constraints:** * `2 <= n <= 104`
null
Database
Medium
1328
1,663
hello everyone welcome to quartus camp we are a 22nd day of march lead code challenge and the problem we are going to cover in this video is smallest string with a given numeric value so the input given here is to integer value n and k and we have to return a string as an output which is nothing but lexicographically smallest string with length n and numeric value equal to k so here the problem statement says that the alphabet starting from a to z will be positioned with one index that is a is 1 b is 2 and so on and we have to form a string whose numeric value is equal to k or end of length n and return it so let's understand this with an example so here is a given first example where n is equal to 3 and k is equal to 27 so which means we have to form a 3 character string whose value is equal to 27 so the output could possibly be a y because a is equal to 1 again a is equal to 1 which sums up to 2 and the rest is going to be 25 y is going to be 25 and finally is that is going to be 26 which we already know so we can also form a b and x or a c and w which will also sums up to 27 but here the problem statement clearly says we have to form lexicographically smallest string so in that case a y would be the lexicographically smallest out of all these solutions because the second character is b and c here in the other words when the first word is having a this is going to be lexicographically smallest so how are we going to approach this programmatically so here the idea is to first form the string with all a's because our string has to be smallest and a is the smallest of all characters so we are going to fill a string with all is so that we get the smallest string first and then we are going to append or overwrite the last character or from the last character towards left so that we make sure that the string maintains the lexicographical order so now we have all a's in our first example n is equal to 3 which sums up to 3 so now our k given here is 27 we have to have 24 more values that has to be satisfied in order to get our first example done so here our string is already formed with all a's whose sum is equal to 3 so now we have our k is equal to 27 we still have 24 more values to be filled so let's start by overriding the last character with values so let's say the first two a stays the same and we are appending a with b so now it becomes four same way we are overriding b with c and this is 5 and d this is 6 and so on finally we are going to append it with y which will give you the value of 27 so as we finally fix the last character's value as y the rest of the two characters are going to seem going to stay the same and this is going to be our output so how did we do it we just started to override the values from the last most character so now we already have a 1 we have to have 24 more so character y will actually get you to that range which will simply be we are first going to check whether we can append this with an is it so is that is nothing but the last character which is having the value 26 so in this case we are simply going to remove this character and override it with is it so we don't actually add 26 we add only 25 why because we already have a value a which is 1 so in this case we add 26 and subtract 1 so which is simply done by doing a minus 1 for this character so if we add 25 to it which will actually be overriding 24 because we have only 24 left if we add 25 then it goes in case value goes in minus 1. so in that case we should not we cannot append it with it so what would be the previous character is it which is nothing but y so for y the actual value is 25 so we are going to replace a with y so in that case we will be adding only 24 to it because we'll add 25 and subtract 1. so 24 satisfies with the existing 24 that is the value of k so we are going to append it with y so hope you are understanding this logic if not let us do a quick run through for the second example so you will get a get better understanding so now n is equal to five so we have to form a string of length five so let us fill with all a's in all five positions so as i said we are going to replace or overwrite the values from the last character towards the first character so now we have our value as 73 so now k is equal to 73 so as i said we have added 5 a's which means which sums up to 5 for now so let us subtract 5 from 73 which will give you 68 so why we are subtracting 5 because we have the sum of 5 so we have to add 68 more to this string so we are going to replace the last character with the highest value possible so what is the highest value from a to z which is z whose value is equal to 26 so here we are going to check whether we can add is it at the end so 68 minus 26 is something higher so we can actually add the value is it at the end but here instead of adding 26 we are simply going to add 25 why because the last character will be replaced by z so in this case if we are going to replace a we are going to first remove a which will take away minus 1 from the total sum and we add 25 to it so in short we simply add 20 to 25 instead of 26. so the characters are going to be same for the first four places and finally we are going to add an is it which will actually sum up to 5 plus 25 30. so as we have added one more 25 to our string let us subtract this 25 from 68 which is 43 so we have 43 more value left to be added to the string as we have added our last character to z which is the maximum value so we have to now move to our last but one character and check whether we can replace it with the highest value which is it so if you subtract 43 with 26 you still have more values to add so in this case again the rest of the characters are going to be same and we are going to replace it with set and the last character is already said so now we have to subtract one more 25 from here which will give you 18 so we still have 18 more to be added to our string so now we have last two characters appended to the maximum value so we cannot change it so now it's time to move to one last but one character so now we have only 18 left to be filled so we are checking whether z can be replaced in this place no because we only have 18 but the value of is it is 26 and for our problem it is going to be 25 so we can't do it so further we reduce it by one character y will be 24 w will be 23 and so on and finally s will be your 18 so when you fill this character with s this 18 will be subtracted and our k will become zero so our solution will actually be a s set and rk has become 0 and our size is already length is already 5 and this satisfies our input criterias and this is going to be our output so this is going to work in big o of n time and space complexity because we are going to use an additional memory to compute this characters which is a character array and we are going to iterate all the characters of length n and fill in the values so let's get into the code now so here is a code for a problem which is pretty simple as i said we are going to have a character array which is going to hold all our characters and finally we are going to return it in form of string because our output is going to be in string and first we are filling our array with all a's as i said we have to fill it with minimum value and first we are going to subtract with n because if we add a in all the positions from total k n will be subtracted as we have added as many number of a's to it and finally we are going to iterate till our k is becoming 0 and at the position from the last because n is at the last position we are going to subtract or decrement our n at every iteration so that our values will be filled or overridden from the last position so as i said we are going to check which is minimum whether 25 or k if 25 is minimum from k we first append it with a z and subtract the value from k if not if k is minimum then we are going to append it with result with that particular character and subtract it from k and finally rk becomes zero so we are going to replace the characters from the last till however position it holds and finally we are going to return it in form of result so hope you are understanding this code let's give it a try yes so let's submit yes the solution has been accepted and returns in 23 milliseconds so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
Smallest String With A Given Numeric Value
detect-cycles-in-2d-grid
The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on. The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string `"abe "` is equal to `1 + 2 + 5 = 8`. You are given two integers `n` and `k`. Return _the **lexicographically smallest string** with **length** equal to `n` and **numeric value** equal to `k`._ Note that a string `x` is lexicographically smaller than string `y` if `x` comes before `y` in dictionary order, that is, either `x` is a prefix of `y`, or if `i` is the first position such that `x[i] != y[i]`, then `x[i]` comes before `y[i]` in alphabetic order. **Example 1:** **Input:** n = 3, k = 27 **Output:** "aay " **Explanation:** The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3. **Example 2:** **Input:** n = 5, k = 73 **Output:** "aaszz " **Constraints:** * `1 <= n <= 105` * `n <= k <= 26 * n`
Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
null
216
welcome to september's lego challenge today's problem is combination sum three find out possible combinations of k numbers that add up to a number n given that only numbers one to nine can be used and each combination should be a unique set of numbers so that's actually very helpful that each combination can only be a unique set of numbers so we should never have any repeating numbers now if we are given the number k equals three and n equals seven then we can see our output's gonna be one two four because this is the only combination of numbers from one to nine uh with three numbers that's ever gonna equal seven with three and nine here we have one two six one three five and two three four uh so that's basically it um now one of the things that we can see with this problem is that the numbers that we can use are potential candidates let's say are always going to be sorted it's going to be one through nine so that's actually very helpful in what we want to use our approach we can use a depth first search recursion and what we're going to do is basically check every single go through a recursive loop where we check to see every single combination that we can build from our numbers one through nine and we'll build up our stack as we move along and once we have a stack that is the length of k we'll check to see if the number is n and if it is we'll add it to an output and if it isn't we just will stop our recursion right there because one of the good things about this is because it's sorted once we see that the sum is greater than the sum that we want to calculate for we could stop our loop we don't need to calculate any more after that because say that we have like one two six now we want to check one two seven well we don't need to check that because we already know everything after this point is going to be greater than nine so we could break our loop there all right so the first thing i might want to do is set a output of an empty list and we're going to do a depth first search recursion and a couple primers we need to pass first we need to pass our stack or the build list that we're building up and we need to pass in our number to know where we are in our recursion like are we at one are we at two um and that way we can know like we're not going to make any repeats and check numbers that we've already set so we don't need a set here we just need to know where are we in our recursive path let's say uh and the last thing we want to pass is some so far and what this is going to allow us to do is not have to check our build to see how what the sum is every single time we just check that here and say hey if the sum that we calculate so far equals n then add our build to the output all right so the first thing we need to do here is have our base case right and if this build i should say the length of this build is equal to k then we know we can end our recursion we don't want to go any further than that but one thing we need to do is check to see if our sum so far equals n because if it does then we add it to our output otherwise we don't and we just keep we just stop our recursion so if sum so far equals n then add to the pen to our output the build and this is our stack that we're building up um and that would be it so at this point here this is where we're going to be actually making our recursion and what we'll have to do is basically check from i and range of the number we're on all the way up to nine and we actually need to add one there to make sure we take care of nine um and we will call our deaf research we'll call our pass in our build plus the number that we've just calculated for we'll pass in our uh i as a number but we'll actually add that one there so that we don't like repeat the same number and we need to pass in our sum so far plus the i so this is going to be what allows us to check to make sure that the number is equal to number we're checking for right and one thing we can actually do here is just check sum so far plus i if this is greater than n then we can just break our loop actually we don't need to calculate any further because that would be a waste of time since we know our sum so far is already exceeded and like we don't need to calculate any more than that and that would be it um all we need to do now is just call our debt for search we'll call in a passing empty list as a stack we'll pass in our num so far which is going to be i'm sorry number we're on which is going to be 1 first and the sum so far which is going to be 0 at first and that's it after that we just return our output and this should solve the question let's make sure this works looks like it does and there we go so that's accepted that works perfectly fine and it's a good solution uh one thing to note is one of the things also you can do is actually use inner tools and why don't we just use inner tools and find all the possible combinations for the numbers one through nine with a length of k right and we actually have a tool for that in inter tools so we can use create a list say nums i for i in what range of one through nine plus one uh while this numbs and we'll say okay give me all the combinations using inner tools that's some numbs with a length of k right so this is going to give us all possible combinations with a length of k and then really all we can just do here is say all right well we turn for c in combo if the sum of c equals n then add it to our list and just return that and let's make sure that works it does and this should be accepted it does and shockingly this actually is faster in lead code now technically this is slower in terms of time complexity because we're not breaking our loop um before we're actually checking for every single combination but it actually runs faster and the reason for that i'm not completely sure but my guess is it's got something to do with the way the algorithm works for combinations here it's just whatever is going in the background it's faster than my stupid little recursive for loop um so sometimes like even though in theory like my time complexity is faster sometimes these things the reality just doesn't match and that this is actually faster so it's like one of those things to remember stay humble even though you think you know something like the reality might be different this might actually be a better use than my recursive function so all right i think i'll end it there thanks for watching my channel and remember do not trust me i know nothing
Combination Sum III
combination-sum-iii
Find all valid combinations of `k` numbers that sum up to `n` such that the following conditions are true: * Only numbers `1` through `9` are used. * Each number is used **at most once**. Return _a list of all possible valid combinations_. The list must not contain the same combination twice, and the combinations may be returned in any order. **Example 1:** **Input:** k = 3, n = 7 **Output:** \[\[1,2,4\]\] **Explanation:** 1 + 2 + 4 = 7 There are no other valid combinations. **Example 2:** **Input:** k = 3, n = 9 **Output:** \[\[1,2,6\],\[1,3,5\],\[2,3,4\]\] **Explanation:** 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. **Example 3:** **Input:** k = 4, n = 1 **Output:** \[\] **Explanation:** There are no valid combinations. Using 4 different numbers in the range \[1,9\], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination. **Constraints:** * `2 <= k <= 9` * `1 <= n <= 60`
null
Array,Backtracking
Medium
39
378
welcome to july's leeco challenge today's problem is k smallest element in a sorted matrix given an m times n matrix where each of the rows and columns are sorted in ascending order we turn the kth smallest element in the matrix now note that it is the k smallest element in the sorted order not the case distinct element so we had duplicates we're still looking at the index number not the distinct element okay so at first glance it kind of looks like this is just sorted in like road column fashion 159 10 11 13 so why don't we use like divisors and modulars but that's not going to work because you can easily imagine some examples where we're sorted row and column but it's not going to be sorted in that same direction so this technically is sorted rolling column but if we moved left to right here that wouldn't work because it's not in sorted order so that's not going to work is there anything we could take advantage of given that it's sorted well before we do that why don't we just do a brute force method let's just flatten this matrix into a 1d array and see if we could sort it and return the kth element in there and all we have to do then is say 4l in matrix we'll just extend our temporary array with the list and make sure to sort this and literally just return the temp k minus 1 element right so this would be the brute force method and it actually does work in fact it gets accepted here um because time complexity wise it's going to be what n squared to the log of n squared because of the sort here so you know at first glance i thought like okay well this is it maybe that's it that's the solution but something didn't sit right with me because i knew that because it's sorted in row and column fashion there has to be something we can take advantage of here otherwise it's like we're literally just storing the whole thing we're not taking advantage of the fact that it's sorted in rolling column um so one way that you could do that is to do a binary search but instead of looking at the elements here what we're going to do is look at the gap between the minimum number and the maximum number that's going to be our range when we do a binary search and we're going to do another binary search through each row to find how many elements are less than the element that we're searching for as soon as we find our left and right range equal another and our k is yeah equal to 8 then we can return whatever number we come up with so one of the few things we do know about this matrix is that the top left right here and the bottom right is going to be the min and max of our matrix right so let's first take advantage of that we'll set our left and right pointers as well as the n here make the left pointer is going to be matrix of zero right point is gonna be matrix of negative one and the n is just going to be what length of matrix so first let's write a helper method to show us how many elements are less than whatever input that we put in to check whether we should move our left pointer to the middle or the right corner to the middle so we'll call this less than k and we'll pass in some number so let's see we're going to count the numbers initialize it with zero and we'll say four say row and range of n let's do a binary search here we'll do a bisect but we have to do a bisect right and the reason for that is let's see here the reason for that is if we find a number that's like equal to all these numbers here we want to go all the way to the right side to see how many are less than k so we'll say bisect right and then we'll add this number to our account here finally return our account and now let's do our binary search so while l is less than r calculate the mid which is going to be l plus r divided by two uh if less than k oops less k of mid if this value is less than k then we want to move our left pointer to the middle right and we're going to have to add one here because we want to find um the right gap here so otherwise we'll say r equals to mid and then we can just return r l or r doesn't matter which one so let's see if this works okay that doesn't look like it's working so submit it and there you go so that's accepted as well uh time complexity wise this would be i think it's gonna be log oh no it's gonna be n to the log of whatever the gap between the min and max is so we'll call that m so n log of a right here i believe that's correct although this part here might make it n log n hmm n log n times log of the m something like that but either way when i look at the speed it's about the same because of our constraints uh really depends on what would be our constraints if we had like really large ends this solution would be much better otherwise the brute force method works fine and it's uh in fact sometimes faster when we run it and look at the time so it's up to you i did see one other solution that is oven time but it was so complicated it used math and median values and it was just way too complex for me to go through so let's end it here thanks for watching my channel and remember do not trust me i know nothing
Kth Smallest Element in a Sorted Matrix
kth-smallest-element-in-a-sorted-matrix
Given an `n x n` `matrix` where each of the rows and columns is sorted in ascending order, return _the_ `kth` _smallest element in the matrix_. Note that it is the `kth` smallest element **in the sorted order**, not the `kth` **distinct** element. You must find a solution with a memory complexity better than `O(n2)`. **Example 1:** **Input:** matrix = \[\[1,5,9\],\[10,11,13\],\[12,13,15\]\], k = 8 **Output:** 13 **Explanation:** The elements in the matrix are \[1,5,9,10,11,12,13,**13**,15\], and the 8th smallest number is 13 **Example 2:** **Input:** matrix = \[\[-5\]\], k = 1 **Output:** -5 **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 300` * `-109 <= matrix[i][j] <= 109` * All the rows and columns of `matrix` are **guaranteed** to be sorted in **non-decreasing order**. * `1 <= k <= n2` **Follow up:** * Could you solve the problem with a constant memory (i.e., `O(1)` memory complexity)? * Could you solve the problem in `O(n)` time complexity? The solution may be too advanced for an interview but you may find reading [this paper](http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf) fun.
null
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
Medium
373,668,719,802
478
hello everyone welcome to day 17th of march lead code challenge and today's question is generate random points in a circle in this question you are given three parameters the first one is the radius of the circle the second one is the x coordinate of the center of the circle followed by the y coordinate of the center of the circle what we need to do is to generate random points which lie within the circle this point should be highlighted but the point that we need to generate should lie within the circle not on the circumference of the circle nor outside the circle so please keep this point in mind and let's quickly understand the algorithm that i have created for this we need to fill in these two methods in the solution the first one being the constructor of the class and the second one is a random point generation logic so moving on to the algorithmic part the slideshow that i have created for this let me just take a pen here so even before jumping onto the details of the algorithm let's try and understand few properties of a circle the center of the circle is a comma b let's highlight that a is x coordinate b is the y coordinate and the radius is r so this is r this length is r again this 2 being r so let's write all the extreme coordinates of the circles this point would be a comma b plus r the bottom one would be a comma b minus r the right most would be a plus r comma b and the left one would be a minus r comma b so this is a minus r comma b also let's try and understand few properties that we read in 11th or 12th standard x minus a where a is the center of the circle square plus y minus b square if it's equal to r square then it lies on the circle so if there's an x and y coordinate whose distance from the center whole distance from the center which is given by a square x minus a square plus y minus b square happens to be equal to r square then that point lies on the circle if it's greater than r square that means it's like it lies outside the circle somewhere here like anywhere around along this region and if it lies within if it is less than r square that means this distance is less than r square x minus a square plus y minus b square is less than r square that means that lies inside the circle so these all for all these points this property will be true pretty simple and let's reduce the problem from a circle to a 1d problem to a point to a to 1d problem from a 2d to a 1d problem how let me just explain that let's assume this coordinate as a and we are interested in finding a random number between a plus r starting from a minus r so this is pretty much clear to us that the range that we are interested in is a minus r to a plus r as stated here the range of x coordinate how can we do that let's try and generate random numbers up to a range of 2r so if we are able to do that starting from 0 we can generate random numbers up to 2r pretty straightforward we can use java rand helper class uh to generate numbers from 0 up to 2r and let's then add a minus r to it so if i add a minus r to it this point will become this point and this point will become a minus r will become this point and the center would be a so which mathematical formula can we derive we need to generate numbers a minus r plus random up to 2r so this is the formula that we have that we will use for generating random numbers between the range of a minus r up to a plus r a minus r plus random 2 r that means first you generated a random number starting from 0 to 2 r and you added a minus r to it and therefore you are able to generate this range we'll do this for the x coordinate here we'll do it for the y coordinate and we will pass the x and y coordinates uh to this logic of ours which will tell us whether that point lies on the circle outside the circle or inside the circle we'll keep on doing that till the time we don't find the point that lies inside the circle that's it that's pretty much it and as soon as we find such a point we abort the process and return those x and y coordinates so let's quickly move on to the coding part let me just define three variables a stands for the x coordinate double b stands for the y coordinate of the center so these two correspond to the center and double r stands for the radius we will also generate a random helper class and let's call it random means like this null and let's move on to the constructor part this dot a equals to x enter this dot b equals to buy center pretty simple and this dot r equals to radius also we'll initialize rand equals to new random so everything that we need to initialize has to be done in the constructor and all the private uh helper methods should be uh in initialized null or their default values basic rule of java and let's just write the method to generate x and y coordinates in that range so get random coordinate and what we will pass it r and the starting coordinate so let's write this helper method first generate random coordinate and it will accept two double variables first is the radius and second one is the x or the y center coordinate so let me just call it c and what we need to return r minus c plus rand dot next double into 2 into r so let me just explain this part to you next double gives us floating values between the range of 0 till 1 and when we multiply it with 2r we get numbers floating numbers within the range from 0 till 2r this is what i have done here and once we have written this let's just generate the y-coordinate get the y-coordinate get the y-coordinate get random coordinate r comma b and while get distance and what will pass x comma y comma r if it's greater than or equal to r square r into r if that is the case then we'll have to keep on generating such random numbers otherwise we'll return our answer and these x and y coordinates are those coordinates of a random point to completely this let's write the last method private double get distance double x and double y we don't need r here so let me just remove that and the distance would be given to us using the formula of distance between two points x minus a into x minus a plus y minus b into y minus b pretty straightforward way of calculating the distance actually the square of the distance and i have not used square root therefore i multiplied it with r into r other than keeping r then otherwise i would have done a square root here not an issue or you can go for either ways and let's just revise this code once yeah this looks fine we generated the numbers get distance and get random coordinates oh this should be c minus r so though in this slideshow you saw a minus r plus 2 random of 2r so using the same logic i have written it here so this is c minus rather than a minus r and let's just submit this accept it thanks for watching the video hope you enjoyed it please don't forget to like share or subscribe and subscribe to the channel
Generate Random Point in a Circle
generate-random-point-in-a-circle
Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle. Implement the `Solution` class: * `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle `radius` and the position of the center `(x_center, y_center)`. * `randPoint()` returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array `[x, y]`. **Example 1:** **Input** \[ "Solution ", "randPoint ", "randPoint ", "randPoint "\] \[\[1.0, 0.0, 0.0\], \[\], \[\], \[\]\] **Output** \[null, \[-0.02493, -0.38077\], \[0.82314, 0.38945\], \[0.36572, 0.17248\]\] **Explanation** Solution solution = new Solution(1.0, 0.0, 0.0); solution.randPoint(); // return \[-0.02493, -0.38077\] solution.randPoint(); // return \[0.82314, 0.38945\] solution.randPoint(); // return \[0.36572, 0.17248\] **Constraints:** * `0 < radius <= 108` * `-107 <= x_center, y_center <= 107` * At most `3 * 104` calls will be made to `randPoint`.
null
null
Medium
null
147
hi guys how are you i hope all you are doing good welcome to the learn code easily so today we will solve one more question that is medial well question and the question is insertion list it's it is a very easy question actually this is coming from the insertion sort if you know the insertion sort then you have to then you can do it very well if you do not know then first you have first you need to learn if you go on the internet and you if you write on insert some sort then there are some good explanation out there you can re you can read it from there uh yeah so as in this with the help of graph everything is given here if you want to learn how the insertion insertions are work then it is graphically represented here you can see from here this is the same process now you have to follow the same process as it is as given in the picture so first i will tell you uh already it is written in the three points insertion sort i create consuming one input element each repetition and growing a sorted output list at each iteration insertion sort removes one element from the input data find its location as you can see it is finding its location so the location of three is here belong within sorted list and insert it there it repeats until no input remains no input elements remain so we have started from here now when we will go till four so four will be resetted here so the list is sorted so the three points have been described in the pictorial form so if i take that one example so how we will do it as you can see if you compare you have to compare every time you have to start from here and your second pointer is this one like this one now you have to compare the previous element is greater than the current element so we will swap so it will become five comma six now the remaining list is three one eight seven two four now uh we have uh we are done with this element we will move towards the next element now 3 is greater than 5 is greater than 3 yes so let's sort it so it will become 3 6 now uh the 5 will come here 18 7 to 4 so this is the first step now this is the second step but this is not yet uh in indeed why because the because we have the initial pointer is here now i will go there i will go for the next position and i will check 6 is greater than 5 yes so it will become 3 comma 5 comma 6 18 comma says 7 comma 2 comma 4 now i am at this position now if you will move there then your current pointer and the previous pointer will come at the same point so we cannot do anything so the second step is done now we will again move from starting and now your next current pointer is at this point you have to compare again one and six then you have to compare this element with one and you have to compare with this index element with one so if you compare then it will become 1 comma 5 comma 3 comma 6 comma 8 comma 7 comma 2 comma 4 now it is still not in that and now you are there now you will reach at this position okay now you are done with first like this element now you will come at this point your current pointer is this you have to compare both one five is greater than six no okay so this will be like same as given now you are done with uh one you are done with 5 now your pointer will move to 3 and you will compare one is less than 5 is also less than i have done something wrong here when your pointer will come at this point one so one will go there six will come here five three now six you have to compare with this is also less than you have to compare with three as well no something is wrong i have done so five six is correct now you will come at three now you have to it will become three five six okay now you will come at 18 this is like this is a team this is it now when you will come at this point you have to one five six it will be three now you have to compare three bit five so three will come here five will come here and it will be six now you will compare with five and three so it will be three and now you have to compare with six and five so five will come here 6 8 7 2 4 now you now your pointer was there so the previous pointer and the current pointer are at the same position so you cannot do anything now you will move eight now you have to compare again eight with one eight with three so all are sorted now you will go for seven you will compare with every element one three five are less than 6 is also less than when you will reach at this point then you can see that previous element is greater than the current element so i am doing directly so it will be 6 now 8 and 7 will be swiping will be swap so it will become 7 8 2 4 now you will move at 2 now you will compare with 2 and 1 okay it is less than now you will compare with 3 and 2. so it will become one two five six seven eight three and four now your pointer will come at this point at this position you will compare for three and five so three will go there five will come here now your next pointer will come here and you will again compare so this will become six and this will become five okay this is also done now you will go for next position so seven and six see the previous element is rather than the current one so we will swipe it so this will become okay so now your current pointer will come here you will swipe it so it will become seven and it will become eight okay this is also done now your current pointer will come at four now you will compare one is less than four two is less than four three is less than four five is not less than four so i will swap these two element okay six is less than five no let's type it say one is less than six no let's type it okay uh it is less than seven no let's type it as you can see my current list is sorted and we have to follow the same step i hope you have understood the process let's begin with the implementation so it is eight minute already done so let's implement as quick as possible so let's take the two pointer that is the current pointer that is my head dot next what is my previous pointer is head okay so if head is equals to none or head dot next is equals to none and head does not equals to none we have to return head so while uh my current pointer then equals to none let's run for another loop when my previous does not equals to current and if my previous dot val is greater than it means that my previous value is greater than the then my current value so let's sep it and move my previous pointer towards the next one no sorry uh it is my current it is my previous yeah it's correct now what i will do every time my previous would start from beginning and i will move my current to current.next current.next current.next and we have to hmm okay so if my head is none if my head of next is none but head is not and still we have to return here because one element we cannot sort a single element so this is my previous this is my current so current as you can see i'm increasing my current every time so the previous is all again is uh always start from the beginning so that's why i have again slicing my previous with the help of it because head is at the starting value it is the starting head is always point to the starting node i am starting my current i'm fixing i'm moving my current towards the next value and also the previous towards the next value as well okay so previous current previous dot file okay i think it is done now let's directly try to submit it and see that whether it would submit or not oh it is taking time okay so we have done in a single strike so i hope you understood how we are doing we are just following the same step as i have described you so if you do not know please go to some articles some documentation of insertion sort you will learn it then you can implement it very well so i hope you understood guys i will okay so there are some similar type of question you can solve this as well so i will meet in the next video with the next video till then bye take care bye guys
Insertion Sort List
insertion-sort-list
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. 3. It repeats until no input elements remain. The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Constraints:** * The number of nodes in the list is in the range `[1, 5000]`. * `-5000 <= Node.val <= 5000`
null
Linked List,Sorting
Medium
148,850
363
welcome to july third sleep code challenge maximum sum max sum of rectangle no larger than k given an m by n matrix entry k return the maximum sum of the rectangle and the matrix such that its sum is no larger than k it's guaranteed that there will be a rectangle with the sum larger than k so given this matrix here uh 1 0 negative 2 3 um you would think that uh using the uh well i'll explain first so let's say if you were to add this rectangle here ly in blue it'll give you the sum of two which is um no larger than k which is two so let's think about this for a bit so first thing you think of is that brute force approach um uh since it's uh negative numbers it's probably not a good way of doing this but uh if you were to enumerate all the possible rectangles to get the best solution uh time complexity probably like uh yeah m squared n times n squared so that might not be the most best way of doing it because it's not very clever and takes a very long time however you seek a little example here using a one dimensional array here so you have two negative one since we're always guaranteed with some larger than k um if we were to sum all these together we'll get uh equal output three and our case three so let's kind of work with this kind of idea working with our one-dimensional idea working with our one-dimensional idea working with our one-dimensional array first and uh seeing how that works out so um let's see so we're going to use this idea um let's see called uh let's see if we have an array of uh negative one negative two and four let's put that space there and we want to develop this thing called a um let's call a look up where it's gonna be a uh an array that's gonna store our something called a prefix um uh p sum so first we're going to use that to start perfect sum so the first thing it's going to have is 0 because there's nothing summing it and we're going to move through our first index here which is going to be negative 1. so perfect sum is going to be a running sum of negative one right here so we're gonna have negative one so first we're gonna have zero here so i'm gonna put whatever's in the perfect sum into our lookup and then we're gonna sum it again and i'm going to add that to our lookup so we're going to have a running sum as we're going along and putting it into our lookup so then we move our um we move to the second right here which is negative 2 plus negative one would be negative three let's store negative three right here and our lookup and then lastly we're gonna move to four so four plus negative three is gonna be one and we store one into our lookup so we're gonna have this however it's uh we're gonna actually rearrange this and put this negative one at the end here but uh i haven't decided yet so i'm gonna use this idea for one dimensional array and how we're going to develop that towards working towards a harder solution we're using not just one dimensional but two or three or even more dimensions right a two-dimensional array two-dimensional array two-dimensional array so um let's see for each time we run this algorithm let's updating our prefix sum in a one-dimensional array we're in a one-dimensional array we're in a one-dimensional array we're probably gonna do it for each uh row each row and then we're gonna do the same thing with then this the entire the global so we're going to sum these two together as well uh the columns together and i'm going to do it for each row that way as well so it's um let's see if this approach or kind of background kind of works um let's get to it so there's many ways of this is a hard solution i mean yeah a hard question uh challenge so let's first divide our uh dimension so m by n is going to be the length of the matrix and then length of the matrix at position zero so yep so we're gonna first make our rows uh so for e for row and matrix we are going to uh start making our array our matrix so for um uh for i in range let's see n minus one what we're going to do is uh make our row so row at index plus one will be incremented to row at i all right so um we need to uh define an output so our output is or initialize our output i should say let's um it could be none but uh that won't work for integer types so let's call it the float of negative infinity just uh just to have some kind of initialization going on now we're going to loop through our matrix so we're going to have a double for loop into nested for loop here so for i in range of n for j in range of i to n so that's uh for each uh each row you're going through what do you want to do so we want one first to find our lookup which is going to be our array of uh starting at zero and we're gonna find our uh prefix sum counter or perfect sum or our ongoing sum i guess which is going to be initialized to zero so for each um let's say um each count now each character each element in our matrix all right let's call it c in range of m for each um this is individual each cell in our matrix on an array we want to be able to update our perfect sum so we're going to implement that with the increment that with the matrix cell at location j and we want to if the um minus the um so if i is greater than zero what do we want to do you want to minus it with the matrix c location at the i minus 1 location else y zero so this is the turning operator here um so that's updating our prefix sum now we want to do is uh update our lookup table and we're going to do that with bisect left so um let's call this index uh or type variable i should say um bisect left our lookup and our perfect sum minus k because now we have a perfect uh sum and our lookup already we're going to build that and we want to make sure the perfect sum is within the restraint within the um within the balance of k right it can't be greater than k because that's the condition and we want uh so if so first we define our index yup so if our index is greater or equal to zero and our index is less than the length of our lookup table what we want to do is update our output to be the max of the output and our prefix sum minus the lookup at the location index then we want to insert so bisecting sort so we want to sort using um a sorted type of approach to the bias and sort we're going to insert lookup and the prefix sum because we want to put the uh this the um the last sum at the end of the lookup and then return our output all right let's see this is even close to working oh let's see output finished oh that doesn't look good let's see first we define our m and n side lengths okay for each row in the matrix we're going to make the columns for it all right and the at and the output is going to be a float of a negative infinite number so for i in range n nested with four j in range i to n we're gonna make a lookup table and a prefix sum counter so for each cell in our matrix we're going to increment our perfect sum with the matrix at location c cell j minus our if the index if i is greater than zero we're going to have a minus the cell at matrix c in the i minus one location else we're gonna minus zero and then whenever we define an index number here which is bisect left where we have to look uh look up and the perfect sum minus k because we wanna not be within our outside our bounds so if the index is greater than or equal to zero and the index is less than the length of lookup we want to update our output with max of the output and the prefix sum wise lookup at the index and then we want to sort that using bisect insert with lookup and the prefix thumb and we want to return the output as well all right that seems to be should work please work all right accepted so this approach is um using something uh using a prefix sum on a one-dimensional array and then one-dimensional array and then one-dimensional array and then we're gonna we eventually sorted it using bisect sort it's not really using a story container it's just more like using the bisect function to sort it but uh in terms of time complexity i believe that it is let's go through this so we have a nested for loop here going through um so we have this is the row which is n so n big o of n times m squared times no wait this is um m this is uh let's see hmm big o of m squared times n times the log of n because for we iterate it's a lot uh i'm not entirely sure about that but the space complexity is a big of n because we store it in our um as a number so uh we store we do have a lookout but we never have to return it so yeah that would probably be our uh i could be taught at wrong in terms of space and space complexity and time complexity but that's a hard question so uh that's pretty much all i got have a good one
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
1,859
hey everybody this is larry this is me going over q1 of the bi-weekly me going over q1 of the bi-weekly me going over q1 of the bi-weekly contest 52 52nd sorting the sentence so hit the like button hit the subscribe button join me on discord let me know what you think about this prom so this one could be it could be a little bit more tricky i think but the key thing and it took me a little bit of a while uh is to notice that there are no more than nine words meaning that you don't you only have to care about the last character and that's it um and that's basically what i did i look at the string i split it up word by word and then i sorted by the last character um and then i joined it back together removing the last character and that's it um this is going to be n log n where n is the number of words uh which i guess roughly is almost the number of characters but like number characters over three or something like that uh but yeah um in terms of space we don't really i mean we it's linear space we can reconstruct everything i suppose um but yeah uh you're not going to do more than that so yeah that's what i have for this problem i solved it during the contest in about a minute and 22 seconds uh yeah uh let me know what you think and you could watch me stop it live during the contest next uh hey yeah uh thanks for watching hit the like button to subscribe and join me in discord let me know what you think about this contest um yeah i hope y'all just have a great week good contests and yeah stay good stay healthy to good mental health and i will see you later bye
Sorting the Sentence
change-minimum-characters-to-satisfy-one-of-three-conditions
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. A sentence can be **shuffled** by appending the **1-indexed word position** to each word then rearranging the words in the sentence. * For example, the sentence `"This is a sentence "` can be shuffled as `"sentence4 a3 is2 This1 "` or `"is2 sentence4 This1 a3 "`. Given a **shuffled sentence** `s` containing no more than `9` words, reconstruct and return _the original sentence_. **Example 1:** **Input:** s = "is2 sentence4 This1 a3 " **Output:** "This is a sentence " **Explanation:** Sort the words in s to their original positions "This1 is2 a3 sentence4 ", then remove the numbers. **Example 2:** **Input:** s = "Myself2 Me1 I4 and3 " **Output:** "Me Myself and I " **Explanation:** Sort the words in s to their original positions "Me1 Myself2 and3 I4 ", then remove the numbers. **Constraints:** * `2 <= s.length <= 200` * `s` consists of lowercase and uppercase English letters, spaces, and digits from `1` to `9`. * The number of words in `s` is between `1` and `9`. * The words in `s` are separated by a single space. * `s` contains no leading or trailing spaces. 1\. All characters in a are strictly less than those in b (i.e., a\[i\] < b\[i\] for all i). 2. All characters in b are strictly less than those in a (i.e., a\[i\] > b\[i\] for all i). 3. All characters in a and b are the same (i.e., a\[i\] = b\[i\] for all i).
Iterate on each letter in the alphabet, and check the smallest number of operations needed to make it one of the following: the largest letter in a and smaller than the smallest one in b, vice versa, or let a and b consist only of this letter. For the first 2 conditions, take care that you can only change characters to lowercase letters, so you can't make 'z' the smallest letter in one of the strings or 'a' the largest letter in one of them.
Hash Table,String,Counting,Prefix Sum
Medium
null
805
hey everybody this is Larry this is me trying to do a bonus prom that haven't done before hit the like button hit the Subscribe button join me on Discord let me know what you think about this one on February 20th 20 24 I almost forgot the year a second all right we have a hard problem today so hopefully not too hard hopefully it's still solvable uh 805 spread away with the same average you are given an integer array nums you should move each element nums into one to two arrays A and B such that a and B A non empty and average of a is equal to average of B return Tru it's possible to achieve that in force otherwise no death run away okay uh so basically this so hm that's a interesting one so the first thing is noticing that the order doesn't matter so yeah um yeah so basically okay H the thing to notice is that and is dirty so what does that mean that means that we can do some funky algorithms um obviously um you know two to the 30 is going to be too slow so what can we do right I mean to be honest two to 30 immediately jumps to me as um as uh spit in the middle or meat in the middle but that's kind of like a I don't know I and this is just a like a little bit meta it's just that it's a very hard thing to expect people to know so on an interview that would be ridiculous let me give it a little bit of a DOT to kind of think about um it's kind of hard to say I mean the other way that I would think about it is that because nums of I is 10 to the fourth the other possibility is um dynamic programming right that may be probably the easier way to think about it I mean that way to meet in the middle um if we have to maybe we can do it but yeah I think that should be fine yeah uh this is kind of still tricky with dynamic programming I mean it's not it's actually that not that bad I think I could do dynamic programming it's just tricky for me to explain it I'm trying to figure out way uh the queen way to explain it um but I think it should be okay to be honest right so all right I mean I think we could just do uh BR force or not brof force but memorization but with the idea Bo Force so let right so then now we can do something like um and for this one because it is a hard I don't know how many people watch as a beginner let me know in the comments because I kind of struggle sometimes about like how much to um or like the level to explain these problems um so and for today given that this is a dynamic program problem I'm not going to do the dynamic Pro I'm not going to explain memorization b or rather I'm not going to explain basic memorization I do that a lot on my daily videos already at least in the past so this time today I'm just going to be a little bit lazy and not focus on that because that's not the interesting part about this problem I think but yeah but maybe I will I don't know we'll see how that goes but basically if you want to write Pro Force you might have something like uh possible I don't know uh the index of the number like basically how many I used um the current total and then the number of items that are used in the total right now used to say and in that case uh let's kind of think about this for a second right index could be 30 obviously total can be uh like we said um 30 * 10 total can be uh like we said um 30 * 10 total can be uh like we said um 30 * 10 what it 10,000 well this is just 10,000 sorry 10,000 well this is just 10,000 sorry 10,000 well this is just 10,000 sorry 10 to 4 and use this also up to 30 so then that means that this can go up to 9 million um oh wait this I'm really wrong total is way than that right total is the sum of 30 numbers so it's actually that's why I said it that way but then I kind of confused myself uh is that yeah so it's this right though not all of them is possible so in theory in actuality um is that now all of them are kind of possible because you have dir numbers then you can just have um you know you get I'm just all the powers of twos then that would be the summation of 1 + 2 + three or 1 2 4 to summation of 1 + 2 + three or 1 2 4 to summation of 1 + 2 + three or 1 2 4 to 300,000 and then 300,000 and then 300,000 and then 300,000 300,000 300,000 times like 10 20 uh because then it'll be doubling until um well until 3 200,000 what is until um well until 3 200,000 what is until um well until 3 200,000 what is that is basically 20 doublings no it's like s 16 doublings so then it's 16 * like s 16 doublings so then it's 16 * like s 16 doublings so then it's 16 * 300,000 um or 17 * 300,000 because of 300,000 um or 17 * 300,000 because of 300,000 um or 17 * 300,000 because of the doubling so then it is a lot right but anyway but yeah so this actually comes up to be a lot so this would actually not be a reasonable way to do this right because now um yeah do I have to really do meat in the middle for this one maybe I do I kind of missed a cuz in my head missed uh timesing this by Dirty I think when I first finish and then I also missed the used part a little bit but cuz I was thinking about it up bottom top but maybe we have to do um meet in the middle right how would meat in the middle work it's not a easy meet in the middle either um we also double check two to the 15 what's two to the 15 again like 32,000 I what's two to the 15 again like 32,000 I what's two to the 15 again like 32,000 I guess that should be okay I mean no me in the middle would work if I could figure out how it works exactly with averages is there any other way of doing it h is there another DP that's not napsack that was my first intuition but well I okay maybe I have to play around a little bit with what the average means a little bit because I think I have some in my head right so basically average is just equal to sum of a over count of a obviously right um and then you have sum of B is over count of B so then basically you have sum of a time count of B is equal to sum of B time count of a right and then basically we can convert this to n minus count of a right something like that does that help us um so this fun this thing should be equal to the other thing and of course sum of B is just equal to Total sum minus sum of a does that help don't know let's multiply that out right so sum of a * n minus sum of a * count of a sum of a * n minus sum of a * count of a sum of a * n minus sum of a * count of a is equal to Su total sum minus sum of a * count of a um I think the sum of a * count of a um I think the sum of a * count of a um I think the sum of a times count of am I doing this right oh uh this actually times count of a on this side oops um but in any case I think this part kind of cancels out right so let me just write on the next line so I don't know I'm really bad at doing this on here I'm usually better at paper so maybe I'm just confusing this but okay right then we have this I mean now it is kind of clear what that means right oh I mean this is a property that to be honest I did not realize when I started writing this so it just means that the average is equal to well the average of the entire frame which is a property that I did not think about because basically it's just saying that the average of a is equal to average of B then there average of the entire frame so that means that now we have an idea of what we want the Tet to be right so then now it becomes a different thing right because then now we have sum is equal or you know let's just say total equal sums of nums then now what does that mean that means that we can try we could Pro there's only dir numbers right so we can try if this is one then we know what sum a needs to be if this is two we know what sum a needs to be so forth right because then now so then we can prove for or we can like basically we can say is there one number with the average total Over N is there two numbers with the and then so forth right and here you can rewrite this as one number with this as the sum right this and two numbers is this times two as the sum right that's sum so then now we don't have to deal with the average anymore well I mean one number obviously is just one but you get the idea okay this is actually a fun problem and you know I did not know how to solve this before I had some ideas in my head obviously of some Impressions but I didn't think about doing it this way so this is a fun Evolution for sure kind of an interesting problem okay right and that's pretty much it then right because then now this becomes a really straightforward um a straightforward um whatam I call it sorry I got stuck in my head uh a straightforward nap thing right that we kind of had before um with fewer States well one is pretty straightforward I'm trying to convince myself that I'm trying to make sure that what I'm saying is true I think that's what I'm doing now um so dirty choose I mean this is dirty choose two is pretty straight for D choose three is pretty straight for what's What's d choose 15 again I guess that's a big one do choose I guess I need Google choose 15 is uh you do choose 15 is only 155 million which actually is a little bit slow so we won't do it that way but inferior is almost close enough to do and also with this way the um the meat in the middle is actually pretty straightforward as well I mean the napack I can un I can see but so okay so the other thing I want to point out is that it stops at is there n/ two numbers sums to average there n/ two numbers sums to average there n/ two numbers sums to average total time n / two because then total time n / two because then total time n / two because then after this um if one number sums to average of n it also implies that um n minus one other numbers sums to dot right so we only have to Loop this to n /2 which is to say that now if this to n /2 which is to say that now if this to n /2 which is to say that now if we look at our earlier thing we only have to go to 15 so we only have to sum to 15 numbers right so then now basically if we had our thing earlier of possible uh index total count or something like this I forget or used um now we reduced it to index is equal to well still up to 30 uh total it you only some 15 numbers so then now it's instead of uh so it's this times 15 instead oftimes 30 and then used only goes up to 15 so then now what is this fast enough time 15 * 15 is this fast enough time 15 * 15 is this fast enough time 15 * 15 times 10,000 all right so that is 67 times 10,000 all right so that is 67 times 10,000 all right so that is 67 million so still a little bit too much even though a lot of them are not as possible and because we go up to 150,000 um a lot of them are not should 150,000 um a lot of them are not should 150,000 um a lot of them are not should not be possible so it could I think it probably is more borderline even though it's possible uh was it 60 what did I say 67 million or something uh so this is you know 67 million States um but lazy math right because technically speaking it's going to be like the summation of all these things so um so it's actually a little bit less so it's or a lot less really because it only goes up to 15 um you choose a power of two FR then it kind of saturates pretty quickly or pretty um like the first 10 doesn't do anything really I don't know I mean I think maybe we can YOLO and go for this but uh but let's think about divide it in the middle right so uh divide in the middle we have two to the 15 possible things um and then we can B research so that should be like probably the way we want to do it 2 to the 15 is 32,000 and then log it 2 to the 15 is 32,000 and then log it 2 to the 15 is 32,000 and then log base is like times 15 maybe and that should be good so I think that's the way we'll do it um but yeah really annoying prom uh not something that you would do in an interview I mean it's me about 16 minutes to kind of come to this conclusion this is a very fun observation to make to be honest uh and so I don't know it's kind of fun I like it I dig it um but yeah let's do the so if you want to go I'm not going to talk about this too much um I'm just it's more of a it doesn't it's not that interesting of an algorithm it's so limited in use but it comes up um randomly like here but uh um I don't even Advocate learning it just because it just like when is it ever going to come up not much to explain it's just doing it in a way such that basically instead go two to the power you two make two sets of enters and then fin a resarch on them so that you can yeah maybe yeah okay so here maybe I'm use maybe not yeah I'm just going to use the B Mas but please um I have watched my note level but still I gu have sure anyway all right I'm going to use bit mask I'm not going to explain it in this video there's already enough conversation problem um if you don't know it you should not work on this I hope that doesn't come off as I just mean like you could work on others that kind of because this is not that for you but you know you want to watch but and basically yeah now we do for right I guess this is the for way of course if you put in the entire way it's going to that's then what you want to do is and right and then here we'll just it out yeah basically now it's 16 and half two three four and then it just possible and this is the dictionary of the count and then and they're not I don't think they are in order I mean in this case it is just because it is another lucky but okay right so then now we have this thing and basically what the idea here is okay so for um I don't know for I in range of left right so then now we look at and then now Bally um z i gu they could be they can't both be basically you're just combining basically just piing I from the left and J from the right side that's what it's say so now what is the target goal right so the target goal here have we have n over total sorry total Over N is what we fin reach um it's equal to some sum some number some i j that's number right i j on the other side and basically now I X is the sum that we're looking for just like right so yeah have to do a couple things basically a whole number so if pho possible that's number we're searching for then now for left values and now we're going to search from J we're going to search for x so I guess it's oh no and oh okay so the same way that this cannot be zero it cannot be that's and um not a super fast solution pretty okay solution uh yeah this is in the middle everybody take this form but actually to be honest I enjoyed it is there easy DP okay I don't I wonder like in the past the B are tighter or like less tight because I don't know how work yeah I don't think because we did the analysis I mean and like maybe I thought yeah this is basically what then now I kind of do but it's just like don't know I mean this part is part that figure I see I mean this is basically the same way that we have I don't know well I mean no the way that they do is don't I think yeah I don't think I don't know what the intended to hon it seems like a lot of people did DC but that me in the middle require all this stuff sometimes yeah finding this part is maybe I don't think I mean we did it a little bit differ all right uh that's what I have for this one I actually like this Farm it's kind of fun but I also think it's not a good interview farm interiew farm I don't think in the middle is an want to learn comes up kind of that's all I have for this one let me know what you think very good so help to the mental health have a great recipe we
Split Array With Same Average
escape-the-ghosts
You are given an integer array `nums`. You should move each element of `nums` into one of the two arrays `A` and `B` such that `A` and `B` are non-empty, and `average(A) == average(B)`. Return `true` if it is possible to achieve that and `false` otherwise. **Note** that for an array `arr`, `average(arr)` is the sum of all the elements of `arr` over the length of `arr`. **Example 1:** **Input:** nums = \[1,2,3,4,5,6,7,8\] **Output:** true **Explanation:** We can split the array into \[1,4,5,8\] and \[2,3,6,7\], and both of them have an average of 4.5. **Example 2:** **Input:** nums = \[3,1\] **Output:** false **Constraints:** * `1 <= nums.length <= 30` * `0 <= nums[i] <= 104`
null
Array,Math
Medium
1727
215
hello everyone welcome back here is vanamsen today we are diving into a super interesting coding problem number 250 key largest element in an array so it's a daily lead code Challenge and also its classic problem very common on uh coding interview so make sure to stick around till the end okay so uh here is the test guide we need to find the key largest element in an unsorted array so sounds simple right but there are multiple ways to solve this problem and today we'll focus on the most straightforward one the sort and select approach all right so app if we are given for example this Ri so from 3 to yep three two one five six four and key is to so task is really simple because we need to Output the key uh largest element so key largest element so second largest in this case is a five so it's second largest and the first largest is obviously six so we'll return five okay so really simple test and implementation could be also really simple so return sorted num reverse through key minus one so this is implementation one line of code we are sorting and picking a key number and because all right is zero indexed we are picking key minus one so as you can see for this array and key two output is 5 so all good so uh now let's break this down step by step so the core idea here is quite simple uh all we are going to do is sorting the number in the standing order and then just picking the key element so it's super intuitive and starting with the python built in a sources function we sort the list num in reverse order that means the largest element will be at the front of our list and then the magic happened with a last line or last part of one line code so key minus one and remember in programming our indices start from zero so to get the key largest element we need a index key minus one so basically the second largest number for example when a key is two is on index one so this way key minus one so uh so it's really a simple and time wise we are looking at n log n time complexity which is typical time complexity for sourcing a list of n elements and space so space complexity is just oh one so constant space complexity so that's because we are merely sorting the original list without using any extra space so all right let's give the test for unsynthesis cases as well uh so hopefully it will work so yeah as you can see it worked all good and our implementation uh still bit 98 other runtime so 99 88 and 84 with respect to Mineral but uh it's thanks to built-in uh sort in it's thanks to built-in uh sort in it's thanks to built-in uh sort in Python uh so yes uh that's the beauty of this approach real Simplicity uh combined with efficiency of course there are other methods to solve this and if you are interested check out the description below where I have provided code in multiple languages including C plus Java rust and go and much more and also I will cover other implementation with hip so if you found this video helpful make sure to hit the like button and share it with your friends and subscribe for more uh coding challenges and tutorials and as always keep practicing happy coding and
Kth Largest Element in an Array
kth-largest-element-in-an-array
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element. You must solve it in `O(n)` time complexity. **Example 1:** **Input:** nums = \[3,2,1,5,6,4\], k = 2 **Output:** 5 **Example 2:** **Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4 **Output:** 4 **Constraints:** * `1 <= k <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
Medium
324,347,414,789,1014,2113,2204,2250
621
everyone welcome back and let's write some more neat code today so today let's solve the problem task scheduler one of you suggested this problem and i think it's a pretty good one so we're given an array of tasks it's a character array and it's going to be limited to the characters from uppercase a to uppercase z so 26 characters each of the characters represents a task and the task is something that the cpu needs to process and the tasks could be processed in any order each task takes exactly one unit of time to process so that's good because it makes things simple for us and for each unit of time the cpu could either process an entire task or it could be idle and the reason it would be idle is because we're also given non-negative integer input n that non-negative integer input n that non-negative integer input n that represents the cooldown period between the two same tasks and the same task is represented by the same letter the same character in the array and to understand this let's take a look at an example and by the way what we actually want to return is the minimum number of units of time that the cpu will take to finish all of the tasks let's take a look at this example we're given these tasks right three a tasks and three b tasks and the idle time we're given is two units of time so basically let's say we processed an a task right that takes us one unit of time to process now we process a b task and now we know that before we process another a task we have to wait two units of time so you know let's say we process an a we can't process another a we have to wait two units of time before we can process another a so what are we gonna do in the meantime well there's a b as well so let's process one of the b's and now for this b we know we actually have to wait two units of time before we can process another b so the next time we can process another b will be at this point in time after we have processed our second a so now the question is can we fill this spot with anything or are we gonna have to be idle at this point in time and there aren't any other characters right we had one a and one b now we have two a's and two b's remaining so we can't do anything this has to be idle we process an a second a and a second b uh that means that before we can process another a is gonna be two units of time so this b and then another uh unit of time and then another a and we also process the b the next time we can process a b will be at this point in time so at this point again we are going to have to be idle but the good thing is that this is the entire um like all the tasks we were looking for three a's and three b's so as you can see it took us one two three four five six seven eight units of time to do this so our output is going to be a so now let's think about a general approach that we could come up with to solve this problem so let's say we had this as our input first thing to notice is we're going to be given characters a through z doesn't really make sense to worry about which character we're looking at right there's not really not a big difference between a b and a c but we should keep track of how many of each character there is so we know there's three a's two b's and two c's right we don't even have to worry about the characters anymore we can just focus on the numbers we know that there's three of one character there's two of a different character and then two of another character we know that the idol time in this case is one what order should we uh process the characters in it's probably better to process the more frequent character first the more frequent task first because we know there's going to be some idle time and processing the more frequent one first basically gives us more time to not be idle and i'll show you the intuition behind that let's say we did a c first right we do c uh we know that idle time is just one right so then let's say we do b and we're allowed to do another c right away let's say we do that right we do another c and uh then we do another b because we the idle times only one right so now we've already processed all the c's and the b's and all we're left with is three a's okay let's process one of the a's okay great but now we have an idle time we have no other characters available for us so we have to wait and then we can process another a and then we wait and then process another a so in this case this was one way but did this minimize the total time that it took us to process all the tasks a different way would have been to start with the most frequent character right a and now there's only two a's left so now what's the most frequent well you could say a again but we know that there is an idle time of at least one so at this point in time a is not available to us so we have to process a different character let's say a b then a is actually going to be available for us again so we could process the a or we could process the c in this case it doesn't really make any difference because there's two of each of these so we could do either one let's just do c so then there will be two a's one b and one c then we'll of course want to do the more frequent character the a and then there's gonna be one a remaining we can't process another a without at least one unit of idle time so let's do b and then do c and then we can do a right this also is a valid way and this one actually minimizes the idle time rather than this one and what is the idle time in this case it's about uh not the idle time the total time in this case is about seven as opposed to nine in the other case so that's kind of the intuition why we're going to try to do the more frequent task first and then the less frequent task how we're going to be doing this is by using a data structure called a max heap which will allow us to continuously figure out which task is the most frequent one and the max heap can actually allow us to determine that in log n time right if we have a bunch of these we could figure out which is the most frequent in log in time which is good but in this case actually it's even better than that it's about log 26 since we only have 26 different characters this is kind of a constant time operation anyway but i will say that the overall time complexity is still going to be big o of n one because we are gonna have to you know count the occurrences of each task so we're gonna have to go through the entire uh input and we're going to be you know popping every value from our max heap and adding every value to our max heap so the time complexity is going to be big o of n that's also going to be the memory complexity but now to the actual algorithm itself we're actually going to use one other data structure aq it's not required but i think it makes the problem a little bit more organized so let's start off with the max heap right we have three integers we're going to be adding integers to our max heap not the characters we're going to be taking the counts of each task and adding that to the max heap so we're going to have a three and a two and a another two and by the way when i actually code this up in python we don't have a native max heap so the way to we only have a min heap so the way i get around that is basically by taking each of these values and making it negative you know in a max heap we want to pop the maximum and we can do that in log n time so in this case we'd pop the 3 which is the maximum but in python we're actually going to do it the opposite way all of these are going to be negative so we're going to end up popping the minimum which is going to be negative 3 but we're going to you know assume that it's a positive 3. but yeah so that's the idea first we're going to pop the 3 or the negative 3. you can think about it however you want that's the most frequent but now we want to change the count from being a three to now being a two right because we just processed one of the tasks so you know if you have a negative you'll have to add one if you have a positive you can decrement it to one in my case when i write the code i'm going to be adding one to this but now we're actually going to be taking this and adding it to our queue data structure because we know that there's some amount of idle time for this task at the current point in time we are at initially we were at time equals zero but we just processed the task so now we're at time equals one and we're going to add this integer 2 or negative 2 to our q but we're also going to be adding another value to the queue and that's at what time is this task going to be available for us to process once again basically at what point can we take this and add it back to our max heap right what's the idle time that is going to be remaining well right now we're at time equals one and our idle time for each task is n equals one so basically we're gonna take n and add it to our current time so it's gonna be two basically at time equals two this task is gonna be available for us to add to the heap again so that's what the second value in this case means and once again we're going to pop from our max heap we're going to pop the negative 2 and that means we have processed the task so now our time is actually going to be time equals 2. we're going to take that task it was a negative 2. we're going to add 1 to it which is going to make it a negative 1. so then we're going to take that negative 1 and add it to our q and at what time is that task going to be available to add back to our max heap well it's going to be 2 plus 1 because n is 1 in our case so at time equals 3 this task can be added back to our max heap but now that we're at time equals 2 we see that this task actually is available now to add back to our heap so let's pop it from our q and take the negative 2 and add it back to our max heap and at this point you're probably starting to get the idea so i'll just kind of fast forward through this we're going to pop this again set our time now equal to 3. we're going to take that negative 2 add 1 to it so it'll be a negative 1. we'll add that to our heap at time equals 4 it's going to be available for us to add back to the heap this value can be popped from our queue we can add a negative 1 here and then start the cycle over so let's pop this value over here uh add it to our q we're running out of space so let's add a little bit more space uh that negative two will become a negative one the time now will actually be four so the time that this can be popped it's going to be at time five we see it's time for so this can now be popped so we add that back to our uh heap negative one and now it's time equals four so i'm really going to fast forward through this it'll take one more unit of time to process this task but now this task as you can see we're going to pop it's a negative 1 we're going to add 1 to it so now it's going to be 0 right 0 once a task becomes 0 we know that we don't have to process it anymore right so when it's 0 we're not going to add it to our q because it doesn't have to be idle it's never going to be added back to the max heap once it's zero we're not going to do anything with it so uh you know we pop it from our max heap and there's nothing left but we see that this value over here and right now it's going to be time equals five actually so time is five this can be added back to our max heap let's add that negative one sorry if it's getting a little bit messy but next we're gonna pop this from our max heap it's gonna become zero so we don't add it to our queue now it's gonna be time equals six after we process that task and lastly we have one task remaining we pop it we process it becomes zero we don't add it to the queue so now after processing that task our time is seven so we can return seven in this case and that's pretty much the entire algorithm so that's what i'm going to be following even though popping and pushing to a max heap is usually a login operation in this case it's really going to be a log 26 operation so the overall time complexity in this case is really just big o of n because we have to just go through every single task okay now let's write the code okay so now let's code it up and you can see i have a couple comments just to kind of help simplify things for us and i usually don't do this but we want to count the occurrences of each character in the input it's a list of strings we could just you know run through that loop through that and add it to a hash map but you can actually do that with a built-in way in python just using a built-in way in python just using a built-in way in python just using a counter which is literally a hash map it'll just do that for us so we don't have to write the code but now we actually want to create our max heap using those counts themselves uh we can do that in python with one line of code we're just going to iterate through each count in the hashmap that we just created but we want to only iterate through the values so count.values and we want to add that to count.values and we want to add that to count.values and we want to add that to our hashmap but in python's case we can't have a max heap this is actually a min heap after we heapify it so i'm actually going to take the negative of the count and add it so this is just creating an array with every negative count that we computed but to actually turn it into a heap we can do heapq.heapify in python and to that max heapq.heapify in python and to that max heapq.heapify in python and to that max heap and it'll basically order it'll take this array and order it in such a way that it is a max heap basically for us to efficiently get the maximum value from the heap whenever we want it we're also going to declare a variable to keep track of what time it is initially we'll set that to zero and we'll also have a q in this case a double ended queue and the double ended queue is gonna actually contain a pair of values and the pair of values are gonna be that negative count that we had up above and for that uh you know task that count the corresponding idle time at what time is it going to be available for us to add back to the max heap okay so with that said we're gonna continue uh our loop we're gonna continue processing these tasks while the max heap is non-empty but end or not the max heap is non-empty but end or not the max heap is non-empty but end or not and but or the cue is not empty right as long as one of these is not empty that means we have more tasks that we need to process so as we process each iteration of the loop is just going to increment the time by exactly one and actually before i even forget i mentioned that the time complexity of this whole algorithm is going to be big o of n but that's not entirely correct let's say n is the size of our tasks we can add one more variable let's call it m where m actually represents what the idle time is because in the worst case you know we have to go through that idle time for each task that we have write suppose that the tasks was just an array of all a's in that case we'd have to you know go through the idle time for each task but the idle time is actually a pretty small constant i think it's less than 100 in our case but just wanted to mention that in case but okay now let's continue with the algorithm so at each iteration of loop we're going to increment the time by one if the max heap is non-empty we by one if the max heap is non-empty we by one if the max heap is non-empty we are going to pop from it and we can do that with heap q dot heap pop from the max heap and from it we're gonna get the count and as we uh pop from the heap that means we're processing this task so to the count itself we can actually add one to it because remember we're actually using negative values for the counts if you were using positive values you'd probably subtract one from it but in our case we're going to be adding one to it and if this count is non-zero we to it and if this count is non-zero we to it and if this count is non-zero we can check that uh like this if count is non-zero then we want to go ahead and non-zero then we want to go ahead and non-zero then we want to go ahead and append it to our queue and we can do that like this we're gonna append a pair of values the count itself and the time that it's going to be available again and we can get that by taking our time our current time adding to it the idle time n so at this time we can once again add it to our maxi okay that's great we process a task we remove it from the max heap but remember we also have to take care of our queue if our queue is non-empty and the first value in our non-empty and the first value in our non-empty and the first value in our queue at index 0 the idle time for it which is also it was actually going to be at index one because it's the second value in the pair so if this time has just been reached so if this is equal to the current time that means you know we can actually pop this from our queue so we're going to say q dot popped left and so this is actually going to pop that pair of values and from that pair of values we care about the first one which is the count so we're going to get an index of zero but actually that value itself what do we want to do we just want to add it back to our max heap so we can do that with heap cue.heat push we can do that with heap cue.heat push we can do that with heap cue.heat push we're going to take it add it to our max heap so let's just copy and paste this and uh move it up above so the only thing left for us to do is once everything has been processed for our max heap and our queue we can just go ahead and return the time that it took us to do all that work let's just clean this up a little bit that's the entire code so now let's just run it to make sure that it actually works and as you can see on the left yes it does work and it's pretty efficient i do want to mention there actually is a different solution for this that's actually a little bit more of a true linear time solution but i think it's a lot less intuitive and i think this solution is perfectly fine for interviews and because it's more of an intuitive solution i think this is more or less what interviewers would expect you to come up with so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Task Scheduler
task-scheduler
Given a characters array `tasks`, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle. However, there is a non-negative integer `n` that represents the cooldown period between two **same tasks** (the same letter in the array), that is that there must be at least `n` units of time between any two same tasks. Return _the least number of units of times that the CPU will take to finish all the given tasks_. **Example 1:** **Input:** tasks = \[ "A ", "A ", "A ", "B ", "B ", "B "\], n = 2 **Output:** 8 **Explanation:** A -> B -> idle -> A -> B -> idle -> A -> B There is at least 2 units of time between any two same tasks. **Example 2:** **Input:** tasks = \[ "A ", "A ", "A ", "B ", "B ", "B "\], n = 0 **Output:** 6 **Explanation:** On this case any permutation of size 6 would work since n = 0. \[ "A ", "A ", "A ", "B ", "B ", "B "\] \[ "A ", "B ", "A ", "B ", "A ", "B "\] \[ "B ", "B ", "B ", "A ", "A ", "A "\] ... And so on. **Example 3:** **Input:** tasks = \[ "A ", "A ", "A ", "A ", "A ", "A ", "B ", "C ", "D ", "E ", "F ", "G "\], n = 2 **Output:** 16 **Explanation:** One possible solution is A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A **Constraints:** * `1 <= task.length <= 104` * `tasks[i]` is upper-case English letter. * The integer `n` is in the range `[0, 100]`.
null
Array,Hash Table,Greedy,Sorting,Heap (Priority Queue),Counting
Medium
358,778,2084
403
hello everyone welcome back here is Van Amazon and today we are diving into a fascinating problem on uh lead code the frog jump problem so you will understand the logic behind the solution and how to implement it in Python and for those of you who prefer other languages don't worry I will provide implementation in the description below so all right let's quickly go over the problem statement so the task here is simple we have a river divided into units and at each unit there might be a stone and our frog can only jump on Stones not in water and the Frog starts on the first stone and the initial jump is always one unit and after that if the Frog last jump was a key units its next jump could be a key -1 key or key plus uh one so the goal is -1 key or key plus uh one so the goal is -1 key or key plus uh one so the goal is to determine if the Frog can cross the river by landing on the last uh Stone so let's take some examples so example number one we are given a stand position so it's zero one three five six eight twelve and Seventeen and our frog starts at position 0 and it first jump one unit to position one then two three and two you need five and so on and the Frog eventually lands on the last stone at position 70. so the answer here is true so now that we got a grasp on the problem let's start coding our solution so uh the approach I'm taking here is using dynamic programming so for each Stone position we'll keep track of all possible jump distance that can land the frog on that stone so at the beginning of our frog is at position zero and can only jump one unit so we initialize our DP dictionary with the first stone position as set containing the value 1. so let's implement it DP and 4 Stone in stones DP Stone will be set and DP at zero at one so and now for istan in our list we will iterate through all possible Jam distance record in our DP dictionary and for each possible jump distance we will calculate the next Stone position so if this next Sun exists in our list we will add the possible jump distance to its set in the DP dictionary so for stone in stones for key in DP Stone next Stone will be Stone plus key and if next Stone in DP if key minus 1 greater than zero DP next turn at Key minus 1 and DP next turn key and DP next turn will be at Key plus one and return line of the Piston greater than a zero admin minus one so the final step is to check if there are any jump distance recorded for the last Stone so if there are it means our Vlog can reach the last tone so let's run this implementation so hopefully it will work okay so type for stone in Stones so yeah all good and now uh let's submit it for unsynthesis cases as well so it's running and yep as you can see uh it bit 80 with respect to random and also 81 with respect to a memory and work for all test cases and uh it's a beautifully combination of both dynamic programming and set operation and time complexity is quite acceptable so it's all n square and for the problem constraint and at this wrap up our solution for the frog jump problem and I hope you found this session insightful and for those of you looking for implementation in other programming languages uh Link in the description below and if you enjoyed this session don't forget to hit the like button sure eat with your friends and of course subscribe for more coding content and leave your thoughts and question in the comment section below and as always keep practicing happy coding and see you next time
Frog Jump
frog-jump
A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of `stones`' positions (in units) in sorted **ascending order**, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be `1` unit. If the frog's last jump was `k` units, its next jump must be either `k - 1`, `k`, or `k + 1` units. The frog can only jump in the forward direction. **Example 1:** **Input:** stones = \[0,1,3,5,6,8,12,17\] **Output:** true **Explanation:** The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. **Example 2:** **Input:** stones = \[0,1,2,3,4,8,9,11\] **Output:** false **Explanation:** There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. **Constraints:** * `2 <= stones.length <= 2000` * `0 <= stones[i] <= 231 - 1` * `stones[0] == 0` * `stones` is sorted in a strictly increasing order.
null
Array,Dynamic Programming
Hard
1952,2262
118
all right so this leap code question is called Pascal's triangle it says given a non-negative integer num rows generate non-negative integer num rows generate non-negative integer num rows generate the first num rows of Pascal's triangle in Pascal's triangle each number is the sum of the two numbers directly above it so if you take the number two it's the combination of 1 and 1 if you take the number 3 it's the combination of 1 and 2 if you take the number 6 it's the combination of 3 and 3 so the example is an input of 5 and what we get is a triangle made up of arrays with 5 rows with as we said before each number being the sum of the two elements above it all right so this is Pascal's triangle it's just a series of numbers where each row is made up of numbers that are themselves made up of the two numbers in the row above them so when I first try to solve this problem I try to come up with some crazy formula but it turns out a lot of it is just manual and I'll show you what I mean so let's start with the first row all we have to do is manually add an array with the number 1 in it and then with every row from then on the ones that we're seeing they're all gonna be added manually let me just undo all that so with this row what do we manually add the number 1 another thing to note is that the number of elements between the ones is always 1 less than the row count above it so let's take this number 2 there's one element between these ones and the row above it is row 2 two minus one is one let's go to the next row which row is above the row with the 3s in it's row three so how many elements are in between the ones in this row 3 minus 1 which is 2 and let's go to the final row which row is above this through a 1 2 3 4 so how many elements are between the ones in this row 4 minus 1 which is 3 all right let me undo a bunch of that to not make it messy knowing that how many elements are going to be between the ones in this row the row above it is Row 1 what's 1 minus 1 0 so they're going to be 0 elements in between the ones in this row so like I said all the ones we're seeing are manually added so when we're done doing the calculation we just did we just manually add a 1 at the end of this row now let's go to the next row remember the first thing to do is to just manually add a 1 now how do we get the next element let's see if we can find a pattern we know the next element is going to be a combination of these two numbers the indices of these two numbers are 0 &amp; 1 the index for the numbers are 0 &amp; 1 the index for the numbers are 0 &amp; 1 the index for the number we need is 1 so we know that the elements that we need to add are always the elements in the row above with the indices of 1 less than the index we're on so right now we're on index 1 so we need index 0 and the element with the same index so the elements 0 &amp; 1 add up same index so the elements 0 &amp; 1 add up same index so the elements 0 &amp; 1 add up to 2 now what do we manually add the number 1 let's do it one more time so new row manually add the number 1 which has an index of 0 how many elements do we need between to number ones in this row the row above it is Row three so you subtract one from that which means you need two elements between the ones so we're going to need an element at index one and an element at index two and as we know now we look at the elements in the previous row with an index one less than the index were on and an index of the same index were on so we're on index one so we need indices zero and one and that'll be three same logic for the next one we're at index two so what do we need to add up the index of 1 less than we're on + 2 which is the index we're on + 2 which is the index we're on + 2 which is the index we're on what does that come out to it also comes out to the number 3 and then finally since we've added all the elements between the ones we now just manually add the last number 1 so let's clean this up a bit so this is what our array would look like so far all right so let's start out with what lead code has given us it's a function called generate and it accepts a variable called num rows which represents the number of rows our Pascal's triangle needs to have all right let's start out this way the way our triangle is represented is actually just an array so that's what we're going to return at the end what we have to do with this array is push in arrays inside of it and each array we push in can be looked at like a row so in the end this is what it actually looks like but more in the Pascal's triangle form this array would have a row count of two ignore the opening and closing brackets alright so now that we've said that will create a new variable called triangle and we'll make it the empty array next we'll check the numbers variable that's passed in and if it's zero then we'll just return the triangle as it is now which is empty so if num rows is zero then the triangle has no rows so we'll just return the empty array so return triangle all right now we'll do our first manual step which is to manually create the first throat so what we'll do is we'll say triangle dot push and what are we pushing the first row only has one element in it of the number one all right let me do some cleanup before we move on at this point this is what our triangle looks like alright now we need a for loop to populate each row so we'll say for let I equal 1 usually we started I equals 0 but we already have our zeroth row and that's just the number 1 that's represented to the left so we'll do i is less than numbers and then i plus a pretty standard for loop now remember one of the keys to solving this problem is to look at the row in front of us so we would need a reference to that row so let Prevot equal triangle i minus 1 right now this is the previous row so this is the row we're talking about all right and now we have to create a new row so let new row equal an empty array this is what we have so far all right now comes another manual step remember we are manually adding the number one at the beginning and at the end of each row so we need to add the one at the beginning so new Rho dot push the number one so that'll be this now we need to populate the interior of each row and the way we do that is with another for loop so for let and we'll create a variable J this time equal one why is it one when we usually start at zero it's one because we already have an element at the 0th position of our new row and that element is always the number 1 so now we just stop when J is less than the length of the previous row and then we do J plus another pretty standard for loop in the row we're on now this loop actually isn't going to do anything it's going to be skipped why is that because J is 1 and we're saying we go until J is less than the previous rows length is 1 so we can never enter this loop and will only enter if J is more than 1 but we still have to populate it for future rows so remember we said that every element in this step is just a sum of the two elements above it one being the one with the index one less than it and one with the same index as it so that'll look like neuro dot push the previous row J minus 1 plus previous row J so again let's pretend real quick that the previous row was I don't know 1 2 1 the indices are 0 1 2 the array below it would need the indices 0 1 2 3 index 1 will be made up of index 0 &amp; 1 above it will be made up of index 0 &amp; 1 above it will be made up of index 0 &amp; 1 above it and index 2 would be made up of index 1 &amp; 2 above it so it's always the index &amp; 2 above it so it's always the index &amp; 2 above it so it's always the index were on minus 1 plus the index were on ok so let's just get rid of that to make it cleaner ok so now we're done with that for loop what do we do next this is just another manual step we already pushed in the number 1 at the beginning so now we have to finish it off by pushing in the one at the end so a new row dot push the number 1 so that'll be this and the final step in this for loop is even though I've drawn it so far to make it look like our tray fits into the outer array it actually hasn't so far it's really been like this with our array not being inside of it yet so the final step is to push our array into the outer array so that'll be triangle which is the outer array push the new row we just created alright so now that for loop would go for as many times as the rows that we've passed in and what's the final step it's to just return the triangle array which would be this whole thing okay let's test the code oh I missed parenthesis try it again looks good submit alright so the answer was accepted it was faster than about 19 percent of JavaScript submissions as usual the code and written description are linked down below if you like the video just give it a like and subscribe to the channel see you next time
Pascal's Triangle
pascals-triangle
Given an integer `numRows`, return the first numRows of **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** numRows = 5 **Output:** \[\[1\],\[1,1\],\[1,2,1\],\[1,3,3,1\],\[1,4,6,4,1\]\] **Example 2:** **Input:** numRows = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= numRows <= 30`
null
Array,Dynamic Programming
Easy
119
682
everyone welcome back and let's write some more neat code today so today let's solve the problem baseball game even though this has practically nothing to do with baseball maybe that's why it has so many dislikes because other than that i think it's a pretty good problem it's very logical there's no crazy tricks behind it but i'm just gonna skip the first paragraph because it's pretty useless if this problem teaches you anything it's basically how to kind of filter out the unnecessary information when you're reading a problem which is actually a somewhat useful skill so at the beginning of the game we start with an empty record we're given a list of operations where each of the operation could be one of the four following it could be some integer given in the form of a string as you can see they don't really mention that but yes it's given as a string in this case there's five there's two now they mention at the bottom of the problem that the integer itself could be i think a value somewhere between negative a thousand and positive a thousand so it might not just be one digit so you have to kind of keep that in mind but the other three operations are one is a plus symbol what that means is we're going to add the two previous scores that we were given in operations together and we're guaranteed that there are going to be at least two previous scores so one thing we're kind of learning is that we're going to need to kind of memorize what the previous scores were at least two of them and the third one is a d that means we're gonna double the previous score the single previous score and it's guaranteed that there will be at least one previous score the last one is going to be the letter c which means we're gonna invalidate the previous score basically removing it from the record now what this means is we can't just keep track of the two previous scores we have to keep track of all of them because what if we have a ton of c's in a row that means we have to invalidate the previous one then the next one and keep doing that this kind of hints to us since we're going to be adding scores and removing scores a data structure to do that is going to be a stack because as we add we're going to be adding to the end of the stack as we remove in this case we're also going to be removing from the end of the stack so a stack data structure we can do both of those operations in big o of one time after we've gone through every operation what we want to do at the end is just take the sum of all of the scores and return it so if you couldn't tell before yes we definitely need to keep track of every single score so that we can at least sum it at the end so now let's just quickly run through this example and then let's code it up so first we're just going to iterate through all of the operations starting at the beginning so this time we have a five what we can do in the code is first just check is it a plus nope is it a d nope is it a c nope so that must mean it's an integer that's probably the easiest way for us to detect that otherwise we could use some kind of built-in function to check if kind of built-in function to check if kind of built-in function to check if it's an integer but it's easier to just have this be the else case so it's a five so what we do is keep track of it we're gonna record it we have a five next we get another integer two let's record it and then move on next we get ac what do we do when we get a c we invalidate the previous score so to do that we're going to do a very simple pop operation on our stack so we're invalidating the last one so as so at the end when we sum all of the scores we're not going to include this one next we get to a d means we're going to double the previous score now the previous score is not 2 because we invalidated it the previous one is going to be 5. we'll know that because we're just going to take the top of our stack which is gonna be five so we're gonna take double five and we're gonna add 10 to the stack last we have is a plus means we're going to take the sum of the two previous scores we're guaranteed to have them and we do have them we have a 5 and we have a 10 we take the two previous ones add them together we get 15 and then we add 15 to the stack now and that's it we went through every single one of these so this is our stack we have three values what we're going to do is add all three of the values together we're going to get a total of 30 and then that's what we're going to return and that's exactly what they expected so now let's code it up okay so now let's code it up first we're going to just initialize our stack it's going to be empty initially and then we're just going to go through every single op in the input array and then just kind of write out the if statements we know that one is a plus another one is if we have a d and another one is if we have a capital c and then the last one is just going to be the else case where we have a number so if we had a positive that means we're going to take the sum of the two previous scores and add them together so we're guaranteed that they exist in python you can get the last value in an array or a stack by taking the negative one index or we could take the length of the stack minus one and to get the second to last one we can take a negative two index or we could just take the length of the stack minus two either way you can do it but this is easier in python we're gonna take the sum of those and then append that to the stack so that covers that case if we have a d we're going to take double the previous value so to get the previous value similarly we're just going to take the negative one index and then we're going to double it so two times that and then we're going to append that to our stack so also not too bad and then the last uh the c case is where we're invalidating the previous one so we're not adding to the stack this time we're popping the last value that was added to the stack and then the last case is suppose that op happens to be a number so this time we're actually using off we're going to take up and we're going to come uh convert it from being a string into being an actual integer somewhere between negative a thousand and positive a thousand and then we're gonna append that to our stack after we've gone through every operation and done that all we need to do is take the sum of our stack so now let's run it to make sure that it works and as you can see on the left yes it does and it's pretty efficient so the overall time complexity was big o of n because we're just iterating through every single input and yes we might be adding to the stack and we might also be popping but we're only going to pop as many values that we could have added to the stack so it's going to be big o of n where n is the size of the input array and of course we're taking the sum of the stack at the end but that's also a big of n time operation so the overall time complexity is bigger of n the memory complexity is also bigger of n because we have the stack and the stack could be of size that's the same as the input array so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Baseball Game
baseball-game
You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record. You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following: * An integer `x`. * Record a new score of `x`. * `'+'`. * Record a new score that is the sum of the previous two scores. * `'D'`. * Record a new score that is the double of the previous score. * `'C'`. * Invalidate the previous score, removing it from the record. Return _the sum of all the scores on the record after applying all the operations_. The test cases are generated such that the answer and all intermediate calculations fit in a **32-bit** integer and that all operations are valid. **Example 1:** **Input:** ops = \[ "5 ", "2 ", "C ", "D ", "+ "\] **Output:** 30 **Explanation:** "5 " - Add 5 to the record, record is now \[5\]. "2 " - Add 2 to the record, record is now \[5, 2\]. "C " - Invalidate and remove the previous score, record is now \[5\]. "D " - Add 2 \* 5 = 10 to the record, record is now \[5, 10\]. "+ " - Add 5 + 10 = 15 to the record, record is now \[5, 10, 15\]. The total sum is 5 + 10 + 15 = 30. **Example 2:** **Input:** ops = \[ "5 ", "-2 ", "4 ", "C ", "D ", "9 ", "+ ", "+ "\] **Output:** 27 **Explanation:** "5 " - Add 5 to the record, record is now \[5\]. "-2 " - Add -2 to the record, record is now \[5, -2\]. "4 " - Add 4 to the record, record is now \[5, -2, 4\]. "C " - Invalidate and remove the previous score, record is now \[5, -2\]. "D " - Add 2 \* -2 = -4 to the record, record is now \[5, -2, -4\]. "9 " - Add 9 to the record, record is now \[5, -2, -4, 9\]. "+ " - Add -4 + 9 = 5 to the record, record is now \[5, -2, -4, 9, 5\]. "+ " - Add 9 + 5 = 14 to the record, record is now \[5, -2, -4, 9, 5, 14\]. The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27. **Example 3:** **Input:** ops = \[ "1 ", "C "\] **Output:** 0 **Explanation:** "1 " - Add 1 to the record, record is now \[1\]. "C " - Invalidate and remove the previous score, record is now \[\]. Since the record is empty, the total sum is 0. **Constraints:** * `1 <= operations.length <= 1000` * `operations[i]` is `"C "`, `"D "`, `"+ "`, or a string representing an integer in the range `[-3 * 104, 3 * 104]`. * For operation `"+ "`, there will always be at least two previous scores on the record. * For operations `"C "` and `"D "`, there will always be at least one previous score on the record.
null
Array,Stack,Simulation
Easy
1720
157
yo whatsapp vyas going students should be given all circulars question which is the read and tagged as given read most loudly okay what is this is like and he is the question like and subscribe this Video give a video liquid liner person subscribe problems - Abdominal Total and Guys So problems - Abdominal Total and Guys So problems - Abdominal Total and Guys So Lutab Skin Thing Examples Click on the like button subscribe and don't forget to subscribe this channel and subscribe my channel subscribe hotspot of account wounded the value from the end poor 500 99999 likes for creative they can Love you like this is my favorite song new kya hai and number five I will clear like total number of but if they continue it is 0.1 total number of but if they continue it is 0.1 total number of but if they continue it is 0.1 total this is fixed total number of but if video 9th step people rule swine flu and should not doing this You should delete and ok that agar noida will calculate deactivate eligible account for advertisement bhavya help does not matter if they compare account to man - man - man - that sorry point no what do it i will benefit my distemper active valley hotels look like a that i plus channel Lots of total plus it is exempted a taboo 548 not seen in defiance of water and of the lambs pet services replacement for play subscribe that if source code so what is due to have adopted in under temple run ok in over her mistake is greater noida Press Club At Its Okay My Channel Subscribe Abs Who Is The Value Of The Subscribe And Subscribe The Amazing Bhi Kidar Hai A Boom Help 200r In This Question Time Complexity Of Android My Space Complexities Of Saunf This Question Screamed Use Channel To Subscribe Take Care See You In Next Video Song Subscribe Button Love You By
Read N Characters Given Read4
read-n-characters-given-read4
Given a `file` and assume that you can only read the file using a given method `read4`, implement a method to read `n` characters. **Method read4:** The API `read4` reads **four consecutive characters** from `file`, then writes those characters into the buffer array `buf4`. The return value is the number of actual characters read. Note that `read4()` has its own file pointer, much like `FILE *fp` in C. **Definition of read4:** Parameter: char\[\] buf4 Returns: int buf4\[\] is a destination, not a source. The results from read4 will be copied to buf4\[\]. Below is a high-level example of how `read4` works: File file( "abcde `"); // File is "`abcde `", initially file pointer (fp) points to 'a' char[] buf4 = new char[4]; // Create buffer with enough space to store characters read4(buf4); // read4 returns 4. Now buf4 = "abcd ", fp points to 'e' read4(buf4); // read4 returns 1. Now buf4 = "e ", fp points to end of file read4(buf4); // read4 returns 0. Now buf4 = " ", fp points to end of file` **Method read:** By using the `read4` method, implement the method read that reads `n` characters from `file` and store it in the buffer array `buf`. Consider that you cannot manipulate `file` directly. The return value is the number of actual characters read. **Definition of read:** Parameters: char\[\] buf, int n Returns: int buf\[\] is a destination, not a source. You will need to write the results to buf\[\]. **Note:** * Consider that you cannot manipulate the file directly. The file is only accessible for `read4` but not for `read`. * The `read` function will only be called once for each test case. * You may assume the destination buffer array, `buf`, is guaranteed to have enough space for storing `n` characters. **Example 1:** **Input:** file = "abc ", n = 4 **Output:** 3 **Explanation:** After calling your read method, buf should contain "abc ". We read a total of 3 characters from the file, so return 3. Note that "abc " is the file's content, not buf. buf is the destination buffer that you will have to write the results to. **Example 2:** **Input:** file = "abcde ", n = 5 **Output:** 5 **Explanation:** After calling your read method, buf should contain "abcde ". We read a total of 5 characters from the file, so return 5. **Example 3:** **Input:** file = "abcdABCD1234 ", n = 12 **Output:** 12 **Explanation:** After calling your read method, buf should contain "abcdABCD1234 ". We read a total of 12 characters from the file, so return 12. **Constraints:** * `1 <= file.length <= 500` * `file` consist of English letters and digits. * `1 <= n <= 1000`
null
String,Simulation,Interactive
Easy
158
141
in this video we'll go over Lee code question number 141 link list cycle given the head to a linked list we need to return true if there is a cycle in the linked list or return false if there isn't one so what exactly is a cycle in a linked list well a linked list consists of nodes and pointers to the next node in the list and normally the last pointer points to a null value to Signal the end of the list but if instead of pointing to null the last pointer points back at some other node in the linked list there is now a cycle and if you try to Traverse this linked list you could keep traversing it forever and never reach the end so now the question is how can we detect a cycle in a linked list to solve this we'll be using an algorithm commonly known as The Tortoise and hair algorithm here's how it works we start by initializing two pointers a slow pointer and a fast pointer the slow pointer will Traverse the linked list one node at a time while the fast pointer will Traverse the linked list two notes at a time then if the two pointers and end up on the same node at some point then that means that a cycle exists so why does this work well think of two people running on a track with no Cycles if we let them run the faster one will eventually reach the end which for a linked list is the null value and we would know that there are no Cycles but if we put them on a circular track that does have a cycle then at some point the faster person would catch up to the slower one which means that they would be back at the same position again and so this is what we're looking for and it's how we know that a cycle exists now you may be saying this is an example of two things moving continuously but linked lists are made up of discrete nodes isn't it possible that the faster pointer could pass the slower one by skipping over it so that they never land on the same node well let's take a closer look at a few different scenarios to figure this out the first scenario here is that the fast pointer has made its way around and is now one node behind the slow one then at the next step both pointers would land on the same node and we're done the second scenario is that the fast pointer is two nodes behind the slow one then at the next step the fast pointer would be one node behind the slow one and now we're back to the first scenario where both pointers meet on the next step and it's the same idea no matter how far back you move the fast pointer at each step the distance gets reduced by one node until eventually both pointers land on the same node now let's look at the code and see how we can do this in Python we'll be using this definition of a linked list here each list node has two attributes Val which is the number you see inside each node and next which is a pointer to the next node in the linked list we are given a pointer to the head of the linked list which I'll represent with this green label here so the first thing we'll do is create another pointer called Fast which I'll represent with this orange label so head will be the slow pointer and fast will be the fast pointer now we'll enter a loop that will move these pointers forward as long as both fast and fast.next are not null in other words we fast.next are not null in other words we fast.next are not null in other words we keep looping until we reach the end of the linked list so now let's move the pointers up first we'll set head equal to head.next so we're moving it up one to head.next so we're moving it up one to head.next so we're moving it up one node then we'll set fast equal to .next so to break this down this .next so to break this down this .next so to break this down this would be moving it up to fast dot next and then we have to do another dot next so now we've moved it up two nodes then after moving up both pointers we check if they point to the same node right now they do not so we'll loop again head gets moved up one node and fast gets moved up two nodes then we check again now I need to emphasize here that even though both nodes have a value of 5 this condition is still false because remember when you compare two objects using the is operator it checks if both objects are located in the same place in memory in other words we are checking to see if they are the exact same object in this case they are two different objects that happen to have the same value of five so this is still false and we loop again heady gets moved up one node and fast is moved up two nodes and for the last iteration head gets moved up one more and now fast has caught up to head now when we check this condition head and fast both point to the exact same object in memory so we return true and we are done now if this had been a linked list without a cycle at some point fast would have reached the end of the linked list and either fast or fast dot next would have been null so we would have broken out of this Loop and just returned false which means that there was no cycle
Linked List Cycle
linked-list-cycle
Given `head`, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**. Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** false **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Easy
142,202
336
hey coders so today we will look at this problem number 336 balance bears which says given a list of unique words return all the pair of distinct indices i j in the given list so that the concatenation of the two words word i and word j is a bad intro right so okay so this is a palindrome sort of question so if we have abcd we need to go through whole array and check which word if we concatenate forms of palindrome right so here dcba and abcd ic forms a piling room zero and one is a solution for that so these are all the solutions which we can get and okay so see the naive way will not work because as we can see the word length is of words length like the arrays length is all five thousand uh and five thousand times five thousand is like 25 10 times 10 raised to past six right and for the each word we need to check them too so multiply them by 300 itself so it's going way off the charts so the naive way will not work most probably so now let's go to the solution and see how we're going to achieve an optimized way of doing it okay this will be our example array which we will be solving so the very first thing we need to do is we need to pre-process this array and is we need to pre-process this array and is we need to pre-process this array and form a dictionary right or a hash map with individual positions as their value and the words will be their key right so dictionary would look something like this so dcba will be at the very first position or you can say it has position zero so here this these all words are just reversed right cbs reverses abc this and that right clear so next thing is we need to take a individual word we need to go word by word and we'll form the operations right let's pick abcd so what are all the words which when concatenated with it forms a paragraph those words are dcba cba and dcb of course so the next thing is what we will do we'll form a prefix postfix expression for the same word say abcd and let's say here we have the word abcd right so first of all in the prefix we have nothing in the ball switch we have the entire world we will check if postfix is spread this prefix is present in our array we say no it is not so we won't do anything yet uh next thing is we will check if abcd is present inside our array we can see it is present and we will also check if of a post fix if our prefix is a palindrome it is but here's a catch the element right so it must be at least one time partition for the postfix to be considered right or else we will have duplicating it right we will see this further so next thing is we move a to the left and we'll check if a is present then no a is not is bcd present ah no it's not then we'll move ahead we'll check is a b present no it's not is ct present no it's not moving ahead with abc is abc present you find yes abc is there so check right okay abc is there so is our postfix a balance room yeah it is a parallel drone a single letter is a palindrome our current position right which was zero and the position of this abc which is like 0 1 2 and thus add that to our answer okay simple moving ahead we'll check again is our postfix inside our area no it's not so it doesn't make any point moving ahead we again check is abcd inside our array yeah it is right it is present but is this position same as our current position no it is not so we will count this as our answers right and put them in our resultant array so here you must have gotten a little gist of what is actually happening here in the next step we will discuss its code and how we will implement it using python so let's make the pre-processed pre-processed pre-processed area we are using a dictionary comprehension so bear with me now we will iterate the array now let's make prefix and postfix now we will put our first condition now we make another check where we change if j is greater than zero right this was the part where we avoid the duplicacy and we check if the post fixed right is no we made a mistake over here it should be post now we check if pose is in our dictionary d and the current position i definitely not equals to the position of p right now let's run some guest cases it works so far just run all the test cases okay cool now let's summit it okay it's working you
Palindrome Pairs
palindrome-pairs
You are given a **0-indexed** array of **unique** strings `words`. A **palindrome pair** is a pair of integers `(i, j)` such that: * `0 <= i, j < words.length`, * `i != j`, and * `words[i] + words[j]` (the concatenation of the two strings) is a palindrome. Return _an array of all the **palindrome pairs** of_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "dcba ", "lls ", "s ", "sssll "\] **Output:** \[\[0,1\],\[1,0\],\[3,2\],\[2,4\]\] **Explanation:** The palindromes are \[ "abcddcba ", "dcbaabcd ", "slls ", "llssssll "\] **Example 2:** **Input:** words = \[ "bat ", "tab ", "cat "\] **Output:** \[\[0,1\],\[1,0\]\] **Explanation:** The palindromes are \[ "battab ", "tabbat "\] **Example 3:** **Input:** words = \[ "a ", " "\] **Output:** \[\[0,1\],\[1,0\]\] **Explanation:** The palindromes are \[ "a ", "a "\] **Constraints:** * `1 <= words.length <= 5000` * `0 <= words[i].length <= 300` * `words[i]` consists of lowercase English letters.
null
Array,Hash Table,String,Trie
Hard
5,214,2237
186
all right so let's talk about the reverse Source in the string too so you're giving the charter radius and then reverse the order of the word so this is going to be pretty much it right so you have to reverse the original chart right so again so little sky is blue right so you blue put it in it first is put it as a second Sky uh on the following and then another will be at the end so this question is pretty straightforward you need what you need a reverse function so I uh when I want to reverse right I want to reverse the entire string first so I will be like this e u l p and then you have a space then space and is I space right y k s space e h t right so once I reverse the entire string right I can now reverse the chart array before the space so blue I mean eulb I don't know how to pronounce but when you reverse you will become blue s i c when you reverse will it will become is right and then y k s and then it's k y e t h t then you'll become low so this is the entire uh idea right so I need a helper function for reverse right so Char s in I in J so while I less than equal to J right so you need the 10 equal to what uh Sai and s a i equal to S A J CJ equal to 10 and now you increment your counter right so I plus and then you should be J minus five so uh you are given the position right and then later on you just uh you know so I need to say reverse entire screen and then it's starting from zero and any from what the value in this which is a star length minus one all right so you have to uh so you have to have I and J pointer right so in I okay go to zero energy is also J is also equal to zero right and then you need to have a condition to Traverse right so while I listen to insta lens and then also J is less than equal to external try is the lens because s is sorry right and you want to what so in the beginning uh here's it in the beginning there might be have a space right so you probably can have a space low something like this right and then you uh you want to get rid of what you want to get rid of the space so I enjoy what's selling from here and I you want to get rid of the space right so you want to say if you want to study from I at least position right and then one and then when you know your current position I'm going to assign my J equal to I and then I Traverse my trip uh J index When J it when J Char is now what is not a space so I need to reach a position which is a space after the alert right and then I know I need to swap between I and J minus one I and J minus between I and J minus one I need to swap right I need to reverse sorry and then here we go so uh so while I listening is the lens and um the current chart is AI is equal to space right I need to increment my eye so I need to initialize re-initial my I so I need to initialize re-initial my I so I need to initialize re-initial my I uh so J is equal to I and then while J is less than it's the lens and also sha is not equal to space and J plus and then you want to reverse a s a i h a minus one and then once you reverse uh once you reverse the entire stuff right J is actually at a space position right then you want to initialize your eye so this is how the idea work right so uh reverse what zero oh this is Charlie a little bit table but whatever all right so let's talk about the time and space and for the time this is definitely all the plan right uh you Traverse every single you know sorry in this one you reverse the entire screen right so it's definitely all offend and then in this value you are actually what breaking the all of an into the small part so this is still all of them if you want to say it right so if you want to just confirm if you're just concern while there are a value inside a value uh you probably would ask like you know you should be unscripted right but it's not uh it's definitely not so the worst case is going to be at least the reverse full entire chart right so it's all open and the space is constant so I'm going to put some breakpoint and then you know something like this I don't know and you can pause it any second so look at the left window uh if you notice like the original rate is actually what changing right thank you all right so this is pretty much it so if you have any questions leave a comment below subscribe if you want it alright peace out bye
Reverse Words in a String II
reverse-words-in-a-string-ii
Given a character array `s`, reverse the order of the **words**. A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by a single space. Your code must solve the problem **in-place,** i.e. without allocating extra space. **Example 1:** **Input:** s = \["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"\] **Output:** \["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"\] **Example 2:** **Input:** s = \["a"\] **Output:** \["a"\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is an English letter (uppercase or lowercase), digit, or space `' '`. * There is **at least one** word in `s`. * `s` does not contain leading or trailing spaces. * All the words in `s` are guaranteed to be separated by a single space.
null
Two Pointers,String
Medium
151,189
179
hey guys welcome back to another video and today we're going to be solving the lead code question largest number all right so in this question we're given a list of non-negative integers given a list of non-negative integers given a list of non-negative integers and we want to arrange them in such a way that they form the largest number so what does that mean so let's say over here we're given the values 10 and 2. so over here we can form two numbers so one of the possibilities is coming up with the number 102 so 10 and then two so one zero two 102 right and the other option we have is we rearrange it so instead of ten and two we have two and ten and that gives us the value of two hundred and ten so two and then one zero hundred 0 210 okay and which one between those two is bigger obviously 210 is bigger so that's what we're going to end up outputting so now we want to see how do we exactly solve this question so now the first thing that came to my mind when thinking about how to solve it was to just sort the list and then join everything together so let's say that i sorted and just to make sure i'm going to be sorting it in descending order so if i sort this in descending order it's going to end up giving me 102. a better example actually is to look at this over here so if i sort it in descending order i would get 34 first but obviously that's not going to be the biggest number but the biggest number will be when nine comes in the beginning right so sorting it is actually not the best way to do it so we want to make a small other changes to it in order to get the best and so let's see how we can do this and one more thing that we're outputting this as a string so let's just go through the step by step and see how that looks like so this is the exact same question as our example 3 30 34 5 and 9. and this is how we're going to be solving this so we're going to have two pointers and i'll just represent each pointer by its color so one of them is going to be in green color and the other is going to be in red so the green pointer starts off always at the zeroth index and the red pointer is going to start off from the next index so if green starts at index one red starts at index two so currently this is where our red pointer is gonna start so now what we're gonna do is we're gonna form two different numbers so one number that we're gonna form we're just gonna take between green and red is going to be taking the green value and adding that to the right value so three and by adding i don't mean doing three plus 30 giving us 33. by adding i mean taking three and just putting the next two values so three and then three zero and that ends up giving us a value of 330. and one more thing if you noticed um so since we're adding it like this converting these values to a string makes it a lot easier okay so now we have 330 and what is the other combination so over here we took green first and then we took red so now let's take red first so if we take red first we end up with 30 and then let's take green so now let's put three so these are the two values that we possibly have so which one over here is bigger so obviously 330 is the bigger value so since 330 is the bigger value so that's basically saying the same as so first we have green and then we have red and that is exactly the pattern that we have green first and then red so we can ignore this and we're done with it as of now so now what's going to happen is that the green pointer is going to stay the same but what's going to change is the red pointer is now going to go on to the next value so now our red pointer is over here and again we're going to end up forming two different values so we take green first giving us three and then red giving us 34. so now we have 334 now the other number is taking red first so 34 and then adding green so in this case which one is bigger so this one over here is bigger and we got this by doing red first and then green so that means the red value is going to be a better choice since it gives us a bigger value so what we're going to do is we're going to swap these two values with each other so let's just do that real quickly so get rid of this okay so that gives us 34 now since we're swapping it and over here we're going to have three and one more thing is that we're currently done with this and we're going to move our red pointer again so now our red pointer is going to go on to five and we do the same steps i'll just go through this a little bit faster right now so we have 34 so 345 and then we have 534 obviously 534 is bigger so now we end up swapping those two with each other so that becomes 5 and this over here becomes 34. so let's just do that so 5 over here and 34 over here all right cool and one more thing that happens now since we're done with that our red pointer is going to end up changing to the last value over here which is nine so now we create the next two numbers so that gives us 59 and 95 so which one is bigger obviously 95 is bigger so again we're going to have to swap those two values with each other so we swap them and now the green value is going to now end up becoming nine so we have nine over here and this over here ends up becoming five okay so that is going to be one complete iteration so what exactly happened in that iteration so if you notice or if you even go back to our answer we got our first value so this is telling us that the first value that we're going to have is for sure going to be the value nine so currently we have the first value in place we don't need to worry about it and nine is going to be our first value so now what's going to happen is that we're going to remove our green pointer since we reach the ending with our red pointer and over here what's going to happen we're going to give a new green value and this is going to be the next value so currently we were done with 9 so 9 is in its correct place so we want to find what is going to be the next uh values right we're going to be the next digits after nine so to find that again we're going to put a green pointer over here and the red pointer is always going to be right after the green pointer so this is going to be our red pointer and over here we're going to be performing the exact same steps so we'll be comparing in this case 303 with 330 and what happens over here 330 is bigger than 303 so that means that we're going to end up swapping that so let's swap this over here so 3 over here and 30 over here and similarly the red is going to change and it's going to move over by 1. so i'm pretty sure you get the point and by the ending of this what should be happening is by each iteration we should be getting the correct value of the green spot so in the first iteration we got the correct value for this in the second iteration right now we're going to get the current value for this spot over here then we're going to get the correct value over here and so on and so forth until we reach the last but one value and that's when we're going to stop with all of this so just to kind of go through this i'll just go through this and you can see what the end result looks like so at the very ending what happens is that we end up with this over here and um if you add all of these together into one number we're going to end up with nine five three four three zero so in other words that's just going to be nine million five hundred thirty four thousand hundred 330. so that over here is our largest number i didn't go through all the steps because it would take quite a bit of time and i would highly recommend that you do go through all the steps if you still did not understand how this works so now what i'm going to do is let's go through the code part of this and understand how the code looks like all right so over here we're going to start off by changing everything inside of our nums so currently everything inside of a num instead of nums is an integer but we want to change that to be a string and why is that so let's say we have the numbers one comma two comma three and when you add them so you would actually be doing one plus two which gives us three but instead what we wanna do is when we add these two values we wanna be so let's say we do one and two instead of doing one plus two we want to get the value 12. so in order to do that converting this into a string is going to make it a lot easier so how exactly can we do that so we can do list and over here we're going to use the map function so we're going to do map and we want everything to be a string so string and then for what so for the list of nums okay so by the ending of this if you print out the if you print out any of the elements and nums it is going to be a string okay so over here we're gonna check if the length of nums is less than two so if we have something which is uh which does not have any length or if we have something which has a length of one then in that case we're just going to end up returning whatever we have so to do that we can just do if length of nums is less than 2 or in other words if it's equal to or less than 1 then in that case we're just going to return so we can use the join function so we're going to give it a string dot join and the reason we're doing a string is because we want the output as a string and then we're going to give nums and the re and one more thing is that it's important that we convert it to a string because the dot join function only works for strings so yeah so now we got our answer for if it's a null value or if it has a value of one number in it so over here we're going to go on to our next condition so to do that we're going to end up having two of our pointers so we had red and green but in this case i'll just call it x and y so x and y are both going to start so x is always going to start off at zero and y is going to be one more than x so in this case let's just make y one and it's not going to be our final code but i'll just use this to explain how it works so over here we're going to have a while statement so while and what is the statement going to be so while the x value is less than the length of nums and the y value is less than the length of nums so that means that we've uh we haven't gone out of the range of the list yet that only then we're going to go inside of our if statement so over here we're going to compare these two values so how exactly are we going to end up comparing them so to do that let's make a function over here called compare so this is going to take two numbers so let's just call them x and y so x and y are going to be the two numbers that we're talking about and actually to be more precise we get x and y exactly from here so x and y is actually going to be the index right so now we want to get them into the number itself so how do we convert this into the number so over here we have two numbers so one of the numbers is going to be nums x sorry nums x plus nums y so that gives us one of the numbers but currently that is a string so over here we're going to convert that string into an integer so this is one of our numbers and the other number that we're going to have we want to convert to an integer it's just going to be the opposite so num y plus num x so over here we formed two of our numbers so over here what we're going to do is we're going to return if the statement so if nums x plus y is greater than nums y plus x then in that case we're going to return true so if this is true we return true but if that is false we're going to end up returning false okay so now let's see how we can add this to our while loop so over here we're going to check if compare so we're going to give it x and y values and if this is true that means that x plus y is bigger than y plus x in that case we're just going to pass we're not going to do anything we're going to let it be as it is but else so else if this is not true so that means that y plus x is greater than x plus y and in that case if you recall we're going to be swapping these two values with each other so how do we do the swap so nums y and nums x so nums y is going to become nums x so let's do that over here and num x is going to become num y so this over here is swapping the two values with each other and at the ending of this for no matter what it is we're going to increase our y value by one so by the ending of this we're going to get the value for one iteration but we don't just want one iteration right we want to be doing this until the x value reaches to the last but one value so in order to make this a lot easier for us we're going to put this inside of a for loop so let's just remove this over here and over here let's put let's do a for loop so four x in range so we're gonna be going up to the length of nums minus one so the last but one value and over here let's put our while loop inside of this for loop and we also want to define the y value so the y value is always going to be x plus one it's going to be the next value and each time we're going to redefine this y value and by the ending of this we should get our nums in the sorted order according to what we want so once we get this all we have to do is return and we want to join these two each uh together instead of a string so string dot join and then we're joining the nums okay so if i submit this over here it's actually not going to be correct we're going to get it wrong at this condition over here so zero comma zero and we ended up outputting the value zero which is actually wrong it expects just one zero so how exactly do we take care of this uh simple uh situation over here so in order to do that we're going to be using the map method again but the way we use it is going to be a slightly different so over here what we're going to do is we're going to map it according to a boolean value so how exactly does this work so let's just first do it real quick so map we want it to be a boolean value and we're going to be using the nums list and one more thing make sure that we're doing this before we converted it into a string so these numbers are still integers so over here if our numbers are equal to zero that means that everything is going to end up as having a value of false and if even one of these numbers is not a zero we're going to have a value of true so to check if all of our values are not zeros we can do any and then we can put this over here and we can check if not any and then of this mapped list over here so what exactly does this mean so over here if let's say as we had two zeros right so what's going to happen once we put it through our map over here we're going to get two false right so we do not have any true right there's no truth inside of this so in that case what's going to happen we're just going to end up directly returning the value zero and that's it we're directly returning the value zero and we're done with the function as it is and even if one of the values is not a zero uh basically in the fact that not everything is a zero then we're going to go past this if condition we're not going to return anything and we're going to proceed on doing all of these steps so now when we submit this we have accounted for that zero um parameter and now our submission is accepted so thanks a lot for watching guys hopefully this video helped you and don't forget to like and subscribe if the video helped you thank you
Largest Number
largest-number
Given a list of non-negative integers `nums`, arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer. **Example 1:** **Input:** nums = \[10,2\] **Output:** "210 " **Example 2:** **Input:** nums = \[3,30,34,5,9\] **Output:** "9534330 " **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 109`
null
String,Greedy,Sorting
Medium
2284
1,662
welcome to january's legal challenge today's problem is check if two string arrays are equivalent given two string arrays word one and word two return true if the two arrays represent the same string so what do we mean so we're given a list of strings you can see though that they're going to be kind of split up in different manners what we want to do is try to concatenate all these strings together and see if they form the same word and we can do that in python fairly easily using the join method right so all we need to do is try the string join and say all right string join the word one and check to see equal to string join of word two and i wasn't sure if this would work because concatenating strings in python is pretty expensive but it does work um so there we go so that seems simple enough but this does use extra memory right because we're forming a new string out of our list of strings so could we do this in o of one space well yes but it's not necessarily going to be faster might save memory let's see how we might do that so we would have to have two pointers per each of the work are two indexes we would need the index for the item list or the string inside of the list as well as a index number for the character inside of this string so let's see what we do we have say word one index zero uh and we'll have word two index as well and both of these will start with zero then we'll also have a character one index as well as a character two index and again these will start at zero now while we have the ward one index is less than the length of word one uh i should say and word two dot index is less than the length of word two we're going to check something here first we want to get the character of what we're pointing at so this would be word one index and character one and we can do the same thing for the second word now uh once we do this we want to check to see if they are equal to one another and if they are we can continue our loop so if c1 does not equal c2 then return false immediately because we know that these words can't possibly be the same but we have to make sure that we want to check to see if we're at the end of the word or yeah the end of the string inside of this index number right so if let's see word1 dot index or i should say charact character one index um if it's greater or equal to the length of word one word uh let's see word one index that's the case um but yeah if that's the case then we want to increase our uh word one index and reset our character one index to zero otherwise we're just going to increase the character index right uh and i believe that actually comes before here character one index is so we'll have character two do the same thing and finally that would be it we just need to go up to the end and one thing to note is we can't just return true here because we could possibly have um one part be like abc and the other one be like a b c d so we want to check to make sure that the lengths of the word one equaling the length of word one is true i should say word index all right so let's see if this works okay it does seem to work and there we go accepted so this would be all one space it's a lot more uh verbose and wordy uh and the truth is i don't think it's any faster in fact here looks like it's being slower and for some reason in lee code it says we use the same amount of memory i'm not totally sure why that's the case uh it's probably something to do with leak code itself but i'm fairly certain technically this is all one space so both solutions are fine uh i just want to go through this in case um you want to try to better so thanks for watching my channel and remember do not trust me i know nothing
Check If Two String Arrays are Equivalent
minimum-numbers-of-function-calls-to-make-target-array
Given two string arrays `word1` and `word2`, return `true` _if the two arrays **represent** the same string, and_ `false` _otherwise._ A string is **represented** by an array if the array elements concatenated **in order** forms the string. **Example 1:** **Input:** word1 = \[ "ab ", "c "\], word2 = \[ "a ", "bc "\] **Output:** true **Explanation:** word1 represents string "ab " + "c " -> "abc " word2 represents string "a " + "bc " -> "abc " The strings are the same, so return true. **Example 2:** **Input:** word1 = \[ "a ", "cb "\], word2 = \[ "ab ", "c "\] **Output:** false **Example 3:** **Input:** word1 = \[ "abc ", "d ", "defg "\], word2 = \[ "abcddefg "\] **Output:** true **Constraints:** * `1 <= word1.length, word2.length <= 103` * `1 <= word1[i].length, word2[i].length <= 103` * `1 <= sum(word1[i].length), sum(word2[i].length) <= 103` * `word1[i]` and `word2[i]` consist of lowercase letters.
Work backwards: try to go from nums to arr. You should try to divide by 2 as much as possible, but you can only divide by 2 if everything is even.
Array,Greedy
Medium
null
695
So if Video Inderpreet Kaur Degree Holder Problem Max India Of Ireland Surya Giver Great And Basically Ireland Group-1 Connected For Directions Where Is Group-1 Connected For Directions Where Is Group-1 Connected For Directions Where Is The Number Of The Return Of The Volume To Maximum Subscribe Example Which You Have A Silent During And Size Of Four Again And You have a dasha languages ​​have enough size of which you have a dasha languages ​​have enough size of which you have a dasha languages ​​have enough size of which you have a silent silence the maximum number of numbers is 123 456 are connected let's look at its leaders take this software into a titillating first sidesteps appeared first on me to two to the celebration Of no value and contributed for the volume to check my name is a plus together and derived from the group which can contribute to form the maximum area from this to record from exactly so many years just call the function and explain the years of tuition in a Good Cause It's Neighbors 151 Deposit And One More Step Number Three And Validation Important And Will U Can Be So To-Do List Start Doing So Be So To-Do List Start Doing So Be So To-Do List Start Doing So You All Subscribe 2014 Porn Wash With Used Lubricating Water And Water Until You All It's Neighbors Will Return To Stop this is the what is the first person bigg boss ne very happy new year so what to do when will again calls never saw it will enter into the function of is right but they cold see the middle of nowhere else will return Return Back to the Function subscribe this Subscribe to YouTube Channel Now to Take Off OK Se 10 Particulars Sale Subject Information in Toilet You Will Reach and Write Rural Schools from the Beginning Night Sweet Dreams Different from this Particulars In and What Happened Now OK Very Interesting And Happiness Not Destroy Justice Am Officer You Can Observe A Very Carefully What Will Happen In This Particular Say This Is To Make A Call To College First Name * Was Okay Is Call To College First Name * Was Okay Is Call To College First Name * Was Okay Is Right Depend Investigate Cold Water Proof Brightness Will Also Make A Call To Everyone Like It Surya Itne Barun Macrame Quite Right Never Stop Never Will Never Left Labels Brightness But Will Also Called Again Seervi And Understand What Is Happening Okay Subscribe To * Understand What Is Happening Okay Subscribe To * Understand What Is Happening Okay Subscribe To * All Its Neighbor Once Again For The First Time When Will The First Subscribe School Fees Time And Situation Second Tax School Say Never And You Will Keep Falling He Changed Gil Se Quality Never Say Never Been Stuck In A Slack Poor Twist Very-Very Important This To Consider What Do Twist Very-Very Important This To Consider What Do Twist Very-Very Important This To Consider What Do You Mean To Look Back 2018 For Defense Can You Make A Is Dynasty This Visit Something Vitamin Value 112-jazz 102 Important Sydney Morning 112-jazz 102 Important Sydney Morning 112-jazz 102 Important Sydney Morning Herald To Finally Bigg Boss Liter Maximum Area So Let's Go For This So Let's Start Hydrating Over All The Sense Point Equal To Zero Oil A Sanam Play N V Side Ko Lamba Not Declared When Is The Number Of Daughter Of Water And Number 90 Number 91 Value Is Unit To Do The Function Points What Is How Did The Various One Simple A Grade Of Held Is Equal To What You Can Simply Give A Brief Come 10 B Positive Number To Do You Live Windows 8 Khesari Value One Switch Account Has To Be Given Minimum And Variable In Which We Can Finally Returns Of The Day and finally no the function of account and function subscribe to the Page if you liked The Video then subscribe to the Page Main Tera Dushman written in and water into this they want to write definition in this function notification aa simply is with in To develop things this note you can simply subscribe to 10000 is greater than two years old is gold channel of side this is 2030 you know not at all not waste time toxins nor to contribute towards it's now a specific count of verbs setting function very -Very Important Development This Don't function very -Very Important Development This Don't function very -Very Important Development This Don't Make The Great Friday Or Will Run Into The Time Limit Straight Problem Run Into Infinity Recessive Calls With Features And Logic What Do We Call The Animals And Share Helpful And Not Withdrawn It's Just What Do We Call The Calling Now That If A Good Qualities And Millet Jewelry Means I Am Not Want To See The Question Pass Control Of Which Never Used Oil Jewelry Middle Name And Don't Give Me Give Winners Will Leave You Know All This Today We Just Cords One Time I - Today We Just Cords One Time I - Today We Just Cords One Time I - One Time He Plus One Upon Time I Will Give 6 - One N One Time Will Give Way Do 6 - One N One Time Will Give Way Do 6 - One N One Time Will Give Way Do Subscribe For This Is For Liberty And Share Subscribe Button Positive How Will Tree To Avoid You Can Give Water Subscribe To Ka Beauty Compiler Identifier M So Yes ok hai vent all govt s well s eminent aur please give dot subscribe The Channel subscribe dot size notification aa ko switch final lakshmi jism intensive king up ko switch marking not really 201 time output description of this video also what is happening unfortunately in this coming Account It Is The Side Chile That Give This In Size Bracket Dead Skin Problem Solve Important Sisters Under The Condition Middle School Subscribe Thank You
Max Area of Island
max-area-of-island
You are given an `m x n` binary matrix `grid`. An island is a group of `1`'s (representing land) connected **4-directionally** (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. The **area** of an island is the number of cells with a value `1` in the island. Return _the maximum **area** of an island in_ `grid`. If there is no island, return `0`. **Example 1:** **Input:** grid = \[\[0,0,1,0,0,0,0,1,0,0,0,0,0\],\[0,0,0,0,0,0,0,1,1,1,0,0,0\],\[0,1,1,0,1,0,0,0,0,0,0,0,0\],\[0,1,0,0,1,1,0,0,1,0,1,0,0\],\[0,1,0,0,1,1,0,0,1,1,1,0,0\],\[0,0,0,0,0,0,0,0,0,0,1,0,0\],\[0,0,0,0,0,0,0,1,1,1,0,0,0\],\[0,0,0,0,0,0,0,1,1,0,0,0,0\]\] **Output:** 6 **Explanation:** The answer is not 11, because the island must be connected 4-directionally. **Example 2:** **Input:** grid = \[\[0,0,0,0,0,0,0,0\]\] **Output:** 0 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 50` * `grid[i][j]` is either `0` or `1`.
null
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
200,463,1845,2206
304
Ajay Ko Hello Hi Everyone Welcome To My Channel It's All The List Problem 304 Ransomware Redeem Your Troubles For This Problem Is Very Famous Interview Problem Anycut Aaj In Amazon Google Microsoft Interview subscribe to the Page if you liked The Video then subscribe to the Page Indian Ginger Green can we like this red square feet thing 09 element witch some lemon and misses 128 like date for everyone call me to the solution subscribe problem example for middle thursday morning all elements witch rectangle 12345 and green square end subscribe to thanks sensual gay 11:00 Exit thanks sensual gay 11:00 Exit thanks sensual gay 11:00 Exit Unlimited Picture Ko Dot Approach Which Is Very Straightforward You Can For The Video And Implement Your Say What Is The Time Complexity Of Dissolution Show In Constructor Members Switch Off But Not Do Anything Which Is Copying Changing Reference 19th Shri-Samriddhi Width And - - 19th Shri-Samriddhi Width And - - 19th Shri-Samriddhi Width And - - - Call We Roman Reigns We All Subscribe - Call We Roman Reigns We All Subscribe - Call We Roman Reigns We All Subscribe Can We Make Every Constitution College Of Know How Make Very Easy The President To Power For It's Us In This Time Complexity Vikram Time Power Point When Is The Maximum Given In This Problem In 210 Suresh Oberoi Time Complexity Rebellion Like Him To Deposit Near Ride Point To The Power This Update Will Be Timeout And Very Poor Performance In Terms Of Time Complexity Software Must Be Follow Nutrition How Will Improve Time Complexity Of This Solution From Being Of Lemon To Be Of This Constitution Method Call 100 How To Do This Point Gas Recently That Solve This Problem Running Some Of Money Are In The Challenges Of Life Se Sure Patience Na Urgent Need To Join The Return Of Life 1364 Me To The Newspaper Chennai Express Which Takes You Into Every One Of That Unwanted Mutton Interviews Pet Something 2516 Elements of Obscurism Half Inch Subscribe Problems Which Helps Improve Time Complexity from Expansion of Words Related to the Same Approach Will You Can Also Saw This Will Create Content by Pressing the Subscribe Button Cleaner Lots of Cases Subscribe in This Element Forces and 10 ft long hair in wave super discus throw is similar to bhiwandi soft will take this rosary and will feel overhead so initially envisioned in 307 323 plus one but will need a glittering subscribe Video over what will be the first one plus one and Evil From This Is Like 251 Switch On Subscribe Shubhesh Like This San Still Here From Starting From Zero Basically From 2002 Dual Air And Attracting Someone From This Sunidhi Shedding After Reading This Issue Seriously Edit To Time Isko Man Read Subscribe Shoot Subha Sector 110 Vikram Thriller 0 Plus - 08 Till Currency Value Which Thriller 0 Plus - 08 Till Currency Value Which Thriller 0 Plus - 08 Till Currency Value Which Is Point Vishisht This Is Vikram And Saunf In Terms Of Digestive Want To Right Member Vikram Sum Of The System Of View From A Plus B Plus We Raw That I Plus One A For B I Plus One Pro And Same Jain Sudesh Water Something This Point To 4 Plus Some Of Social Media Point Subscribe And A Plus One 8 - SBI Two Times Adjustment Compelling Jain11 8 - SBI Two Times Adjustment Compelling Jain11 8 - SBI Two Times Adjustment Compelling Jain11 Video Matrix Of I Will Take Care Of All They Know How To Draw Water From Sorrow And Subscribe Now To Receive That And Have Been Included As One Is Our R1 And C1 Share This Vacancy With Map Dish 218 ISRO Ro Two Billion Plus One And C Two Billion Plus One Subscribe To And Sunao 's Members One And wash hair Previous 's Members One And wash hair Previous 's Members One And wash hair Previous Samsuddin Civil V I one second switch off 419 Udyam 500 Us 512 305 Shift Row End Column Sudesh One is our biggest mistake also level this point All also points lines in this crime area from this point Sudhir and Subscribe 16 December Anna On Max Bhi Neetu Subject Arts Chuckle This Is Wrong No Duty 828 So Here And Next They Will Spread Difficult Swift Nodded In The Subscribe 280 Power To Do Not Very Happy Returns Of The Day Tapasya Avsar Vansham Media Can Verify And Quotes Flirty Ridhead And Pradesh Ko Light picture Video subscribe and subscribe the same will go to plus two plus minus blue green T&amp;C T&amp;C T&amp;C 130 will guide accepted your details on record accept what is the time complexities of this solution so edit can see beer building this matrix over it will take Of Cost Of Consideration While We All Were Born In This Is The Time Complexity subscribe thanks for watching
Range Sum Query 2D - Immutable
range-sum-query-2d-immutable
Given a 2D matrix `matrix`, handle multiple queries of the following type: * Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. Implement the `NumMatrix` class: * `NumMatrix(int[][] matrix)` Initializes the object with the integer matrix `matrix`. * `int sumRegion(int row1, int col1, int row2, int col2)` Returns the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. You must design an algorithm where `sumRegion` works on `O(1)` time complexity. **Example 1:** **Input** \[ "NumMatrix ", "sumRegion ", "sumRegion ", "sumRegion "\] \[\[\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]\], \[2, 1, 4, 3\], \[1, 1, 2, 2\], \[1, 2, 2, 4\]\] **Output** \[null, 8, 11, 12\] **Explanation** NumMatrix numMatrix = new NumMatrix(\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]); numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 200` * `-104 <= matrix[i][j] <= 104` * `0 <= row1 <= row2 < m` * `0 <= col1 <= col2 < n` * At most `104` calls will be made to `sumRegion`.
null
Array,Design,Matrix,Prefix Sum
Medium
303,308
1,646
hi guys welcome to algorithms made easy in this video we will see the question get maximum in generated array you are given an integer n and an array numbers of length n plus 1 is generated in the following way numbers of 0 becomes 0 nums of 1 becomes 1 and for any nums 2 into i it becomes nums of i and for any nums 2 into i plus 1 becomes numbers of i plus 1. from these i plus numbers of i plus 1. from these two conditions we can say that if the number is even we can rewrite the value for it in the nums array as nums of i by 2 and if it is an odd number we can write its value as the sum of numbers of i by 2 plus nums of i by 2 plus 1. at the end we need to return the maximum integer that is occurring in the array nums so this is a pretty straightforward question we'll just be using these conditions that are mentioned over here and we can get the answer easily from that so let's go ahead and write some code for it so the base case here would be if the number is 0 or 1 we can just give the number itself as an output so if n is less than 2 return n otherwise we take an int array that would be of size n plus 1 and we write nums of 1 equal to 1 as it is given to us after this we'll run a for loop the for loop will start from 2 as we are already returning the answer in case of 0 and 1. in here if i mod 2 is equal to 0 which is this condition our nums of i becomes numbs of i by 2 else numbers of i becomes numbers of i by 2 plus 1 with this will update a variable max that would be our result so initially max would be 0 and here we can update max math dot max of max comma nums of i lastly return max let's try to run this code for all the sample test cases that are given to us and it gives a perfect result let's try to submit this code and it got submitted the time complexity for this approach is o of n and the space complexity is also o of n so that's it for today guys thanks for watching the video see you in the next one
Get Maximum in Generated Array
kth-missing-positive-number
You are given an integer `n`. A **0-indexed** integer array `nums` of length `n + 1` is generated in the following way: * `nums[0] = 0` * `nums[1] = 1` * `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n` * `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n` Return _the **maximum** integer in the array_ `nums`​​​. **Example 1:** **Input:** n = 7 **Output:** 3 **Explanation:** According to the given rules: nums\[0\] = 0 nums\[1\] = 1 nums\[(1 \* 2) = 2\] = nums\[1\] = 1 nums\[(1 \* 2) + 1 = 3\] = nums\[1\] + nums\[2\] = 1 + 1 = 2 nums\[(2 \* 2) = 4\] = nums\[2\] = 1 nums\[(2 \* 2) + 1 = 5\] = nums\[2\] + nums\[3\] = 1 + 2 = 3 nums\[(3 \* 2) = 6\] = nums\[3\] = 2 nums\[(3 \* 2) + 1 = 7\] = nums\[3\] + nums\[4\] = 2 + 1 = 3 Hence, nums = \[0,1,1,2,1,3,2,3\], and the maximum is max(0,1,1,2,1,3,2,3) = 3. **Example 2:** **Input:** n = 2 **Output:** 1 **Explanation:** According to the given rules, nums = \[0,1,1\]. The maximum is max(0,1,1) = 1. **Example 3:** **Input:** n = 3 **Output:** 2 **Explanation:** According to the given rules, nums = \[0,1,1,2\]. The maximum is max(0,1,1,2) = 2. **Constraints:** * `0 <= n <= 100`
Keep track of how many positive numbers are missing as you scan the array.
Array,Binary Search
Easy
2305
1,996
hello welcome to my channel today let's talk about lead coder 1096 the number of weak characters in the game so um it will give you a 2d array called properties and then each element of the properties is a two are two uh length of two integer array uh the first one is called attack the second one is called defense so one there is another character which has both higher attack and a higher defense this character is called weak character and the question asks you to output the number of weak characters so uh fight uh we can look at the example in the first example there is no weak character uh in the second example uh character tutu is a weak character because the character the second character has both a higher attack and a higher defense the third example character 4 3 is a weak character because the second character has a 10 as a attack which is higher than 4 and has a 4 as a defense which is higher than 3. so this question um the blue force approach is a you compare each character with all the other characters and the time complex is an n square but uh because the constraint uh here is a 10 to the power 5 so it will get a tle the second approach we can think of is uh to firstly to of the properties by bioattack um so then after sorting we can actually iterate the array from end to the beginning and uh keep a count keep a counter of keyboard variable called uh max defense uh then we compare uh the current character with as a defense with max defense and if it's uh it's if it's smaller than max defense we might have a weak character here so but this approach actually has a still have a slightly problem so let's uh look at the example here so assume we have this three character one two one three and one four so now it's sorted by attack but they actually have duplicated the attack value then when we go back uh go integrated array from back from end to the beginning then we actually firstly we have max defense as four then we compare three with four and we actually have a three smaller than max defense then we might increment this counter but actually we shouldn't because the attack value is uh identical so total solver walk around there is a to sort of array by attacker in ascending order and by defense in descending order then though we will have a for this situation we will have one four one three and one two so now we actually go if we go from the back to the front uh we can we get a max defense firstly assigned another two so max defines as a three and a max defense so actually we will not uh increment the counter for any of this character which is correct so uh let i have an explained approach let's uh um code this uh so i will uh solder this array by using this lambda expression so when the attack is uh the same we don't need to we actually can compare the defense so the this is the sort of the descending order then if a tag is different we send we saw that by a tiger by uh in ascending order so under this so it's sorted and then um we get the length and we need to have a max defense we can actually initialize as a zero because the range is at least one and also we need a counter called als so what we can do is we go backwards so uh iterate and so now is we need to compare so if produce defense is a smaller than max difference so we actually need to increment the corner otherwise uh we don't need to increment counter but we need to update this variable next defense and then we just return sponsor so this basically does that let's test the some example and uh some myth voila so fast uh let me know if you have any question and you can comment and if you like the video please subscribe or click like button thank you for watching see you next time
The Number of Weak Characters in the Game
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game. A character is said to be **weak** if any other character has **both** attack and defense levels **strictly greater** than this character's attack and defense levels. More formally, a character `i` is said to be **weak** if there exists another character `j` where `attackj > attacki` and `defensej > defensei`. Return _the number of **weak** characters_. **Example 1:** **Input:** properties = \[\[5,5\],\[6,3\],\[3,6\]\] **Output:** 0 **Explanation:** No character has strictly greater attack and defense than the other. **Example 2:** **Input:** properties = \[\[2,2\],\[3,3\]\] **Output:** 1 **Explanation:** The first character is weak because the second character has a strictly greater attack and defense. **Example 3:** **Input:** properties = \[\[1,5\],\[10,4\],\[4,3\]\] **Output:** 1 **Explanation:** The third character is weak because the second character has a strictly greater attack and defense. **Constraints:** * `2 <= properties.length <= 105` * `properties[i].length == 2` * `1 <= attacki, defensei <= 105`
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
Math,Dynamic Programming,Combinatorics
Hard
null
253
hey everyone in this video let's go to question 253 meeting rooms 2 on leak code this is part of a blind 75 list of questions so let's begin so this question is actually a premium question and that's why we're doing it on this lint code website that's why the number here is different but otherwise the question and the test case is solution will be the same so let's go ahead and begin in this question we're given an integer or given an array of meeting time intervals consisting of start and end time so S1 E1 has to be better where s i is less than e i and we want to find the minimum number of conference rooms required we can see here that additionally 0 8 and 810 is not a conflict which means that a meeting can end and another one can start at the same time we essentially want to find the minimum number of conference rooms required now we've done question a question similar to this meeting rooms one and in that one essentially we just had to figure out if one conference room could fit every single meeting and so in that one we just looked for an overlap and if there was any sort of overlap we understood that we could not have the scenario in this one we'll have something similar but instead we want to find the minimum number of conference rooms required so if there is an overlap we'll basically add in another conference room and then we can see based on that how we can arrive at the solution okay so let's take a look at the examples here to better understand and again this website is used for premium prompts so we will use it anytime we have a premium problem on lead code let's take a look at what we have here so in this one what we have is we have a couple of meeting rooms right or meeting like times zero to thirty five to ten fifteen to twenty and what is one thing we want to do right so if you think about it like these times mean something right this means that we must start off at time zero this means that we must start off at like time five this means we must start off at time 15. maybe you can think of this as like 12 o'clock this is like 1205 maybe this is like 12 15 or like whatever right but basically meetings have to happen in a certain order be like similar to real life meetings have to happen in a certain order so one thing we might want to do and we did this in made in rooms one is kind of like sort this list right because this list isn't actually sorted um based on anything but what we did in meeting rooms one is we sorted it based off of the starting time why does this make sense well this makes sense because in real life you want to take in meetings based on the starting time right like you want to pick the earliest meetings first so that's one thing we'll have to do so we'll have to sort the meetings based off the starting time and really if you think about it right it kind of makes sense right if I'm just going through this and I want to see um how many like first of all if there's any overlapped but then I would take a look at this one and then I can see it starts at zero ends at 30. and then this one definitely there is an overlap because this last meeting hasn't finished yet right and so if you think about it so we definitely need to do that right so we definitely need to sort based on start times okay so what else well in this question we're asked to figure out the minimum number of meeting rooms that are required like the conference rooms that are required so how can we do this well we know that like it the initial meeting roommate process right that's going to have like its own room that's gonna have its own room okay so we know that and what we also know is that this room is going to be used until this time 30 right so for example if I process this one and then I go on to this one I basically have to understand that like currently there's only one meeting room and that meeting room is ending at time 30. so there's no way that I can process this one in the same room so this one has to come inside it's other room this one has to come inside another room Okay so we've done that now what about this last one over here well this last one I kind of have two options right I could either choose from this meeting room I could choose from this meeting room or maybe like I'd have to create my own meeting room what can we do well when we're on this one over here we have to essentially determine that okay there's a meeting room that has a Time ending of 30. there's a meeting room that has a Time ending at 10. now what can we understand from this well you can understand that from the meeting room that has a Time ending at 10 then I can actually take its place right because my start time is 15 and because we've sorted based off the start time it means that I can essentially like take this meeting room's place because this meeting is done and I can take its place and so after I do that meeting two room two will just have these two meetings here so what does this kind of like remind us of right like if you think about it on any specific meeting we need to know all of the ending times right that are available and we want to essentially pick the smallest ending time right maybe this Maybe This Time ended at like time like um you know maybe nine or something and so we would actually go ahead and pick this time it would evict this one and we would replace room one with this thing over here right so what is this kind of remind us of when we want to pick the smallest time well if you think about it the solution is a heap right we can use a heap data structure so how make the Heap work well basically what we could do is that if the Heap is empty then we know that there are no meeting rooms so we add to the Heap what do we add or we want to sort based off of or we want to extract based off of the minimum ending time right if I'm over here I need to figure out which one of the rooms essentially ended first right like which one of the rooms like doesn't have any meetings anymore and that's determined by the ending time right that's determined by the ending time it's not determined by the starting time because the starting time might be like a super high value but if the meeting ends in like one minute well that's her main focus right so if you think about it what we can do is once we sort based off the start time then add element to Heap based on ending time and then when adding new elements check if we can pop from Heap meaning old meeting has finished right so what does this mean let's maybe take a look in the code to kind of see what I'm saying here but hopefully this step that we have over here can easily explain it but okay so what do we need well we need a heap right so we can do like uh from Heap queue import he pop and hit push okay What else do we need well we need our Heap which I just call this and then I need to go through my intervals right so I need to go through my intervals I will do four interval in intervals okay so now I'm processing this first one now what do I understand well I understand in the first one actually first thing actually we need to do is sort it based off at the start times right so maybe we can do intervals is sorted intervals and what the key is based off of dot start right and it's because of the list of intervals so intervals is actually a class over here so you can see we have the start and the end so that's why we have that okay so after I've done that I can go ahead and loop through my intervals and now what well this first interval that I have no like meeting rooms right you can think of this Heap as storing the amounting the amount of meeting rooms that we can have at any specific time so this Heap over here if you think about it if Heap is empty so if not Heap then no meetings no meeting rooms create one so we can do is we can increase our count so maybe we'll start off our count at zero and then we'll return our count in the end this is the count of meeting rooms and then what then we need to go ahead and we need to add how do I turn off autocomplete can I do that because it turn it off getting annoying yeah so if we're going to be using a meeting room well then we have to add it to our Heap so I can do Heap push H and then what do I need to add well remember we want to pop based off of the earliest the smallest ending time so we will pop based off the ending time so I'll do interval.e and then so I'll do interval.e and then so I'll do interval.e and then interval.s so what is this going to do interval.s so what is this going to do interval.s so what is this going to do well to the Heap what it's going to add essentially it's going to add in the value 30 and then zero and for example if we go into if we go ahead and we process this element here right so maybe if Heap does if Heap is not empty then check if any items on if check if any items finished right so how do I determine that well I can check if heat adds zero right heaped zero will essentially be the item that has a smallest ending time has the smallest ending time if this item that we have right if this item if this is so this is the ending right time right this is the ending time ending and starting so if the ending time of the meeting if this is somehow less than or equal to the starting time of my current meeting right so this character listen to this carefully if the ending time of this meeting which is based off of this first element here if this meeting has ended before our meeting has started well then I can go ahead and use this room right so what I can do is I could just do heat pump and I will pop a heap up and I'll pop from the Heap and I don't actually care about the value but then what I could do is I could append to the Heap I'll do he push H and what do I want to append well I want to append this same thing over here I will append the starting time and the ending time based off of my information here now in this case we actually won't go ahead and actually here um if you think about it here we don't need to increase the res right because we're using the same meeting room so we don't need to do that but let's just kind of take a look at like what this might look like in the first case our Heap just has this value here right he just has this and so what we do is we check to see if the ending time is less than our starting time which in this case is 5 it's not so what we're going to do is we're going to append 5 and 10 to the list to the Heap but we're append it in reverse order and so now we have two meeting rooms right and so I guess here if it's else right if it's else this means we cannot use existing meeting room so create own and I guess this thing here actually uh we need this and we need it over here as well but here we will actually append to Res right here we'll append to rest so what we're doing here is like we're pushing regardless right because maybe in this case I'll replace it maybe in this case I have to add it but we're pushing regardless but if I have to add it then I want to increase my res okay so what happens at this point res is equal to two and then when I go to process this element here this meeting room over here I can see that Heap at zero will actually be reordered the Heap will be reordered to something like this why because it's ordered based off of the ending time and the ending time here is 10 and so when I look at this I can see that 10 is less than or equal to 15. and so what this means is that this room over here can be replaced by 15 and then 20. and so that's why this will actually give us the minimum amount of room that we need and so you can keep doing this but in the end whatever solution let's take a look at the test cases to see that they passed so this should be end alert start and then end and then start keep is not defined um where am I doing the heaped zero so I guess I should be H at zero and between Tuple and int yeah um each had zero oh I guess H at zero refers to the actual like Heap itself right so like this value here so we actually need H at zero so that will give us the start time right and so then we can go ahead and submit it and then we can arrive at the solution perfect so don't really worry about the percentage Beast beat this is actually like the efficient solution here so what is the time here well if you think about it for the time and space we have to concern ourselves with the Heap itself right so in the worst case I need to add in everything to the Heap right because there's an overlap every single time so if I add in everything to a heap then I'm doing a heat push that is a log end time and essentially like um I would also maybe I don't need to do a heat pop but assuming like I do need to do hip-hop then it would be like n log n hip-hop then it would be like n log n hip-hop then it would be like n log n right and actually like by sorting here it is also n log n so really it's still dominated by the sword over here but in terms of the space you can kind of think of the space as o of n because at the worst like we will add in all of the items onto the Heap the time is n log n the space is O of n okay thanks for watching
Meeting Rooms II
meeting-rooms-ii
Given an array of meeting time intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of conference rooms required_. **Example 1:** **Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\] **Output:** 2 **Example 2:** **Input:** intervals = \[\[7,10\],\[2,4\]\] **Output:** 1 **Constraints:** * `1 <= intervals.length <= 104` * `0 <= starti < endi <= 106`
Think about how we would approach this problem in a very simplistic way. We will allocate rooms to meetings that occur earlier in the day v/s the ones that occur later on, right? If you've figured out that we have to sort the meetings by their start time, the next thing to think about is how do we do the allocation? There are two scenarios possible here for any meeting. Either there is no meeting room available and a new one has to be allocated, or a meeting room has freed up and this meeting can take place there. An important thing to note is that we don't really care which room gets freed up while allocating a room for the current meeting. As long as a room is free, our job is done. We already know the rooms we have allocated till now and we also know when are they due to get free because of the end times of the meetings going on in those rooms. We can simply check the room which is due to get vacated the earliest amongst all the allocated rooms. Following up on the previous hint, we can make use of a min-heap to store the end times of the meetings in various rooms. So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied. If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room.
Array,Two Pointers,Greedy,Sorting,Heap (Priority Queue)
Medium
56,252,452,1184
1,346
Going to question check double exists a simple exists whose double is also in the same array as in this example punch is a number whose double i.e. 10 number whose double i.e. 10 number whose double i.e. 10 remaxists from this what does it mean I will return true second example What is 317? There is no number whose double is present in this array so we will return false. What is the first method? The first method is pick this number and check whether it has double or not. Pick this number and check whether it has double or not. Like this, there will be less in these squares. Okay, what is the other way? Sort it because it is not sorted, then it will be sorted in N people, then what to do, what are we doing now? Right now, we are doing linear search in N squares, right. So what will we do now, pick it, apply binary search on the rest, i.e. whether 2i accesses or not, i.e. whether 2i accesses or not, i.e. whether 2i accesses or not, okay, so sort in n people and why do binary search in only n people, because what will be searched first, there will be a loop and more people will search. So N people N plus N people N means N people in. What is the third way? The third way is to use the set. How do I explain the use of the set? As you are iterating, keep moving it around in the set, okay in one iteration. Then in the second loop, check whether it is accessing double the current element or not. So what to do in the first loop is to put it in the set and look in the second one. Grab each element and see whether the double access of the current element is done. Does it or doesn't it? What is happening in it? It is time for Big Off N but you are the fourth and last driver. We will use the set only but take one driver 10253. See what is happening in it. In this, as soon as I see the element, I will add it to my set, okay, and I will check whether we have added its double in my set, that is, it is kept in the set, okay, so much silence, okay, I have added it. I saw the double of the first 10. It is 20, it is not, it is given in the set, then it goes to two, then it is seen that four exists, it does not exist, there is no problem, it is given, this is also given, then it is seen that Alexis doubles the punch, if it loses, then return it, but I take it. This is not our list. This is our list. 5103 Now see, double of 5 exists, no problem, add 2 in your set. Double of 2 exists, doesn't. Brother, only punch is in the set, so add that too, then see 10. Double axis of 5 does not do, look at that too, double of three does axis i.e. double of 3 does not double of three does axis i.e. double of 3 does not double of three does axis i.e. double of 3 does not do 6. No fun. There is something wrong in this algorithm. Double axis of 5 does, we can see it but the punch has already been given. When the punch has already come and 10 will come in the future then we are already checking the double 10 of the punch so if we are making a mess then we can do one more thing. Look carefully here as I am adding some element. I am checking one thing that whether his double axis works or not, I will check another thing that his half does not adjust. Now look like Sam of the future ca n't do anything when we are Panch Dal. Don't know brother whether 10 will come or not but we can reduce it when its double comes, its possible double will come i.e. 10 will comes, its possible double will come i.e. 10 will comes, its possible double will come i.e. 10 will come, we will check whether 10/2 exits come, we will check whether 10/2 exits come, we will check whether 10/2 exits with us, 10 bye tu bole to punch exists han. If it is 5, what does it mean that there are some elements in our list whose double exists? Well, then obvviesli, first we have to see whether that number is And or not. If it is E1, then we will see that N/2 not. If it is E1, then we will see that N/2 not. If it is E1, then we will see that N/2 exists. Doesn't do like here pay ten and han 10 / 2 exists pay ten and han 10 / 2 exists pay ten and han 10 / 2 exists doesn't han does punch Okay so this is the algorithm let's start take the code map or take the set you will take these sets you are taking which set Type Integer Type Set Name Set We will keep it equal You are ok Now what will we do Now we will put loop Forint I will check in it or its half Well for half we will first check What is I Module you equal Zero Contents I/2 If so If yes then return true. Contents I/2 If so If yes then return true. Contents I/2 If so If yes then return true. If such condition does not come then what to do in the last step. Returns false. Ok, let's run and see. If it is not put in Han side then let's put set dot add i after every iteration. After checking, we will also add it to the set. Okay, it is accepted. Let's submit. It is very good, so nothing has been done. The set has been used. Space complexity is big off and end time is also big off. One loop is run. Basically, the end which checks whether an element is present in the set or not is an operation in the Big One, so basically we have used the word double land double this. If the question is that X does not do it, then we What to do here is to check whether the Three Eye exists or not and what to check or not. There are other ways to solve it. Obviously, as I told you can use binary search, but this is the most efficient method. Apna
Check If N and Its Double Exist
maximize-the-topmost-element-after-k-moves
Given an array `arr` of integers, check if there exist two indices `i` and `j` such that : * `i != j` * `0 <= i, j < arr.length` * `arr[i] == 2 * arr[j]` **Example 1:** **Input:** arr = \[10,2,5,3\] **Output:** true **Explanation:** For i = 0 and j = 2, arr\[i\] == 10 == 2 \* 5 == 2 \* arr\[j\] **Example 2:** **Input:** arr = \[3,1,7,11\] **Output:** false **Explanation:** There is no i and j that satisfy the conditions. **Constraints:** * `2 <= arr.length <= 500` * `-103 <= arr[i] <= 103`
For each index i, how can we check if nums[i] can be present at the top of the pile or not after k moves? For which conditions will we end up with an empty pile?
Array,Greedy
Medium
134
51
hi guys this is khushboo and welcome to algorithms made easy in this video we'll see the question n queens the n queen puzzle is a problem of placing n number of queens on an n cross n chessboard such that no two queens attack each other given an integer n return all the distinct solutions to the end queen puzzle each solution contains a distinct board configuration of the n queen's placement where q represent queen and dot will represent an empty space so we are given this example which says n equal to four so here we have got a four cross four chess board and we can have two combinations of queen's placement wherein we have placed four queens on the chest board such that no queens are attacking the other queens how do you know if a queen can attack another queen or not in chess a queen may attack another queen if it is coming into the same row if it is coming into the same column or if it appears in one of the diagonals for that particular queen so these are the three conditions that we need to take care of similarly we are given the second example and the constraint says that n would be in between 1 and 9. one of the basic intuitions for this question is that you need to iterate over each and every cell in the chess board and try to find a combination so it becomes a dfs solution and secondly if you are unable to do so you need to backtrack it and try for another combination so this question is going to be a combination of dfs and backtracking so let's go ahead and see how we can use it to solve this problem let's take the same example of 4 cross 4 chessboard so these are the two placements that are possible for end queen problem now let's take one of the chess board and see what other directions a queen can move so over here we have given the path a queen can take in different colors for all the different queens so if you see this queen which is having a path of blue dotted line will move in either this diagonal or this column or this row similarly for all the other queens now if you notice for this particular cell there are no other color dotted lines coming in this means that no other queen can reach this particular cell similarly for the green one white one and the red one and so these are the safe placements for the queens so the first thing that comes to the mind is what are the conditions that we can apply to choose a safe position now a queen cannot be placed in the same row same column and same diagonal if we take this particular queen no queen should come in the same row as it is falling into the same column it is falling into or in any of the diagonal cells for this queen and if you see over here all the conditions are satisfied and so this is a safe position for this particular queen now how do we find out if the other queens are in same row same column or same diagonal so for that let's start with the same row condition if any of the other queen falls in the same row the absolute difference between the rows of both the queens would be zero that is the row for this particular queen if placed here would have been row one and this is also in row one so the difference between those two rows is zero and that should not be the case similarly for column the absolute difference of the columns of two queens must not be zero that is it should be non-zero so if this that is it should be non-zero so if this that is it should be non-zero so if this queen was falling into this column the column for this particular queen would have been three and for this queen is also three its absolute difference would have become zero and so we can say that the queens are in the same line and one of the queen can attack the other queen so we need to take care of this condition so we are taking d y not equal to 0 as a condition for same column third is the diagonal condition now how do you find out the diagonal element if you notice for a diagonal element we are going to move the same amount in x and the same amount in y and that becomes the diagonal so the difference between the x is equal to the difference between the y for a diagonal so we are going to say that the absolute difference between the rows of the queens must not be equal to the absolute difference of the columns for the queen that is dx should not be equal to d y and so these are the three conditions that we need to apply that is my dx should not be equal to 0 dy should not be equal to 0 and dx must not be equal to dy now let's see what are the different data structures that we would need in order to solve this problem the first one that we are going to need is the board the n cross n board representation so it would be a character array that would be n cross n and dot will represent empty and q will represent queen in that the second thing is to store the position of all the queens that we have placed till now so for that we'll need a list of all the positions and a position will be given by x and y coordinate so that we can take it as an integer array so these were the things that we would need next is what are the steps and how we are going to solve this problem so the first thing is to perform dfs and for that we'll start from zero comma zero that is the first cell the second step is check if a queen can be placed at the current position so for that we'll be checking if it is a valid position or not if it is we'll place the queen we'll fix that position and we'll try adding the remaining queens in the board if not we'll backtrack and check for other combinations so like this we need to find all the combinations now one more thing that we need to note over here is that while repeating the process or while recursively calling the dfs function suppose we have placed a queen over here in row 0. now while repeating would i need to start with the next cell in the same row no i need to go into the row below because we know that we cannot add the queen in the same row so we skip the current row and call the dfs function on the next row so we'll be going row by row and we'll try to solve this problem so this was about the process that is going to be involved now let us go ahead and code this out the first thing that we are going to need over here is the result which is in the form of list of string and let's initialize it the second thing is the board which is going to be a 2d character array and its size is going to be n cross n initially we will fill this board as an empty board so we are going to add all the dots in it so over here we have filled it as empty cells now the other thing that we need is the positions for all the queens that we have so it would be a list and initially it would be an empty list after we have this we are going to call dfs on the board starting from the zeroth row and we will pass this queens list so this is going to take care of all the logic finally we can return the result and this is going to be our main functionality now let's write the dfs function so this is our dfs function in this we need to see that if all the queens are placed or not so that would become the exit condition so if all the queens are placed its size will be equal to n that is board dot length if that is the case we need to construct our output for constructing the output which is in the format of list of string now the internal string represents the rows so let's take that and we'll iterate over the board for each row with this we need to add this character array as a string into the rows once this is done we need to add this particular rows into our result so we'll do result add rows and that's all our result has been constructed if this is not the case then we need to try adding the queen so we'll take a loop and try adding the queen so this is going to be iterated for a row and over here we'll take iteration on the column let's check if we can add a queen for this particular row and column given the queens that i have already added so if we can add a queen we are going to update the board with q for this particular position with this we also need to update the queen's list so queens dot add r comma c and now we need to call dfs on the next row with the updated queens list after this is done we also need to backtrack and check for other positions because we need all the combinations so for backtracking we again need to set this as dot instead of q and we need to remove the queen that we added so this is going to take care of recursively calling the function and finding the combinations now what we need is implement the can add queen method so let's write that so over here we need to check the condition for row column and diagonal so for all the queens that we have placed we need to check and see whether the current row column is safe or not so let's iterate over this and over here we need to check dxdy conditions so let's calculate dx which will be the difference between the rows and d y would be difference between the column so now we need to return false if it falls in the same row same column or same diagonal which would be given by the condition if dx is 0 or d y is 0 or dx is equal to d y if this is there return false and if for any queen this is not satisfied return true and that's it let's try to run this code and see if we have any compile time issues and this is a character array let's run this again and it's giving a perfect result let's submit this and it got submitted so that's it for this question guys i hope you liked it and i'll see you in another one so till then keep learning keep coding bye
N-Queens
n-queens
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other. Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**. Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively. **Example 1:** **Input:** n = 4 **Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\] **Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above **Example 2:** **Input:** n = 1 **Output:** \[\[ "Q "\]\] **Constraints:** * `1 <= n <= 9`
null
Array,Backtracking
Hard
52,1043
912
hi everyone welcome back to the channel and today we're going to solve with code daily challenge problem number 912 sort and array so it's a really simple and a straightforward problem in which uh they want us to solve or they want us to sort an array in an ascending order and just want to return that okay and this is the condition which we have received which is we are not allowed to use any inbuilt functions and the output should have or the code should have a maximum time complexity of n log n okay so these this is the condition and this is the requirement simple and straightforward right so uh you know when you think of any sorting algorithm which can give you the result in N log n the two algorithm which comes to the top is heaps or and mode sort right and I'm gonna use a mod sort in this particular for this particular problem and if you don't know what's actually more sort is don't worry like uh have a you know diagram prepared for that and let's just move to that and I'll explain you what exactly we do in them also okay so uh let's say this was the given array with element five two three one let's say okay so in more sort the aim is to Simply you know just divide the array in equal halves it each time until you get single elements for example we have five two three one right we divided that in five two and three one still uh the elements were not individual so we for the divided that again then we got individual blocks of elements right five two three one now uh basically we have broken down the given array into individual elements now you have to plug that back into one array right and while doing that you will compare the value of both these elements for example two and five which one is uh smaller two of course so you will put in uh I think sorry I made a mistake over here it's fine so you will put 2 first and five okay similarly in this block for you will compare one entry what you'll get one and then three okay then further when you know you didn't get the complete array right at this step so you will again merge these two sub errors down and while doing so you will compare each element uh with each other right so what it will be now so it will be one two three and five so this exact this approach is called Mozart okay and it is guaranteed to get an N log it time complexity uh with this particular algorithm so it's uh and it is also really simple to implement as well so let's move toward the coding part of that post thanks for us uh I want to check like here so what I'll be doing is I'll be basically calling this uh sort array method recursively okay and as we saw like what we wanted to have we wanted to break the elements in half at each step until we get to the individual element so if length of nouns is greater than one nums is the array which we are getting right if yes then we'll perform some operations otherwise I'll just simply return the exact same array okay now we want to divide that into two halves right so what I'll be doing is I'll be taking the flow division of the length and I'll divide that into two r or left half and look right up right it's half okay so left half will have all the values till the mid okay and the right part will have everything after it so now we have divided the given array right now I wanted to call my sort array function recursively fall for left half and right half self taught sort array pass in this left half method and in the next call passenger right half as well okay so after uh this computation you will basically get your uh sorted sub arrays right now uh what we need to do is we need to just merge this array light because we divided that we have done the Sorting on the individual level now we want to merge those as well right so what will you do you will need three pointers basically first one to uh point to your left half J Will point to the right half and the point of K which will basically point to your original nums area in which you will be updating the values right and we'll initialize that with all with zero okay now what I want to do is while I is less than length of left half all right J is less than length of later okay while these two conditions are true basically if we have any uh element in both the arrays because we wanted to compare those values right so we will follow this Loop so if left half if the value in the left half is the current value in the left half is smaller than the value current value of the right half excuse me then what I want to update the value in nums a at gate location with my smaller value left half and pi and if you know if we have put in the value from laptop I do want to increment the pointer as well right else will do the other way down we will put in the value from right half at Jade index and we will implement the JS pointer at the end of this while loop I do want to implement the K pointer as well okay so basically you have done the merging but there is a catch uh it is we are not sure that you know we will be able to cover all the elements of both these sub arrays in this file Loop so there are chances that there will be some leftover elements in I and leftover elements in J as well which you want to append at the end right so for that what we'll do while I is less than like this condition in individually this condition I want to run a loop and what we want to do this and you would like to increment K as well and we will do exactly the same for J pointer as well J is less than write half you want write out see and done so this was the complete solution this is what all you need to do uh let's check out the test cases okay AR is okay sorry I use URL okay so the test case has got let's submit for the evaluation let's index out of range I must have done something line number 28 let's see uh 28 is over here nums of uh sorry this should have been J right awesome so the solution was accepted and we perform decent like we have performed 40.1 percent of the summary of solution 40.1 percent of the summary of solution 40.1 percent of the summary of solution so yeah thanks again guys for watching out the video and stay tuned for the upcoming ones don't forget to subscribe to the channel thank you
Sort an Array
random-pick-with-weight
Given an array of integers `nums`, sort the array in ascending order and return it. You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible. **Example 1:** **Input:** nums = \[5,2,3,1\] **Output:** \[1,2,3,5\] **Explanation:** After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5). **Example 2:** **Input:** nums = \[5,1,1,2,0,0\] **Output:** \[0,0,1,1,2,5\] **Explanation:** Note that the values of nums are not necessairly unique. **Constraints:** * `1 <= nums.length <= 5 * 104` * `-5 * 104 <= nums[i] <= 5 * 104`
null
Math,Binary Search,Prefix Sum,Randomized
Medium
398,894,914
859
Hello hello welcome to Delhi report is required till 1658 we are in this news district so I will give into strips 60 units start to-do list like example with 2GB RAM by Saurabh Singh b positive thinking simple to b subscribe and subscirbe subscribe now Now To Receive New Updates Hai Ki Saugandh 300 Ko Zara Because They Had Online A Different Darkness Mein Druk Gaya Hai Main Example And Virag And Toot Saaf Birthday Correction Different Solutions For Class Twelfth Peeth Mixi This Update Please Like Share And Subscribe To Aap ten seconds sirvi bandhu tiffin size and taraf india 100 list set do ki blast case where they have different things but about option size shift subscribe to hai so lets of fixed rate so dat digital audio files from 0110 solid to properties only One and cold not afford to doing so let's see code 's journey cases stratification this medical 's journey cases stratification this medical 's journey cases stratification this medical institute for this channel is not subscribed and then size different day discovery clock on vignal tal rock it takes care of viraval pradeep just example2 10 behave with r senses one Person Champion Possible Saugandh Porn Register Checked Programs Seervi Hai How To That When 12th Ne - District When 12th Ne - District When 12th Ne - District Ko 12 Finally Abhi Hotspot District Tarf Example And A Fantastic Surf Excel Size Networking Service Friend According 500 Maintenance And Different What They Are Doing Research On 1212 corruption scams during only at least 10 minutes and friends so Vijay Prakash friends questions our difference of character between minutes and boosting while to our channel like this point to and that of election 2014 that pilot because we have opportunities so let's do 155 So Let's Organization Time Complexity Of All This Content Loot Yash Chauhan Shyam Request One Tablespoon Vikas Mishra Business Dining Table Spoon Springsteen Essay Thanks for Watching Please Provide A
Buddy Strings
design-circular-deque
Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._ Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`. * For example, swapping at indices `0` and `2` in `"abcd "` results in `"cbad "`. **Example 1:** **Input:** s = "ab ", goal = "ba " **Output:** true **Explanation:** You can swap s\[0\] = 'a' and s\[1\] = 'b' to get "ba ", which is equal to goal. **Example 2:** **Input:** s = "ab ", goal = "ab " **Output:** false **Explanation:** The only letters you can swap are s\[0\] = 'a' and s\[1\] = 'b', which results in "ba " != goal. **Example 3:** **Input:** s = "aa ", goal = "aa " **Output:** true **Explanation:** You can swap s\[0\] = 'a' and s\[1\] = 'a' to get "aa ", which is equal to goal. **Constraints:** * `1 <= s.length, goal.length <= 2 * 104` * `s` and `goal` consist of lowercase letters.
null
Array,Linked List,Design,Queue
Medium
860,1767
17
hey everyone welcome back and let's write some more neat code today so today let's solve letter combinations of a phone number so we're given a string of digits that contain only two through nine so the digits are only going to contain the numbers 2 through 9 and we want to return all possible letter combinations that the number could represent and so basically what this problem is about is like when you wanted to text people with old phones you only had these digits right so in order to have characters you'd map a number like two to the characters a b c and you can see the reason we're doing two through nine is because one was not mapped to any digits right so we don't need to consider the one two was mapped to abc three was mapped to d e f basically each number or each digit four five six each one was mapped to three characters some were mapped to four characters seven is mapped to four nine is mapped to four different characters so then if you're given a string of digits let's say two 3 in this case right 2 3 is our string well how many different output strings could we have here you can see we have a bunch right we have 9 different strings why do we have 9 different strings because this two could be three different characters it could be a b or c this three could also be three different characters d e f so three times three is nine so basically we can have nine different combinations of these characters right we could have a d we could have a e we could have a f right and so on right so we could have b e b f and then do the same thing for c right so then you would have nine different strings and so basically you can tell that this problem right like writing out the solution like this it's not that difficult because we're gonna basically be forced to brute force this problem and it's a backtracking problem because we have to brute force it right we have to basically find every single combination that we could get using the given digits and you might have noticed i've been doing a lot of backtracking problems recently and that just goes to show you that backtracking is a very important algorithm so let me just show you kind of the drawing of the backtracking solution so luckily for us in this case we're only given two three right and so we only need to find okay two maps to these three characters three maps to these three characters but we know in total we it's possible we could have a four we could have a five if we had a four we know four maps to the next three characters after this so g h i think unless i'm forgetting something and basically we could have any character right from two through nine so we're going to need to create a hash map or some kind of way to map every character from or basically every digit from two all the way to five six seven all the way to nine right and map them to the characters that they end up being right we know nine is i think gonna be xyz we're basically gonna have to hard code this map of characters there's not like a clean way to do it mainly because some of the characters i think seven has four characters right seven is mapped to four different characters and so whatever but this is a pretty small hash map right so it's not a big deal if we have to hard code it but now let's just look at this problem itself how are we going to solve it well so the first character is 2 right so 2 could map to three different characters so two being the first digit it can map to a b or c right and the next character we know or the next digit is three so from a we could have three different characters that follow after it we could have a d we could have an e or we could have an f and that's going to be true for every single one of these right we could basically put a d e f after each of them and this is the entire backtracking tree so based on this what's our solution because remember we want to know the strings that this could map to well this is one string this is another string so basically for each of the leaf nodes in this tree we're going to follow the entire like list of characters that came before that's going to be the output strings right a d a e a f and so on right b d b e b f and the exact same thing for c so when you visualize it like this is actually a pretty simple problem so now you just need to know how to write this backtracking algorithm and i'm going to show you how to do this recursively but before i do that the time complexity for this is basically the number of combinations that we're going to have so the question is how many different output could we have for a string let's say the input string is length n how many different outputs could we have well since we know that there are some characters like i think nine maps to four different characters i think w x y z actually so the brute force is gonna be four to the power of n that's how many outputs we could actually have right because maybe we'd get a string s equal 9999 right so basically we'd have four choices for each of those characters so 4 times 4 basically 4 to the power of n which is the length of the input string right so that's the number of output strings that we're going to have and the length of each output string is going to be the same as the length of the input string right so really the time complexity is going to be big o of n times 4 to the n and basically this is the worst case time complexity okay so now let's get into the code which is going to be fairly short so the first thing we want to do is have a result this result is going to contain the combination strings that we're trying to build and the next thing we want to do is create a map of digits right we want to take every single input digit that could be possible like two and map it to the characters that are possible so abc right for two and unless you wanna see me type this out i think i'm just gonna copy and paste it so this is what our digit map is going to be like and you can verify this if you have an old phone laying around that this is the correct mapping from digits to the following uh string characters so now let's write that backtracking function it's going to be a recursive function and i'm going to declare this function inside of this function so that we don't need to pass in these parameters every time we call this backtracking function and we also don't need to pass the digits that we're on i'm only going to pass in one variable i which is going to tell us what index we're at in the digit string that we're given as the input to our function and i'm actually going to pass in one more variable so the current string meaning basically the current string that we're building so let's say our input was uh one two three and the current string would contain something like a right so if we've only visited one so far we'd have a and then we'd want the next two characters from two and three so we know the base case is if i is greater than or equal to the length of digits or actually an even better base case would be our current string let's say the length of the current string is exactly equal to the length of digits that means that we've basically been able to take every single digit and then map it to a character because current string is going to contain those characters and if that is the case then we are allowed to take our result and add to it the current string that we just built and then since this is the base case after that we can just return if this is not true though that means we haven't finished building the current string that means we need to continue going through the digit that we're at right at index i so let's create a loop to do that so basically i'm going to take digits of i that's going to tell us the current digit that we're at right and i want to take this digit that we're at and i want to map it to the list of characters that it maps to right so if we had nine we know nine maps to w x y z so how can i do that well that's why we created this digit to character map we can take a digit and then map it to a character so digit to character i'm going to take this digit and now basically this is going to be the that string that it maps to and i want to just go through every character in this string so for every c every single character in this string i want to brute force this right so for every single character i'm just going to call backtrack i'm going to make that recursive call right so for i we're going to increment i by 1 because we're moving to the next digit and for the current string we're going to just take the current string that we were given and add one more character to it the character that we're currently visiting c and that's actually all that we have to do we have our single base case and we have our recursive case you can see that the only thing that might be different for you is that our recursive call is inside of a loop so with this backtracking function complete now let's actually call this backtracking function so we the parameters to give it are going to be 0 for the index and the current string is initially just going to be empty right but i'm actually going to need to make one last modification so we're only going to need to call backtracking if the digit string that we're given is non-empty and the reason is because is non-empty and the reason is because is non-empty and the reason is because if digits was empty then our recursive call would be called and then we'd execute the base case once so then we'd end up returning this as our result we'd add the empty string to result but in the way this problem is defined if digits was empty like this if digits was just an empty string the output that they actually want is just an empty array like this so that's why we have to put this inside of a condition but other than that all we have to do is now return our result and the function is complete so you can see that it's pretty efficient about as efficient as you can make a problem like this even though it's a rel it's what's it called it's an exponential function right but 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 you
Letter Combinations of a Phone Number
letter-combinations-of-a-phone-number
Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**. A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. **Example 1:** **Input:** digits = "23 " **Output:** \[ "ad ", "ae ", "af ", "bd ", "be ", "bf ", "cd ", "ce ", "cf "\] **Example 2:** **Input:** digits = " " **Output:** \[\] **Example 3:** **Input:** digits = "2 " **Output:** \[ "a ", "b ", "c "\] **Constraints:** * `0 <= digits.length <= 4` * `digits[i]` is a digit in the range `['2', '9']`.
null
Hash Table,String,Backtracking
Medium
22,39,401
295
hi guys in this video i'm going to walk through this elite call number 2.95 find through this elite call number 2.95 find through this elite call number 2.95 find medium from data stream uh so this question was asked by uh amazon microsoft facebook apple big dance and not other big names and obviously amazon loves this question so this is a object origin design question let's dive into the example in here so uh we initiate the object by uh executing this comment uh mu finder so we call it this object uh median finder so it's a new object so we push in one number pushing the second number so right now when we uh request uh the median so there will be um the middle of this two number which is a one plus two which is two uh divided by two which is 1.5 which is 1.5 which is 1.5 and then after that we push in another number now the medium will be the middle number which is two in this case um so the concept is pretty straightforward but uh the problem is how to do it fast um i will um also there is a follow-up i will um also there is a follow-up i will um also there is a follow-up question that you can think about and i will talk about my solution this follow-up question at my solution this follow-up question at my solution this follow-up question at the end of the video so uh the question was if all the integer number uh in a range of from 0 and 100 inclusive how can we optimize the solution and the second follow-up question was if 99 into the follow-up question was if 99 into the follow-up question was if 99 into the number from the stream are in a range of 0 and a hundred that means uh most of the numbers are smaller but there is some number that is outside this range could be sorry it could be uh the less the another one percent could be smaller than zero or larger than 100 so this is not necessarily a smaller side so it could be somewhere here or somewhere there so how can we optimize the solution so um so these are 34 follow-ups and we'll discuss later on 34 follow-ups and we'll discuss later on 34 follow-ups and we'll discuss later on so immediately one simple approach will be used in naive or is more like a brute force approach where we can have a list that comes with the object so and then when we add the number we just append the number to the list and then um whenever we need to find the medium we sort it and when we say the length is an even number uh we just uh take the average between the center true numbers okay that's in this case when we have two numbers in here we just take the average of two number um yeah so because in this case the length is the even length and in the case where if the length is odd and it's simple just pick the middle number so this approach is a brief force way to do it and uh as obviously whenever we execute this function it's going to be taking we have to do sorting so it's going to be taking a big o we go for n as you can see it's not very efficient because whenever we call it 5 million we have to we sort it and sort it again so all the prior information is not used so that's why i mean all the pipe information is not saved so that's why it's not very efficient a more efficient way to do it is i use two heaps and one is the max heap another one is a mean heap so in python the implementation is always a mean hip that's why we have to be a little bit clever uh to use a mean heap to implement a maxip so let me show you how can i do that so first we have the uh two heaps in here so it looks like a list in python so one is called smalls and then no one's equal large so all the number in the lodge must be greater than or equal to can be equal to as well smalls and the rule is the smallest so how to reinforce that is that we have to make sure the smallest number in largest must be greater than the biggest number in smalls so now the problem comes from how can we efficiently find the smallest amount in large and also how can we find a small uh the largest number in smalls right if this condition satisfied this is automatically satisfied okay and uh most efficient way to do it will be using heaps so uh to find a smaller summer in an array or in a list so we can use a mean heap so we can use so large we can implement it with mean heap and how can we efficiently find the largest number in any list will be use a max heap that's why uh we can implement a maxip to a small so it's kind of not intuitive right so we use a max heap to f to implement smalls and use a mean heap to implement uh large so again the idea is we have to find the largest number in smalls and also the smallest number in large and to find the largest number is moss would be i use a max heaps and you have to find the minimum number in the large will be use the mean heap also another condition we want to enforce is to look at the size right because we look we are basically breaking up all the numbers in two sections one is the number on in the on the smaller side will be small and the larger size will be large and so we and we want these two pieces to be uh more um uniformly distributed the sizes cannot be different from each level so largely um because for example if we have five numbers one side must have two numbers another side will be three numbers which is okay this is only the size is only deferred by one but if we have four numbers uh we have must have like a two numbers on each side so that's the idea um so as you can see the size can only be different by plus or minus one so yeah this is the initial implementation in the init function so in the add number section uh how can we do is um so first we push uh use a heap and push it to uh self.smalls and then and push it to uh self.smalls and then and push it to uh self.smalls and then we can but we can put push it to the self the largest as well but it's gonna be the same after you understand the rest um so because the we again we implemented a max heap a max ship to um too small that's why because in python it's always a mean if um by default so in order to use a massive you have to cleverly uh take the negative sign of the number to push it in because uh the smallest net the smallest negative number will be the largest number okay so that's the idea and here is the checking this condition right so if there's something if this smalls is not empty and large is not empty and we are grabbing the largest number in small and smallest number in large so and also this is a lot of a big time saver because when we look up uh the largest number and also look up the smallest number it's only look that lock up is only take up a bit of one for heaps and this is the condition where we have to make some adjustments so if the minimum the smaller somewhere in the large and also but that's less than the maximum the hot the largest number the maximum number in the smalls and this is where we have to make some adjustments this is violating this condition and we pop it off from the smalls because now uh the max number is too large now and uh because we the implement is a negative number so what we have to put it back to the positive side or yeah so we have to flip the sign so and we save it in the tam and then push it to the large section and by using push so this operation takes a bit of a lock and time and also this the hip-hop lock and time and also this the hip-hop lock and time and also this the hip-hop takes that much time absolutely the same amount of time for the t-push amount of time for the t-push amount of time for the t-push uh operation and then and now we are checking the length and because we have to make sure that there are these two ejection they are relatively the same size i mean can be only different by one at most so if um the length large um even minus one that's still bigger than the smalls and then we pop off the from the large part large section and then save the tam and then push to the smalls and again when we push it to small and because this is a max heap we have to put a negative sign in front of it change the design and push it and this one is the same uh time complexity a bit of lock n same for the push key push and uh on the flip side if the size is the smallest is bigger and we do the same thing but on in opposite way um as you can see the entire add number um so for time complexity uh we have to take a bit of log in and we have to make some adjustment and in the worst case it's gonna be taking a bigger login a bit of login again pick up login again and then again so five times right so um and the constants dropped so you see that the number is uh big of log n uh so this is add number and the five medium is gonna be a bigger one and this is a huge time saver so we first we compare the length right so um in the first case where if the smalls has a bigger length that means the medium will be in the small section let's say uh if we have total five numbers and the smallest we have the three numbers and large is only two numbers and the medium is going to be in the in here so let's say uh if this section is the smallest and this section is large so the medium is going to be the uh the largest number in the smalls okay and this is exactly how we can find that and on the flip side if the large is a small number and that is going to be in the smallest number in the large and also in the case waved at the same length just take the average between the two so let's submit that and it works and now we can talk about some uh a little bit about the follow up so if all integer numbers from the stream are between are strictly between 0 and 100 so how can we optimize it and actually uh there's a clever way to do it so we can have an integer array of 100 so basically it's storing the count of each number uh with a total count so basically we the we have a list looks like this so we have a hundred spot so the first part is counting uh what is what's the frequency for the number zero the second spot is currently counting um the frequency of number one right so go all the way to 100 or 99 and then after we have the count or we have the distribution of all the frequency and we can uh this is a direct lock up to the medium so the time and space complexity is the bigger one and um so phi medium is big 01 as i mentioned so also the ad num it's going to be bigger one as well because we know exactly what index we want to add to the frequency distribution so um so this is how we optimize it and the second follow-up question was if and the second follow-up question was if and the second follow-up question was if 99 of all integer number from the stream are between 0 and 1 how can we optimize it and uh when uh 99 percent between 0 to 100 we know for sure that the medium is going to uh in this 99 percent right because the medium is basically a fifty percent uh fiftieth percentile so we can keep a counter for less than a hundred and grade eight hundred um and yeah so we only need to know how many numbers greater than 100 and then we um yeah so let's say if there is 10 number it's just greater than 10 greater than 100 so that means a thousand number will be less than 100 because that uh ten number accounts for one percent and then often we know that a thousand number is less than 100 and then we can just find the medium that way and we can basically follow this up of approach again we need to have a uh in a list or an array so keep track of the frequency of the numbers this is below 100. so this is how we can optimize it if we are given these two pieces of information um yeah so this is my solution this problem i hope this is helpful if he does please like and subscribe that would be a huge support thank you so much for watching i will see you in the next video
Find Median from Data Stream
find-median-from-data-stream
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values. * For example, for `arr = [2,3,4]`, the median is `3`. * For example, for `arr = [2,3]`, the median is `(2 + 3) / 2 = 2.5`. Implement the MedianFinder class: * `MedianFinder()` initializes the `MedianFinder` object. * `void addNum(int num)` adds the integer `num` from the data stream to the data structure. * `double findMedian()` returns the median of all elements so far. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input** \[ "MedianFinder ", "addNum ", "addNum ", "findMedian ", "addNum ", "findMedian "\] \[\[\], \[1\], \[2\], \[\], \[3\], \[\]\] **Output** \[null, null, null, 1.5, null, 2.0\] **Explanation** MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = \[1\] medianFinder.addNum(2); // arr = \[1, 2\] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr\[1, 2, 3\] medianFinder.findMedian(); // return 2.0 **Constraints:** * `-105 <= num <= 105` * There will be at least one element in the data structure before calling `findMedian`. * At most `5 * 104` calls will be made to `addNum` and `findMedian`. **Follow up:** * If all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution? * If `99%` of all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?
null
Two Pointers,Design,Sorting,Heap (Priority Queue),Data Stream
Hard
480,1953,2207
81
hello everyone so how are you all so I am Aditya and I'm again with a new question on lead code today we will be solving the search in rotated sorted array so now let's read out the problem first so this is the question and we are given there is an integer array nums okay we have been given an integer array okay its name is nums okay sorted in non-decreasing order okay sorted in non-decreasing order okay sorted in non-decreasing order means increasing order okay this array has been suited in an increasing order means the elements are 2 5 6 and Etc okay so these are all in the increasing order now before being passed to your function nouns is rotated at an unknown pivot Points k welcome suppose let's Imagine This this area has been pivoted to some point k and the value of K would be zero okay so for example see it here in this example we have been given an array let me clear this okay so we have been given an array 2 5 6 double zero one two okay so here we can consider the Pivot Point here or we can consider the Pivot Point here earlier there was a similar question search in rotated sorted array but in that case there is only one Pivot Point means we can have only one Pivot Point but here we can see that there is repeated by what point means the Pivot Point can be repeated and it can be more than one okay so this is a problem now what's the question says after that now resulting array is nums K plus 1 will understand this later now we see that for example zero one two triple four five double six seven might be rotated at pivoted Point index 5. okay we have been given taking this array okay taking this array we have the element 2 4 6 8 10 okay three four five six seven eight and ten we have taken zero one two equal four five double six and seven so this is the first area that we are given and it says that it might be rotated at pi over 0.5 pi over 0.5 pi over 0.5 so what is the PowerPoint five zero one two three four and five so this is the private point we have got so it becomes this okay if I make it a pivot point so what does it become let us see that only so it becomes 4 5 6 7. 0 1 2 4 and 4 means we have to start from here we are starting from here because this is a pivot point we have been given so we have to start from here and thereafter these all elements will be written in the form okay so you must get a clear cut idea that how to solve this problem now let's move on to the next thing this is our question and come up on the example first this is the example in the array has been given nums and Target zero we have to find out whether 0 is present or not yes it is present so this is there is basically a two method two methods from which you can apply and solve it the first is binary search binary searching look I am giving you a hint then whenever you see these constants like okay whenever you see the constants are given you can imagine that to solve the quotient with the help of binary searching okay when it has been given in the 10 to the power in binary searching the time complexity will be we go of log n in most of the cases it's we go of login and the other thing is that linear you can apply linear searching the time complexity would be because when you can solve this question with the help of these two methods but binary searching is the most preferred and in the binary searching you must be knowing that concept what was the concept in the binary searching we have an array we are finding its mid position okay if mid position is greater than the first position okay if mid is greater than the previous position so what we do we just suppose this is the right thing we move this right to Mid minus 1. understood as what we do is here is the left we will increment left so this is the basic concept let's code right now okay let us move on the code section okay so here we are required to solve this question we have been given these things already we have seen it look there is a catch what's the catch there is a similar problem to Source rotated sorted array but nums may contain duplicates would this affect the runtime complexity how and why this is the catch then um how we are solving it from and how it is different from the previous question so first let us code thereafter we will see how it's different okay so let's code one by one so the first thing I will explain from The Starting Line only this is the class solution means we are defining a class for the solution okay and this is the access modifier public is termed as access modified water access modifier suppose if you want to declare something according to you for example if you don't want to show the users what constants you have declared about variables you have declared so you can make it private or protected okay but you want to make it visible to the users so you can make it public so the third thing is that I am taking a variable a function variable of type Boolean okay and for what we have an array nums and we are passing its address not I'm not directly writing the nums I am passing its address for the dynamic allocation in the Heap this is the basic concept that you have to get okay why you have to use the reference because I have to take the array dynamically in the field and the second thing is that we have been given an integer Target now the next line will be okay let me remove this okay the first thing is that what I am doing here I'm using the concept of linear searching then you're searching with time complexity we go off and okay so here let's see I have declared a variable I okay I have declared a variable I and thereafter I have run and loop for I is equal to 0 I less than nums dot size I plus and I have run a loop from 0 to nums.sidance array size okay from 0 to nums.sidance array size okay from 0 to nums.sidance array size okay thereafter I am checking the condition if nums of I is equal to Target what does it mean if for example I am running a loop from here okay and I'm running from element to element and if I suppose if I get the target element suppose I am finding 0 and ones are iterating these array elements I got zero I got 0 I will return true else what I will do I will return first that I have got no value equal to Target suppose I am finding 3 here in this array so once on iterating each and every element I did not get three so I will just return first okay so this is the linear searching method which is very simple but the main catch is that I don't want this time complexity I don't want I want to better optimize code so let's run this first okay so accepted also so no problem is let us submit after this uh okay submitted also so now I am going to write a binary search code for this so the first thing that I will declare a variable I not I let us left is equal to 0 I will declare another write is equal to none start size minus 1 understood now what I will do I will check while left is less than equal to right what I will do I will just find the mid would be left Plus right minus left upon 2. okay and now I will check if nums of mid is equal to the Target then what I will do I will just return oh okay if I got nums of mid is equal to Target I will return true yes I founded it okay else what I will do okay let's take elsef as if I got nums of left is equal to nums of made and nums of right is equal to numbers of mid this is the important catch here please check it out I am telling this I am checking this condition y because I may have a repeated character as we have seen that there is a pivot point and there could be a repeated character here okay there may be a repeated character in triple four so it might be a case that in the left digit is equal to the mid digit and the right digit also okay so we have checked this condition let us remove else part here it was a mistake and in this part why what will I do just remove it what will I do I will decrement the r firstly I will increment the left plus and right minus okay now what will I do I will check else if nums of nouns of I with nums of I not I itself it's left okay is less than equal to nums of mid in this condition I will check one another thing what's another thing that if Norms of left is less than equal to Target and The Arrogant is less than what nouns of mid okay so in this case what would be returning okay in this case uh don't return anything you just make the right is equal to Omega minus 1. in the else part what I will do left is equal to Mid plus one understood this concept I have already discussed it okay thereafter let's see the another case else in the else case if checking the another condition if number is less than Target and end Target is less than equal to nums of right I will visualize everything don't worry in this condition just make the same thing I think left is equal to met plus one and the else case right is equal to minus 1 okay and here just return false in the else case let's run this we will definitely get error I know so made okay I haven't declared it the data type now run it okay very nice we have our question has been accepted and let's submit this wrong answer okay so test case not fast what is the let me see the question once again the code once again is equal to minus one next one once again it's kind of mistake okay now again we have to find the article the variable return the size minus one while left right what have I done declared Madness equal to Target return to if now I'm suffering equal to remote left S Plus right minus the okay at last year we have three open curly braces let's remember that one here okay it has been closed there after this has been closed the code is why it avoids the disk is not fast okay so I think uh we have to remove this move this thing and just write elsewhere now let's submit this problem again okay so our question has been accepted done so this is the binary searching we have founded the mid check if mid is equal to Target element we have returned true else if what I am checking if num if nums of left is equal to Mid and lumps of right is equal to mince means all the values in the left in the right and in the middle is same so what will I do I will just increment the left and decrement the right by one okay else if mid is greater than left number and Target is greater than left and Target is less than mid okay so Target element may be in the middle of the left and the middle so what I am doing I am just decrementing right to the mid minus one else and incrementing left to Mid plus one and just opposite thing I am doing in this slope as I have returned first at the last stage so this was the question please leave any comment if you have any doubt and be sub
Search in Rotated Sorted Array II
search-in-rotated-sorted-array-ii
There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values). Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= 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,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`. Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._ You must decrease the overall operation steps as much as possible. **Example 1:** **Input:** nums = \[2,5,6,0,0,1,2\], target = 0 **Output:** true **Example 2:** **Input:** nums = \[2,5,6,0,0,1,2\], target = 3 **Output:** false **Constraints:** * `1 <= nums.length <= 5000` * `-104 <= nums[i] <= 104` * `nums` is guaranteed to be rotated at some pivot. * `-104 <= target <= 104` **Follow up:** This problem is similar to Search in Rotated Sorted Array, but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
null
Array,Binary Search
Medium
33