id
int64
1
2k
content
stringlengths
272
88.9k
title
stringlengths
3
77
title_slug
stringlengths
3
79
question_content
stringlengths
230
5k
question_hints
stringclasses
695 values
tag
stringclasses
618 values
level
stringclasses
3 values
similar_question_ids
stringclasses
822 values
1,502
Hello Hi Everyone Welcome To My Channel Life Events Subscribe Please Subscribe My Channel And Solve The Problem Can Make Arithmetic Progression From Sequence Sudhir And Sequence Number Scotland Arithmetic Progression Difference Between Any Two Consecutive Element Is The Same Truth Can We Rearrange To From The Progression Other Wise For Example 1351 Adhir 132 And Different Between And Differences Can Form A Process With Before vc The Difference Between 1251 Nomination Video *And Forrest To Which Nomination Video *And Forrest To Which Nomination Video *And Forrest To Which Is Not Same Subah It Is Not Forming Arithmetic Progression Switzerland So How Will Solve This What Is Arithmetic Progression Convention s per wikipedia torch light as a yes 168 portion is in the form sold and it of and monitor measure plus and minus one * DJ comedy differences of and minus one * DJ comedy differences of and minus one * DJ comedy differences of customs here is the first come first term of hua hai ki and is the Number of n h term and storm and j comment difference and skimming difference common difference between systems with it peace form is the form of comedy that this amazing F1 plus d ko my plus 2 d that com come and shown in 12th me plus and minus one Day Members And So On What We Can Do For The Given Are Is Indra And Models Will Do Subscribe Solid Second Time Will Get All The Number Likes And Subscribe Number Is The Difference Between Two Dates Are Born In Liquid Liner Wash Bigg Boss Length Of Great Khali Wave Women From Hello How To Hide From Two To Eye Lashes Then They Are Not Like Any Plus No Will Just Checked The Relief In This Will They Are After Eye - Checked The Relief In This Will They Are After Eye - Checked The Relief In This Will They Are After Eye - Puberty Course Not Equal To Define The Difference Of Two Consecutive Terms In The Process And Returned From Fear Can For The Protection Subscribe To Thanks For Creative Work In Art This Teaser Kinglets Embed Code A Committed To Accept What Is The Time Complexity Of Dissolution So Is Not Valid And Login For The Time Complexity Of Dissolution Is A Yes Sir Time complexity of dissolution is form of a login that can we further optimized so let's try to think they are more so as they no like these terms will form solves the first minimum one our arithmetic progression and last tip of the thumb is the maximum favorite song Maximum and Minimum of the World with the Giver Total Difference Minus One Can Get Rid of Phantom is Egg Plus and Minus Wave 2K Ki and Fast t1 First Mrs Vishnoi and Max Value of Power and this is the Value of Subscribe - - - - 1m of Subscribe - - - - 1m of Subscribe - - - - 1m A Message Will Guide Total Difference And Minus One Times Friday 20 Nov Will Check Reddy Comment Difference What Is The Difference Is 30 - Comment Difference What Is The Difference Is 30 - Comment Difference What Is The Difference Is 30 - Steve Waugh Yes Brother And Minus One No The First Time The First Amazon After Everyday In What We Will Do Will Inform All Items Apps curtain sequence like plus a pimp girl a b plus two depends upon and this number shoot present in every soul who will check the numbers painting or not withdraw first absorbs solar 383 and saw in the early age plus particular held minus one day i am Present in our and noida value and you will get the maximum - minnum will get the maximum - minnum will get the maximum - minnum divide boys way in this will check this old values ​​after way in this will check this old values ​​after way in this will check this old values ​​after way fight like and new property vitamins not inherited from the arithmetic progression so let's element co dog video 234 min variable in first view Will Win A Prize From Interior Dot Max Value In The Intellect Beach Fuel Beerwah Which Will Always With You What Will You Just Simply Draw The Numbers In Amazon Quantum Numbers Are In And I Will Update Our Main White Maths Ka Math Dot Minnum A Number Ensemble Updater Maxim Actor Will Update Here And Share No Veer They Will Get Death - Dependent Which Is This Veer They Will Get Death - Dependent Which Is This Veer They Will Get Death - Dependent Which Is This Maths - Maths - Maths - Yes Main Barf Bus Vwe Khali Check Weather They Are Getting Proper Notes for the Effigy Mode on the Number of Let's Get Rid Of Length L 154 Straight Twitter And Minus One And Sacrifice 900 To 1000 Vice President For Mother Saw A Great Salute You Will Be Amazed 0 Oil Din Thi Just Tried To Check An Alarm Set If It Set Note Content Our Will Update As Per Will Come In And Continue To return for the benefit of doubt will update Plus 2 and he has also been hidden - Times and Plus 2 and he has also been hidden - Times and Plus 2 and he has also been hidden - Times and the Devil V2 Divide - the Devil V2 Divide - the Devil V2 Divide - Novel and definition of Plus software in 1m for doing all the times of the arithmetic progression and will attain true they are not able to Return from this is the solution ki awadhi richa semikaln is singh in it and is n't that juice ko iman bhi pending anti aging and hair cutting correct so let's samriddhi solution me eggs accept what is the time complexity of the soul e feel sorry seriously peace running For all the end times and also the 554 operation and he has also been running time social time complexity of solution is form of n that handy space complexities also point is 200 so like it in solution class hit the like button benefits have any questions page center comment section and subscribe to my channel for the future upcoming videos thank you
Can Make Arithmetic Progression From Sequence
construct-k-palindrome-strings
A sequence of numbers is called an **arithmetic progression** if the difference between any two consecutive elements is the same. Given an array of numbers `arr`, return `true` _if the array can be rearranged to form an **arithmetic progression**. Otherwise, return_ `false`. **Example 1:** **Input:** arr = \[3,5,1\] **Output:** true **Explanation:** We can reorder the elements as \[1,3,5\] or \[5,3,1\] with differences 2 and -2 respectively, between each consecutive elements. **Example 2:** **Input:** arr = \[1,2,4\] **Output:** false **Explanation:** There is no way to reorder the elements to obtain an arithmetic progression. **Constraints:** * `2 <= arr.length <= 1000` * `-106 <= arr[i] <= 106`
If the s.length < k we cannot construct k strings from s and answer is false. If the number of characters that have odd counts is > k then the minimum number of palindrome strings we can construct is > k and answer is false. Otherwise you can construct exactly k palindrome strings and answer is true (why ?).
Hash Table,String,Greedy,Counting
Medium
null
227
hey what's up guys in this video we're going to solve this problem basic calculator 2. we have to implement a basic calculator to evaluate a simple expression string the expression string contains only non-negative integers addition to only non-negative integers addition to only non-negative integers addition to obstruction multiplication division operators and empty spaces the integer division should truncate toward 0. that means we have to discard the decimal part for example if we are given this string here we have to evaluate this first so 2 times 2 is 4 plus 3 is 5. the order is that first strip to calculate division or multiplication then addition or subtraction for example here we have three divided two and output is one if we divide three by two then we get one point something okay and we have to discard the decimal part so we have just one and for this input first we have to evaluate this expression first 5 divided 2 is 2 because you have to don't get toward 0 2 plus 3 is 5. here we have note we may assume that the given expression is always valid and we can't use any built-in library function use any built-in library function use any built-in library function all right guys how we can solve this problem now let's see how we can solve this problem to solve this problem we're going to use stack for second understanding let's assume we're given this string first we're going to iterate through this string from left to right first we have the digit 3 and the sign of this digit is positive if we see a sign of a digits is positive or negative then we'll insert that digit to stack so we'll insert the digit 2 stack then we have the digit 2 and the sign of this digit is two so let's insert this digit to the stack then we have this symbol multiplication okay and we have this digit two and what we're going to do we're going to multiply that digit by popping the element from stack so if you pop over to the element from stack then we'll get this element 2 and it will remove that element as well so 2 times 2 is 4 then we'll insert four to stack okay then we're done now what we're going to do we're going to add the value from stack so stack dot puff is 4 plus if we again use stack that puff then it will return this value and it will remove this value so three plus four and that will be evaluated seven for better understanding let's take another example if we're given these strings let's see how it actually works so first strip 22 and the sign of 22 is positive so let's insert 22 to the stack then we have the digit 3 and we have the sign of this digit is negative so let's insert three to stack and this is negative okay then we have multiplications and we have the digit five so pipe times stack dot pop stack that pop is minus three and it will also removed minus three from the stack so five times minus three equals to minus 15 okay then we're going to insert this minus 15 to the stack and we're done now we have two element on the stack now what we're going to do we're going to add that to element so 22 plus minus 15 is seven so for this expression the answer is seven let's take another example for better understanding so if you're given this expression then let's see how it works first we have three the sign of this digit is positive so let's insert two stack okay here we see we have two and before we have multiplication so two times stack dot pop two times stack that puff is three and it will remove this element from stack and it will be evaluated six so let's insert six to stack then we have the digit 4 and we have the operator division before this digit 4 so what we will do we will divide stack.puff with four so stack that proof stack.puff with four so stack that proof stack.puff with four so stack that proof is six and divided four equals to one since we're turn creating toward zero and it will also remove six because pop method return the value end also it will remove the value and we have now one so let's insert one to the stack then we have the next digit is two and we have the sign before this digit 2 is multiplication so 2 times stack dot pop stack that pop will return 1 so 2 times 1 is 2 okay so this expression will be evaluated too and this is how we can solve this problem this solution will takes big of n time complexity or n is the length of the given strings it will also takes figure of enzyme complexity to construct the stack i'm not going to go through the sudoku code i will attach the source code to this video check that out link in the description all right guys this is my solution to this problem thanks for watching this video i'll see you in the next one
Basic Calculator II
basic-calculator-ii
Given a string `s` which represents an expression, _evaluate this expression and return its value_. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of `[-231, 231 - 1]`. **Note:** You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`. **Example 1:** **Input:** s = "3+2\*2" **Output:** 7 **Example 2:** **Input:** s = " 3/2 " **Output:** 1 **Example 3:** **Input:** s = " 3+5 / 2 " **Output:** 5 **Constraints:** * `1 <= s.length <= 3 * 105` * `s` consists of integers and operators `('+', '-', '*', '/')` separated by some number of spaces. * `s` represents **a valid expression**. * All the integers in the expression are non-negative integers in the range `[0, 231 - 1]`. * The answer is **guaranteed** to fit in a **32-bit integer**.
null
Math,String,Stack
Medium
224,282,785
219
hello everyone welcome to learn overflow in this video we'll discuss another L problem that is the contains duplicate 2 this is a easy type problem and we'll understand how we can solve this problem and how we can think of finding a solution to this kind of equations so first of all the question says uh given an integer ARR nums and an integer K we return true if uh there are two indices I and J in the array say that nums I equal to nums J and absolute value I minus J is less than equal to K so what it means is like we need to return uh true if and only if we have like two different uh indices uh in the array where the value at this indices are equal that's Nam equals num so values are equal and the difference between them okay the difference between them is uh less than equal to K okay so that's the thing we are looking for fine so it's pretty simple like you are traversing the whole list and here you are trying to find out if there is a duplicate to see the difference between them should be less than equal to K right that's the idea that's the whole idea now how we should try to find a solution to this okay how you should do that now there can be two ways to do like find a solution to this number one you can use a hash map and the other approach is using a sliding window concept okay so I will discuss both of them so first of all if you're using hashmap so what your idea will be you will first of all you'll Traverse the whole nums one by one okay and what you will do you will first try to find out like whether this hashmap contain change the particular value say you have 1 2 3 and one okay now first of all you check whether you are at the first one okay you will check whether the hash contains this or not no it doesn't contain so you simply add this value okay you simply add this value uh like this value one with map two what map 2 is index what is the index zero fine that you do next you found two is it there within our uh map or not if that map do contains two no so we just map two with our what we just map two with our value means the index IND one over here then find three so we again map three with our index two fine now the next thing is we found one fine now we found one and we find that one is there in our map already now what we need to do is like what's the current index of one is three F so we'll do three minus what is the previous like map. get one so previous index of what so we get zero so 3 minus 0 we find if this is less than or equal to our K if this is less than or equal to K we return true but in case this is not less than equal to K let's say this is greater than K okay what will happen we'll simply add uh map do uh like map. put what this one comma will update this zero to three right because we why we updating see like the idea you need to why we updating is mainly because the difference we already found is greater than K okay we're considering this difference to be greater than k for this example let's say the difference we already found is greater than K so we need to check whether there is other value within that uh is possible or not like other values within the whole num why the difference might be possible because zero is already too far off right we already found that zero is too far off and this is cannot be value so now we should check we should update this value with the current index so that far if we find another one we will see the shortest distance not the whole distance previously okay so this is the idea now this approach is pretty simple and much faster as well so here we just simply updating keep updating and once you find we return true okay so this is the first approach the next approach we have is uh using an sliding window concept okay so what the sliding window is we don't use a set like hash map for this rather we use a hash set in this case okay so what we'll do we'll uh first of all we'll travel to the whole uh as always we'll Trav to the whole ter fine now we'll check if this uh sliding window already contains our or better say we'll check whether our has uh set contains our one like this contains a value or not fine if it contains a value it true but you'll say wait how you can say that okay the next comes here we'll check whether the index is greater than equal to K if our index is greater than equal to K we'll remove it okay see how it is does okay so let me just change it to two Okay because it is giving me true for three so let me change it to two for that it will tell me false now say consider this thing how we going ahead with that so first of all we are checking um if our sliding window or say the set contains our num index we should return true fine and if our index is greater than equal to K we should remove that value like previous value from uh like from our window so first of all first thing first is like keep adding okay so first of all we got a set over here so first we just added one okay remember set doesn't store them in exact order so it can be at any order so I'm just writing it in the order first of all we added one fine next we uh found two that's two is there no so we added two fine similarly we added three because three is also not there previously in the set now the next thing contain comes is the next thing we come ahead is one now here comes the question okay so here we will check that what is already there in your set yes we return true right so this is the first condition we'll see that if one is already there in the uh set we return true but the question here is how this is valid the valid is like we'll keep a check whether a current index okay uh current index I'm saying is greater than equal to our K on if a current index is greater than equal to K what we'll do we'll remove our current value okay see say where we at three right the index is three so three is greater than equal to K right so what we'll do the first of all it will happen at three at this portion fine so for that what was the index was two so index is greater than or equal to k iated is two right so index equal to K so what will happen it will remove nums of index minus K so nums of index was two okay minus K is like index was two k was two that's the equal so we'll simply remove nums of index minus K so what that will happen is like nums of zero will get removed what's the nums of zero nums of Z is one so that's how we removed that fine now we'll check one and we'll find whether one is there in our list or not if it's not there we'll simply uh we'll simply update that Val or we'll simply say true if it's there we'll simply say true or else we'll keep updating and if the end of the whole array we didn't find any True Value being return so that means we return false okay so this concept is also a bit interesting so first of all let me just quickly write down that hash like hash map concept then I'll use this I'll show this set concept like how this set concept is working okay let's go ahead with that so let's see what we did with this question we got first we checked for k equals z or not so why we checking this uh just because see K is already given here F K is given here uh K can be zero in our constraints right so if K is zero that means we are at the same index okay but our question ISS this should be uh distinct indices right so k z is already false right then we took a hash map in the hash map we like first of all we Travers through the whole nums array and in that we took each of the values okay so we just checked if our value is already there in the hashmap if our value is already there then we try to check if our I minus hashmap dog so the hasgate will return as the index previous index so I is less than equal to K if it is so we return true and in the normal case if this is not there or if the value is not uh like if the subtraction is not less than equal to K we will return I put Val comma I with the index and the Val we are putting it fine another thing we need to look for over here is like see we are said that we should be the absolute value of IUS a right but see over here like would it create any kind of problem over here like any kind of negative numbers or something like that no why is it so because by default I is something see if that value is contains in that so I is something on the right hand side right so what I mean is say what I mean exactly is say uh there is like one two like this one two three and then one right so whenever this first one get executed hash is not there so that means hash doesn't have that value for sure right so first of all we don't encounter this statement right and statement like the rest part get encountered now whenever we get the next one right that time contain value is true we will encounter this so where is I currently pointing I is currently pointing at the rightmost point right and has. G Val is something pointing before that right by default is something pointing less than that or before that so it will always a positive number so that's how it is okay I hope you can understand that it will always be less than that so that's how we ask us to make absolute value but we are sure over here that we don't need to take absolute value because it will be positive by default right so that's how it is now uh if that is the case we simply uh return true okay we simply return true if this both becomes true okay and else we just simply keep adding our value update of value in our hashmap fine now if you just check for it runtime then you will see uh that this runtime is something like U let's run it so it comes up to be something like 57 MS uh I think it can be less than that as well but okay there's no problem with that anyways L code is getting mad 5766 anyway it doesn't matter let's look at the next uh kind of approach we have the next kind of approach as I say is like a sliding window approach okay in the sliding window approach we will uh simply update our uh this map with a St let me show you the code for that so here is our the sliding window approach so what we doing we just took a set okay set as you know set will always store our unique elevs now what we doing we are traversing through the whole num s okay uh in the whole num are we just checking if a window like this sliding the state contain num ofi we return true okay so for the initial cases this value this Cas is won be true so for the initial numbers we will keep checking for this window should add the NS ofi okay so if a window contains nums ofi we return true if it is there right but you as I said you will point out how this is valid because we need to check for the absolute value so that absolute value comes from this part so we're checking if that I that is the current index is greater than equal to K okay current index is greater than equal to K we'll simply remove a value that is in nms of I minus K we simply remove the value that is far off from the window okay or that is far off from the range because for absolute value to be less than equal to K we should look for that range only that K number of elements we should only look for we should not look for much values much beyond that right so if the index is greater than equal to we should keep removing elements from that okay we should keep removing elements so we just removed 11 that is much bad previous to that so I minus K so if K is two and I is currently also two so I man remove the zero index from our num s okay so that's how it is it works so if I just run it we'll see how it works for us right now so here you see like I don't know why uh this blit code has this uh problem it comes up with much greater but this is not that high solution okay so here is see like this works pretty fine it works 59 Ms but it shouldn't 59 you should get it much lesser than that so that's it guys so that's how you just do it and this uh the last approach we are talking about the map right but we can check for another like a bit simplified version of that map also uh that map can be a bit simplified so let's quickly see that solution also so here's a map solution but see this map solution is like bit simplified how it goes uh as always as the k equal those things are done okay now what we did we just keep on checking uh we just keep on checking that is uh the whole length like the whole num that is being traversed okay so that whole num that is being traversed and in that how we're going head with it is like we took like map. putut nams and I fine so this is the Bing put so nams and I and it will return the index F now what will happen we're checking the index is not null that is the value is uh like previously not there then it will be null so if the index is not null then what will happen we'll just check for the absolute Val as you said you can do the reverse as well so I minus index or index minus I is like uh you can do fine so if you just do IUS index then also it should works okay so I is less than equal it's like the same concept but we're just making use of the uh return statement of the maput returns as a value okay that's a previous value if there's okay so whatever the previous I value there it will return us that okay so map the put does that way so it's a bit improve you can say let's you can say run that so if we just run that it will say it might improve our solution see this uh goes down much faster the 100 10 millisecond solution how it improves this is like you are not checking for the map dot uh those checks that whether map dot contains key or not whether this value is there or not okay you are simply doing a maput if the maput is like previously there's a value there in our map it will return us that uh like that maap value or if there is nothing it as null so we're checking if the index is not null that me it's there are some Val right it return us that Val so using that particular concept we can see that's simple modification we just improved our solution to much higher okay just a 10 m solution okay so I hope this can be understood how you can go ahead with this solution so thank you all for watching this video also like this video and comment down if you have any doubts to the question I'll be happy to help you out in the comments as well so thank you all for watching this video hope to see you soon in my next video as well thank you
Contains Duplicate II
contains-duplicate-ii
Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`. **Example 1:** **Input:** nums = \[1,2,3,1\], k = 3 **Output:** true **Example 2:** **Input:** nums = \[1,0,1,1\], k = 1 **Output:** true **Example 3:** **Input:** nums = \[1,2,3,1,2,3\], k = 2 **Output:** false **Constraints:** * `1 <= nums.length <= 105` * `-109 <= nums[i] <= 109` * `0 <= k <= 105`
null
Array,Hash Table,Sliding Window
Easy
217,220
449
Hua Tha Hua Hai Ya Welcome To Learn For Defeat Tubelight Engaged In Order To Play List Challenge Dinesh Mahato Problems In Our Lives And Discharge All Tasty Cylinder Follow Swasthya Asking A Given At Not Being Able To See You Release That No Interest In The Ninth From The Thing Which Should Also Be Built During 1128 Sanjay Dutt Method Something Like This Is The Servi For Mother Inside DC Laxman Yogendra Singh From Basis Return From This Cross Tanveer Plugin Free From The Problem Day So Let's Check Example Gaya So Let's A Brief History Subscribe The Channel Please subscribe and subscribe the Channel subscribe Subscribe 6 And Monitoring Ek Minute Voucher Distinguish All Elements Like News Delete Aheer Vriksh Chakma Suit Which Element Event Delhi Metro From Suvansh Wear Pass Must Follow That Is The Current Value Which Is The 6 Else Left And Go To right in recceive mera haq hai 200 g to lap top 10 richest do ki yeh abhi tu na again hair for this particular tree sub tree e want to go for the spot reversal so current lie wa saunf what is left and right way to traverse for This Particular Tree Accessibility Settings Node 281 A Navodayan Father Not Right For Vanasthali Vidyapeeth Ko Back to 10 Particular Share It Back to 10 Particular Not The But And Travels Right Of The Brightness Ko Again Be No More Notes For Relief Notes And Against 128 Welcome Back To snatch from set up to the child of veervrat current status of vitamin c tomorrow morning to take eight daily to log in lap left in the right of it surya 2016 sharad purnima free mode on travel destination for android and can observe every session late from 10th Function and its node in java using spring dales school dress that it is acid to one i android and is android app and common sense of your interested can again call daughter-in-law that and what to write on interested can again call daughter-in-law that and what to write on that west machine line you stop man Does not usually not otherwise no child who studied as net swift only that suitable at this time to equal to null any to directly written on that dont do anything understand what type for morning and painting to the spelling of the current note's value And Dainik Ma Anjana And Falling In Recessive - 10m Function Anjana And Falling In Recessive - 10m Function Anjana And Falling In Recessive - 10m Function Passing The Left And Right Leg This Vimana Developed Function To Build 1000 Years And Severe Always Pending 100% Function And The Severe Always Pending 100% Function And The Severe Always Pending 100% Function And The End Of The Knobs To Maximum Which Country Of The World In The Thing Like This Serial Wise Form of the Criminal Na How Can We See Cardamom The Great Soen Dresses Also We Can You Same Function That's the Way Can You Same Logic The Statement in the Previous Song Will Be Rooted in the Soil and Share Function One Is the Difference Like Share Initially E Will Bring His Life In Middle Decide Using Spring And The Thing Which Will Get Destroyed By Decide What Are The 966 Rudhe Left And Right Side Mein Left And Right Subscribe And Subscribe The Who Is The Present And Right Chal Dissolves Great Danger Point Which Also Means The Best Love Child The Value Of Love You Will Never Be Greater Than 4000 Female Candidates From Falling Into Its Spirit In This Tours In Com Gaon Ke Ram Calling Function S U For Watching This A Given A Name Singh The Current Intake Late Se Aayi Hoon Tu 6000 Se Zor Aur Lekin Aankhen Sign Index Equal To Zero A Probable Teri Bhalai Ke Music Global Traffic Dependent High Court Zero Phone And Urine Pass Index For The Subscribe Point Se Prithvi Process In Which Can Check What Is The Most Valuable Vote is highest value now the highest value will always also must apply for the factory in further rights act with highest value can be anything written in 3ds max value but no the lost when is must 12th class 8 in villages and validity of baroda rights act will Always Be Greater Noida Route Right Main Front Similar For The Factory In Study Subah Always Different But They Can Do Anything Can Be Interested In The Current For This Particular Not True Not Current Sure Vyke B.Sc B.Sc B.Sc Ok Soiling Dysfunction And Alerts Is Function Returning Airplane mode on line return directly dadri noted jai hind this particular function ok and all logic will happen in 12 10 2018 meeting is the fun are the index i aur darshan se global anti 500 index i hai ko share it will know value and what is High value that your morning and traversing to the spring right now always in current first wisdom between the lion itself lights and sense initially vitamin volume according to water is the way also a change for standard act has been that water can directly a good but not destroy Land acquisition left to reverse entry not right again the same day ago that show your wedding free mode travels he also be doing episode aur bata but veer vinod gaya gwalior current month according to my singh and in ignorance recursively calling function passenger left and right hair oil To the same thing but this time water is the current indexes affected closed loop we cigarette note and notes left and right values ​​for note and notes left and right values ​​for note and notes left and right values ​​for the tile recursively call me back to function OK passing the low and high new year where falling back to for left the low will B What is the current flow rate Vikas 98300 Initially do not sleep at all from the facilities provided by business Basis of tree I will be in current notes Bye good night in the morning I will be from the field Teenager current notes person M.Com 1st not from Sim Lift Up person M.Com 1st not from Sim Lift Up person M.Com 1st not from Sim Lift Up To Main Passing I Are Believe Suicide Note That Were Trying To Fight For The Tried Not To Love This Current Security Bill Pass Now This Sample Singh High Apps Badlo S Nau Festival Is Okay And The Best Condition For The Function Will Be Chief My is not under age white is not in the range of lion he is swift is not paying rich that in this great tunnel is not in thin but has written null and here right rai pai can win all its effects of i that hd mp is basically choice Safedi Dal Story Ko Show MTV India Wife Equations In That Case Of Subject Use Not A Superficial Around Delay Dwarka Service Preorder Traversal 100 Just Copy The Same Method Name That It Shyam Khedi Mein Arguments In Builder Facility Taken From The Thing And Oils Method From This Sthal in Serials A Person Rukma A Single Drop Shadow Fight 2 To Bas Singh Jasbir Hero Shri Radhe Ratan That I Will Recruit Sonalika Directly Return MP Singh And Similarly Hear Your Route To Internal Liye Button To Hell Apni Ichha What Method Should Only To Return in silence to be written statement this sn2 sb daughter and married but a well a start-up and start-up and start-up and that amazing delete aroma show elephant with common indiscriminate trees exactly the same method share price 210 will take care of govind singh songs again play music Free mode on free mode of will take care of current node in the left and right so left and right back to take care in reduction in maternal and discrimination and safe roots sex system that little knowledge of Reliance is the base condition that you data that Equal two anal and 1617 that this is can return why not hello how are coping from i third year and e almost to pass law and in 51818 second what is the height that in her before falling at mathura and spirit two lion soldiers Singare the spirit by coma the internal call rate districts muchad ne sadalbal printed milne hai he will be increased max value because at the root i don't no matter which has been 19 march and i love you g a very bihar intermediate 120 hai and shanti Index 2014 Calling This Method Right Short Inductor Keep Track Of Which Index Fund Data Is Renew Which Is The Current Intact And A Greater Noida Buddha Index Global Variable That If No Fear Know The Main Data Will Never Been Also 10 Inch 10 Condition Improved Tubeless condition that can be used by index greater good thought and investigation into a tunnel and calling this developed and includes data of indus dot length equal to your knowledge can happen because sep it pending for its matter and answers when he did not come forward and value Daru Be Interesting To Here And Just Checking The Dentist In That Is Written Not Gya Ka Aadhaar Condition Snorting In Hospital Arrange Right Any To Eternal Share And Checking The Same Thing But In Date Of Induced In What Where Is The Current Spread In The Amazing And 1 To My Love You All Respects Greater Than Enough To High Value Added That Operates In That Case Returner Sunao Share Tabs Condition Now Is The Same Thing Dare Devils And Deccan Chronicle The Current One Person Job Not Valid Screen ODF Intercurrent Remedy Can Enter And Suno my current inductive effect depends in preventing and sector-17 that I am in preventing and sector-17 that I am in preventing and sector-17 that I am se not left to echo unknown ka dead body nikal se method passenger data ko ma no sense loop slow will be same was the function of but I will be in current notes owner not Hi issue in 12th Pound must be here and there Status value is not in the stranger tides Low and high and tolerant return Addiction Smile of will make this Singrauli flight tickets will call the same function but this time elections will be I current notes value and hybrid was Hiked that was passed into the function in the eastern and western the note a solid CO2 now taken care of all the condition sahrdaya index do it length or date of indic short length 10 eternal give doing enough and top get offended information vikas singh are and computing In line only Sudhir Vyas and shifted to preserve and eternal give entry no definition in the hear a year after year to interest dot print deposit setting are cent to convert 10 value * invalid value * invalid value * invalid today form in greater noida and again we discuss video calling Collect Select So Let's Transcode Officer Test K Space Create Time 10 Keys Instructable Chapter Improvement Time Officer Algorithm Belief And Password Have To Go Through Which Every Element For Not In The Desert Using Your Response Setting Of And Will Be The Addition Space And The Time Complexity Of India Has Been Going Through Each and Every Element Choudhary Facility Just Another 10 Videos Upload Solution Class Ninth Question Regarding 1000 Comments Section Thanks
Serialize and Deserialize BST
serialize-and-deserialize-bst
Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a **binary search tree**. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure. **The encoded string should be as compact as possible.** **Example 1:** **Input:** root = \[2,1,3\] **Output:** \[2,1,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The input tree is **guaranteed** to be a binary search tree.
null
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Search Tree,Binary Tree
Medium
297,652,765
725
hello everyone welcome back here is vanam and today we got a fascinating problem in our hands we are going to dissect solve and understand a medium level problem on linkcest list from uh lead code daily challenge so if you uh someone looking to dive deep into words of data structure uh particularly Link at list uh you are in the right PR all right so let's first understand the problem split uh link it list in parts we are given a singly linked list and an integer K and our task is to split this list into key consecutive Parts but there is at Leist notice uh in this example each part uh of split list has nearly equal notes so this is our challenge so keeping the length of each part as equal as possible so given one 2 three and key five uh we have something like this and in the second example we need to split it into uh three uh parts and you can see that uh each part is uh yeah consists of four elements three and three so before diving into the code Let's uh take a look at our plan so first thing we need to know is length of our list once we have that we can determine how many notes each part should uh ideally have and how many parts uh should get an extra notes so uh with this knowledge we can then Traverse our list uh creating the parts and that the essence of our uh solution so let's get uh to the uh most exciting part so coding this time in uh python so uh length and current and part will be zero head and all right and then while current length + current length + current length + one and current will be current next okay so now we have our length and base size extra will be def mod length of K and current will be uh one more time head so now uh for uh in range key damy will be link note and part head will be just dummy and then four in range base size yeah base size plus extra note greater than one so it's greater so we have two Loops orderwise just and dumy next current dami current next and current so if extra greater than zero extra decrease and dami next will be known and part upend uh part head next and we return our parts okay so this is implementation we can uh run to verify it's working uh so yeah uh so given this uh list and key five we have this output so all good and second test case also uh pass okay so what we uh did in our implementation so we started by calculating the length uh so it's simple Traverse move through each node and keep counting so now that we have our length using python div mode function we can get the base size of each port and how many extra notes we need so this is a crucial part uh for our logic and now uh we uh just look uh key times to create our parts so notice how we use a damin Noe uh so it's a nit trick to simplify the creation of each part so uh inside this uh second Loop we create node based on the uh BAS size and if there are any extra nodes uh needed so uh our implementation work so let's submit it to double verify uh is working as expected so yeah as you can see it's bit 92% with respect to Rand time I have uh 92% with respect to Rand time I have uh 92% with respect to Rand time I have uh yeah best time of I think uh yeah 32 milliseconds but yeah probably different test cases uh different results uh so uh yeah all good yeah it was even yeah 32 milliseconds so uh yeah so let's quickly run through uh yeah this test so as you can see everything uh passed we beat 92% can see everything uh passed we beat 92% can see everything uh passed we beat 92% with respect to runtime and yeah just uh 24 with respect to memory but uh if you look at the graph uh the differences are not so big so maybe some uh differences in implementation so there we have it uh a step by-step there we have it uh a step by-step there we have it uh a step by-step breakdown of splitting a link at list into parts so this approach is really uh straightforward and remember it's all about understanding the problem uh planning our solution and then translating this uh particular logic or plan into code and if you want to see how this problem can be tackled in other programming languages like uh C++ go programming languages like uh C++ go programming languages like uh C++ go rust and much more uh check the link uh below and yeah uh so uh before we wrap up uh so if you have uh any question or uh thoughts about problem solving uh please leave them in the comment section below and as always uh if you like it uh please give it a thumbs up and subscribe for more coding adventure and uh tutorial and most importantly keep practicing stay motivated and happy coding
Split Linked List in Parts
split-linked-list-in-parts
Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts. The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null. The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later. Return _an array of the_ `k` _parts_. **Example 1:** **Input:** head = \[1,2,3\], k = 5 **Output:** \[\[1\],\[2\],\[3\],\[\],\[\]\] **Explanation:** The first element output\[0\] has output\[0\].val = 1, output\[0\].next = null. The last element output\[4\] is null, but its string representation as a ListNode is \[\]. **Example 2:** **Input:** head = \[1,2,3,4,5,6,7,8,9,10\], k = 3 **Output:** \[\[1,2,3,4\],\[5,6,7\],\[8,9,10\]\] **Explanation:** The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts. **Constraints:** * The number of nodes in the list is in the range `[0, 1000]`. * `0 <= Node.val <= 1000` * `1 <= k <= 50`
If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one.
Linked List
Medium
61,328
1,930
hi friends uh welcome to followup let's have a look at problem 1930 unique lens 3 pic subsequences uh in this video we're going to share two formats of solutions the first one is based on dictionary so we are going to focus on the middle character well for the second one we're going to use index and the red index and we are focusing on the two ends uh with that said we are going to do the following plan first we're going to digest the problem uh requirements and then we do the analysis and share the code so now let's look at the problem digest so here very given a string s we want to return the number of unique palome palindromes of lens three that are a subsequence of s so here the word unique uh is very important right so uh a p Drome is a stent that reads the same forwards and backwards I guess this is very uh familiar to us so there are three examples uh in the first example the output is three so if you look at a so you see uh a first appears in at index zero and then at index four and in between there are three different characters a b c so we return three if you check B and C they both appear just once therefore there are no pal dromes uh of lens three and ending with b or c right uh in the second example all the characters are unique characters therefore the output is zero the similar you can examine uh example three so here B first appeared at index zero and then at index uh see 1 2 3 4 five right in between there are three unique characters a b c so the order are b c a right anyway uh this B in other words there are three uh unique P drums ending at B so if we look at a so we have a right there's one p Drome and the and a so in total we are going to get four right that's the return so with that St you can also quickly uh look at this constraints so now let's look at our analysis this so uh in the first uh solution we're going to focusing on the middle character so and then we check the two ends characters so here uh we want to use this one so s consists of only lowercase English letters so we know that there are 26 lowercase English letters right so this actually uh simplifies the problem in a sense so first I'm going to uh from string import uh ask key lower case so this import uh help us to avoid uh writing the a up to Z strs right and then our goal is to uh linear scan this string s so we're going to look at the left of the current index the right of the current index and then we check every uh lower s uh lower case letters so first I'm going to use this three dot as a set so this is going to the duplicate right this the result left is a dictionary uh this a site so corresponding to the number of unique characters to the left of the current index you can think like this the right because originally we haven't do the linear scan so the right we can Rec everything is on the left so let's use collections counter s so now let's do the linear scan so for I in range lens s then because we are currently looking at the uh character SI so we need uh we want we can regard uh we can begin to put things uh to the left so what we think is that left is going to add SI for next round right so now let's look at the current situation what we want to do is to write because currently we're looking at this current is decremented by one right so then we want to check if right s is zero right so we just need to delete this key right SI and then the main logic is that so we use the current character uh SI as the middle character and then we check the two uh two ends to see if there are some characters they provide the same uh they both appear in left and right so notice that there's a sort of asymmetry so left we are using a set and right we are using a counter so the reason is that we need to make sure after certain index so if there are occurrences of certain uh letters so now let's do the check so for character in s lower case so then we just do a check if character in left so this the one and if character add uh character in right so if this is the case so actually we know uh we have a uh P drum that is uh character SI and character but you know due to the fact that the left and the right are the same so we can uh map this or make correspondence or hash it like SI and the character right this the same so we use this to represent a uh lens three panum so basically it says the middle character is Si and the two ends has character so we append this we are append uh twoo this is H uh hashable right uh that's the basic logic right so afterwards so we just uh do this yeah if you look at the next round basically because we have finished the uh looking at the current index or use it as a middle character then SI will appear to the left right then that's the state of the left set right so now what we want to do is just to return the length of the three dot so here because we want to return unique pal DRS so this set play the roow of the duplication right so this actually forms V solution format we can do a test uh set has no attribute append so here let's see let's use add so now let's do it again yeah it passes the first example so now let's look at generic case yeah it passes the generic cases so now let's look at the second one so notice that uh in the first one in the sense we are focusing on the middle character right so we use SI as the middle character and then we check all the different SQ cases so this solution actually uh take advantage of the second constraint that is s consists of lower English letters only so now let's look at the second solution uh for the second solution we are going to look at the our focus on the two ends right so for uh this actually is similar to let's use example one to recap so here I check the index for a so a first appears at index zero and then uh a appears at the red most index that is uh four right 1 2 3 four and in between we have ABC so this contributes uh three different P Dres ending at a so actually in order to check um for example the in example one the P drums ending uh ending with two characters a so we just need to look at the first occurrence of this a and the last occurrence why because in between it contains all possibilities so this why we check the first and last actually this is uh due to the assumption that we want to find the uh number of unique PS so because this so we just need to for any character if we want to check the pading drums ending at those that character we just need to check the two indices the first occurrence and the last occurrence of that character so this then we check the middle so to uh retrieves different characters this will include all possibilities so if you have grasped this um simple idea and then the coding is very simple so here basically uh let's use the characters uh this is a different or unique characters in s so here if I like write like this we didn't take uh specifically use this lowercase letters uh assumption so actually even it appears there's other characters in as this still works so let me uh initialize a result variable this is the Contin variable right then we are going to check for character in characters so we want to use this character as the ends of PS right so then we want to check IG so this is uh s index character and then s r index so character so r index will be the red most index you can understand like this right so now uh the between uh we want to see uh now that we know this so you know it's possible that I and G are the same but if that's the case they do not contribute anything right so now let's do this so basically I want to write R do increment by length of set of um s i + 1 to G so in other words set of um s i + 1 to G so in other words set of um s i + 1 to G so in other words I want to count the unique characters uh in between I and G but both uh exclusive right so then we just need to return the result variable so this is the second solution format so I wrote I like this because this save some writing but you know it use uh it uses the string slicing which can be time consum me so now with that side let's do a test yeah it passes uh V special case so now let's look at generic case yeah it passes all the gener cases so I guess basically that's about it for this uh for this problem so here in the first one uh let's quickly look at the temp complexities right so we do this one this is essentially linear operation and then this is also uh linear but in between we have this one if you also count this for Loop but this for Loop uh itate each time 26 times because ask lower case is a constant bonded by a constant 26 this is the one uh this is the temp complexity for the first version for the second version this is also uh essentially linear operation and then here we have a for Loop uh this two are linear operation but here the temp consumed is like we do the slicing this can be temp consuming um with that said I guess that's about it for this specific video uh you're welcome to follow up our videos or channels so there are some other types of problem that can be practiced with that said I guess that's it
Unique Length-3 Palindromic Subsequences
maximum-number-of-consecutive-values-you-can-make
Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**. A **palindrome** is a string that reads the same forwards and backwards. A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. * For example, `"ace "` is a subsequence of `"abcde "`. **Example 1:** **Input:** s = "aabca " **Output:** 3 **Explanation:** The 3 palindromic subsequences of length 3 are: - "aba " (subsequence of "aabca ") - "aaa " (subsequence of "aabca ") - "aca " (subsequence of "aabca ") **Example 2:** **Input:** s = "adc " **Output:** 0 **Explanation:** There are no palindromic subsequences of length 3 in "adc ". **Example 3:** **Input:** s = "bbcbaba " **Output:** 4 **Explanation:** The 4 palindromic subsequences of length 3 are: - "bbb " (subsequence of "bbcbaba ") - "bcb " (subsequence of "bbcbaba ") - "bab " (subsequence of "bbcbaba ") - "aba " (subsequence of "bbcbaba ") **Constraints:** * `3 <= s.length <= 105` * `s` consists of only lowercase English letters.
If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.
Array,Greedy
Medium
330
1,762
hey folks welcome back to another video today we're looking at question 1762 but links with an ocean view the way we are uh solving this problem is by actually uh traversing the area that's given to us from right so if you look at this particular area we know that the ocean is to the right so to be able to view some the ocean everything to your right if there are buildings to your right should be at a height that's less than your height so basically if you keep moving from the right you should be able to solve the problem this um i don't think the difficulty level makes sense here it's stated as medium but i think it's a pretty simple problem so let's jump right in so let's first create a list of integers and let's call it list is equal to new um arraylist and the reason why we have that array list is because that's where you'll be storing the indices of all the buildings that do have an ocean view and currently because we don't know the size um of the like the number of buildings that we will be adding to the resulting interior that needs to be returned that's the reason why we just initialize the list and the next thing we do is just iterate through the array from the right so let's just get the height first let's get it as heights dot length and since we're iterating from the right so it would be and i will be equal to n minus one i greater than or equal to zero decrement i um and we also need a maximum that we've seen so far so let's initialize that to integer.min value for now integer.min value for now integer.min value for now um right and then if the height of the current building if it is greater than max that means everything that we have seen previously um is smaller than the current building so you just initialize the reassign the value of max to the current value that we have and you just add that to the list that you need to return so it'd be list dot add zero and i so the reason why you're adding it that zero is because you need to return the list in um ascending order so because you're moving from the right all of your indices will decrease and if you add it at the zeroth index you know you're maintaining that order um so once this for loop is done all you need to do is actually convert the list to another and return it back there are multiple ways of doing this but um i think the one liner would be use the stream and then map to end i hope that's how you do it i gets mapped to i dot to airway okay let's try compiling this and see if it's okay so the first case is okay everything else is okay as well awesome um so let's talk about the space and the time complexity of the entire solution the space complexity of the entire solution is off and since we are using a list to store the indices that need to be returned um sorry the space complexity the time complexity is of n since we are iterating through all of the values in the area awesome if you have any questions about this problem please let me know in the comments below um don't forget to subscribe to the channel and like the video i really appreciate that it definitely keeps me motivated to make more videos thanks so much and i'll see you all on the next video peace
Buildings With an Ocean View
furthest-building-you-can-reach
There are `n` buildings in a line. You are given an integer array `heights` of size `n` that represents the heights of the buildings in the line. The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a **smaller** height. Return a list of indices **(0-indexed)** of buildings that have an ocean view, sorted in increasing order. **Example 1:** **Input:** heights = \[4,2,3,1\] **Output:** \[0,2,3\] **Explanation:** Building 1 (0-indexed) does not have an ocean view because building 2 is taller. **Example 2:** **Input:** heights = \[4,3,2,1\] **Output:** \[0,1,2,3\] **Explanation:** All the buildings have an ocean view. **Example 3:** **Input:** heights = \[1,3,2,4\] **Output:** \[3\] **Explanation:** Only building 3 has an ocean view. **Constraints:** * `1 <= heights.length <= 105` * `1 <= heights[i] <= 109`
Assume the problem is to check whether you can reach the last building or not. You'll have to do a set of jumps, and choose for each one whether to do it using a ladder or bricks. It's always optimal to use ladders in the largest jumps. Iterate on the buildings, maintaining the largest r jumps and the sum of the remaining ones so far, and stop whenever this sum exceeds b.
Array,Greedy,Heap (Priority Queue)
Medium
null
65
Ki A Hello Everyone Welcome 2016 Saunf Electronics Questions Page Number in Question Veer A Hunger Strike at Present Slide Show Lemon Juice Stick Pan Now in Brief Introduction to Avoid Giving One Number here in this Video then subscribe to the Page if you liked The Video then subscribe to the greatest artist that a number is a silent number effective in the given for electric board for not visiting your 2.1 subscribe and subscribe visiting your 2.1 subscribe and subscribe visiting your 2.1 subscribe and subscribe the Channel subscribe and subscribe the subscribe Video subscribe to quote 10 and can be different for It's Capital and Original Followed by Assigning on Thursday Subscribe and Chord Subscribe 12 Posts In This Decimal Point After Seeing Pass Tiffin Is To-Do List Subscribe To That Daughters And Daughters-in-Law Witnesses That Daughters And Daughters-in-Law Witnesses That Daughters And Daughters-in-Law Witnesses In Decimal Point Not Violet Number United Way Raw Jise Country S Decimal Point In The Power Loom Sweet Talk About You Can Not Afford To Decimal In The Volume Show Will Return For Some Tips To Avoid Any Possibility 0.7 2.5 Vikram Thakur Possibility 0.7 2.5 Vikram Thakur Possibility 0.7 2.5 Vikram Thakur 's Updates Mill Number Investments Will Say 's Updates Mill Number Investments Will Say 's Updates Mill Number Investments Will Say Singh Wale Number One More Awadhesh Again After Experiencing Subscribe and Multiple Subscribe 0213 Slow Recent Times Will Start From subscribe Video Subscribe Something is Not That Number Subscribe The Police To Coordinate's Positive and Negative Numbers Chakradhar 10600 and Index Study Intense Pain Suicide Veeravikram And Video Subscribe Synonym Subscribe To That Commission This Part So Tube And These Cases Of Women Activists In Websphere 81.7 81.7 81.7 A Plus B Plus C Is Coming Button Intermediate Index Will Return Form Date Are Let's Talk Blast Case Srvi 029 Positive Negative And Definitely Original Subscribe To That Bigg Boss Inverter Hybrid SIM Hair Is Group ko not only exam pimples wrinkles and during this will return for you the voice of water in the interpretation Arvind Singh Saund Subscribe and right side par Rauniyar only for you the judge of what I will assist you number Shiv Bullions 5th number password in the decade Not be seen in the north end subscribe to that between there operation app trim arguments there is a subscribe button on the left side more than that extra that difficult this Sunday of the problem subscribe and subscribe the Channel and subscribe the Video then subscribe to that can Not have explained this part explains number ka notification in between morning return from its most cases discuss that if laid and problems of decimal point to be true under-19 subscribe and subscribe the Effigy in the last minute crafts with its power and ka marriage note See the number sonth gas wa kam something like subscribe button wala number twitter ki agar wife is note aap serial ke yeh for the classroom also every set the number subscribe and subscribe the 100 number 123rd subscribe now to the number subscribe and want a part To be next s's bearing c plus or minus science and two inactive wishes and plus one at midnight that with respect to the current in next fold earrings' stains this day will return fold earrings' stains this day will return fold earrings' stains this day will return forms from atharva will update number subscribe here example this scene plus one Two Three Lee A Plus Se Loud Updating Numbers Likessy All In Unwanted Deposit Cash This Butterfly Don't See And Digit That Dengue Don't Prominent Otherwise News Update Number Seervi Liquid Subscribe To Hai I Hope This Logic Therefore To You Apart From This One Important Picture Vidron its return journey to the number subscribe subscribing will be id point note servi subscribe button hai hain akshar fir border time complexity of this approach is order of a middle overlap degree and complexity Uttar Pradesh logical mode of but not doing Any Experience I Like Subscribe and Hua Hai
Valid Number
valid-number
A **valid number** can be split up into these components (in order): 1. A **decimal number** or an **integer**. 2. (Optional) An `'e'` or `'E'`, followed by an **integer**. A **decimal number** can be split up into these components (in order): 1. (Optional) A sign character (either `'+'` or `'-'`). 2. One of the following formats: 1. One or more digits, followed by a dot `'.'`. 2. One or more digits, followed by a dot `'.'`, followed by one or more digits. 3. A dot `'.'`, followed by one or more digits. An **integer** can be split up into these components (in order): 1. (Optional) A sign character (either `'+'` or `'-'`). 2. One or more digits. For example, all the following are valid numbers: `[ "2 ", "0089 ", "-0.1 ", "+3.14 ", "4. ", "-.9 ", "2e10 ", "-90E3 ", "3e+7 ", "+6e-1 ", "53.5e93 ", "-123.456e789 "]`, while the following are not valid numbers: `[ "abc ", "1a ", "1e ", "e3 ", "99e2.5 ", "--6 ", "-+3 ", "95a54e53 "]`. Given a string `s`, return `true` _if_ `s` _is a **valid number**_. **Example 1:** **Input:** s = "0 " **Output:** true **Example 2:** **Input:** s = "e " **Output:** false **Example 3:** **Input:** s = ". " **Output:** false **Constraints:** * `1 <= s.length <= 20` * `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`.
null
String
Hard
8
442
today we are looking at lead code number 442 it's a question called find all duplicates in an array and here we're given an integer array nums of length n where all the integers of nums are in the range of 1 to n and each integer appears once or twice we got to return all the array we got to return an array of all the integers that appear twice all right so here we have four three two seven eight two three one and we have two and three so you can see two appears once and twice right there and three appears once and twice right there and so we push in two and three and we return that here the only integer that's appearing twice is one so we're turning one and nothing appears twice in this example so we return an empty array and we are guaranteed that each element in nums appears once or twice and a follow-up here is could or twice and a follow-up here is could or twice and a follow-up here is could we do this without extra space and an ove and runtime okay so there are two ways to do this we can do this in linear space and then we can do this in constant space and we'll look at both ways of approaching this if we want to do the linear space way of approaching this it's not too bad we just want to do a hash okay you can use a javascript object or a hash table whichever whatever it's called in your particular language and all we're going to do here is we're going to scan through this array and count the frequency of all these numbers that's all we got to do all right so i'll just quickly kind of show you what that'll look like when we get to four we're gonna make four of the key and count the frequency of it's appearing once here we're getting the three so three is going to appear once two is going to appear once okay 7 is going to appear once 8 is going to appear once and now 2 because we hit 2 again we're going to increment this and 2 is going to appear twice here we hit 3 again we're going to increment the frequency of three that'll equal two and here we hit one and one will equal one okay and so once we have this hash then all we have to do is filter out the keys where the value is equal to two and then return the keys push those keys into an array push two and three into an array and uh that will be our result and we can do that and there's nothing wrong with doing it that way but we are using extra space we're gonna have to create worst case uh a hash that's going to be the size of the input okay so now how do we do this how do we solve this question in constant space it's not technically constant because we're gonna have a result array that could be the size of the input so technically it is o of n space but not creating any extra space besides the result so how could we do that in constant space there's a really important clue that's in this prompt and that is that the range is from one to n okay and this is really important because there's a lot of other leap code questions that kind of give you this clue and there's an efficient way of solving it when you're dealing with an array of values in that array that are within the range of the indices of the length of the array so to make it easier because the values here are one indexed so it's going from one to the length i went ahead and just marked the indices here from one to eight okay so let's just pretend the indices are mapped to one index so how can we do this in constant space and how can we use the property that the values inside of this array are within the range of the length of the array so what we're going to do here is here we're at i right and if we look at the value at i it's 4 what indicee does that point to what is the value at that indices it's going to be the 7 right and so what if we just go ahead and take that and then just negate that we just put a minus sign right there on that seven okay that means that there is a four in the array if that number at it at the fourth index is negative that means that somewhere in that array there's a four that pointed to this index right here okay so let's just move forward so now this i is going to go to this three it's going to point to the third index which the value is two and let's just go ahead and negate that as well i'm just gonna put a negative sign on there okay we're gonna move forward and we're gonna go to two now it is minus two we're gonna take the absolute value of that and that's going to point to the index 2 which is pointing to the value of 3 and we're just going to go ahead and put a minus sign right on there as well okay moving forward we're going to go to this 7 we're going to take the absolute value of that value which is 7 and that is going to point to this 3 and we're just going to go ahead and put a minus sign on this 3. okay we're going to go ahead and move forward to this 8 that's going to point to this value right there that one and we're going to put a minus sign on there that's going to indicate that it's been visited we're going to move forward and now you can see when we get to this 2 right it's going to point to this indices right here and we can see that it's negative and that means that we have been there before we have been at this address this 2 right here at some point we've been there before because it's negative and so because we know that what we can do is push this value of 2 let's go ahead and point it here push this value of 2 right here into a result okay so we have our result here and i'm going to go ahead and push that 2 in there because the address that it's pointing to is negative that means that somewhere else in the array there was a two meaning that it got here and it negated that okay moving forward i'm going to go to this three i'm going to take the absolute value of that which is going to be three and again here we go we're here at this 2. it's negative the value at the address of 3 is negative that means at some point earlier in the array we hit this address meaning that there is a duplicate okay so what i'm going to do is i'm going to go ahead and take that absolute value and i'm going to go ahead and push it into the result all right moving forward i'm going to go to this minus 1 that's going to point right over here it's positive that means it has not been visited and i'm going to go ahead and mark that as negative to say that it's visited and then i is going to go outside of the range and you can see here that we do get the correct result okay and now what about what do we have to think about our time and space complexity here well we only have to do one scan versus if we did the hashing method we'd have to do two or three scans it's still of n with the hashing method or this method but with the hashing method not only did we have to scan the array once to get all the frequency but then we had to scan the array again to filter out any of the keys that had a frequency of more than one here there's only one scan that we have to do and because we're using this kind of trick that this feature of this array that all the values here are in the range of the length of the array we were able to do this just in one scan and we don't have to create any extra space besides the result okay we can't avoid the result but besides that you know we don't have to create a hash table that's the size of the array so we can do this in constant space if we're not inclusive of our output okay so our time complexity here is o of n okay where n is the size of the uh the array and then our space complexity is constant okay if we're not inclusive of the result array which is pretty good and this is a very important thing to remember is there's these clues in these questions that come up a lot where uh there's so many other lead code questions where you'll see that the input is in a range of zero to n or you know one to n it's something that's in the range of the size of the array anytime you have that then you can use the values in the array as a way to keep track of things and it makes you know there's ways to solve it in a much more efficient way okay so let's go ahead and code this up we're going to go ahead and create our result and this is going to equal an empty array okay and now we're going to go ahead and iterate over our array so we'll say i equals zero i is less than nums.length i is less than nums.length i is less than nums.length i plus okay so now what do we have to do we want to get our index that we're going to look like the address that we're going to look in another part of the array okay so we can just say let idx equals math.abs idx equals math.abs idx equals math.abs of nums at i minus 1. so now why are we doing it this way we want the absolute value because we're looking at the address here and if it's negative meaning that we've visited before that's not going to work as an indices you can't you know you can't do it with negatives it has to be between 0 and the range of the array why are we doing this minus one because our input here is one indexed okay so it's mapping it's not mapping to the zeroth index it's mapping to the one index and so we just want to take whatever value is in nums of i and just minus it by one okay and now we want to just create a variable for the value which is going to be what is currently in nums at idx okay and now all we have to do is we have to check is that value less than zero is that value negative if that value is negative it means we have visited there before and that means we just want to push whatever is at the absolute value of nums at i okay if not then we want to go and make whatever is in there negative so if val is less than zero we're going to go ahead and have result dot push math dot abs of nums at i okay else what are we going to do we are going to uh negate whatever is in at nums at idx we're going to say nums at idx it's going to equal minus nums at idx okay and then we're just going to go ahead and return our result go ahead and run that make sure everything works and we're good okay and you can see we're getting excellent performance here let's go and run it again see if we can make this go higher um but yeah we're beating out almost 90 on speed and then we're beating out about 85 percent on space as well so it's an excellent way to solve these types of problems and it's a good thing to see if you can find these sort of clues in the question prompt like this right here i think is the big giveaway that the range is going to be from one to n as soon as we know that okay the range is the values inside of our array are going to be integers between one and the range of the array then we can go ahead it just opens up a lot of different ways that we can go about solving it okay so that is lead code number 442 find all duplicates in an array i hope you all enjoyed it and i will see everyone on the next one
Find All Duplicates in an Array
find-all-duplicates-in-an-array
Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_. You must write an algorithm that runs in `O(n)` time and uses only constant extra space. **Example 1:** **Input:** nums = \[4,3,2,7,8,2,3,1\] **Output:** \[2,3\] **Example 2:** **Input:** nums = \[1,1,2\] **Output:** \[1\] **Example 3:** **Input:** nums = \[1\] **Output:** \[\] **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `1 <= nums[i] <= n` * Each element in `nums` appears **once** or **twice**.
null
Array,Hash Table
Medium
448
688
uh in this problem firstly if you want to get the intuition please skip this part of 5-10 minutes I speak so part of 5-10 minutes I speak so part of 5-10 minutes I speak so basically whenever the problem comes up for property I was the one who was the most scared of out of all so that's how I will teach you that how to think of the questions when it comes to probability specifically right so it's gonna be a very good problem how to think from scratch going on what can help you in thinking itself it will actually help you cool now let's create a model example itself uh explanation itself uh which says that we are Simply Having a n cross and chess board okay I will have simply an L by that end I can get more the size of chessboard which is n cross n and a knight we have Knight which means in Hindi we said as Gora or you know uh at night we have and you know how the night moves right uh a two and a half moves it just goes two and then half two and then one so it is how our Knight moves in eight directions two and then one moves cool um so we know the status of the Knight which is row and columns and he attempts to make exactly K moves which means in one move he reached here in next move he can again try to go any of the eight directions and he will okay in one move he reached here right in next move he will reach other eight Direction so basically he can try to move exactly eight moves he will try to move exactly like move starting with this cell row comma column cool um and it's just or everything is a zero indexed which means the top left cell is actually a zero comma zero on the bottom right is actually yeah which means the top left cell is actually a zero comma zero and the bottom right cell will be a n minus one comma n minus one which is simply a zero based indexing which we have zero comma how a knight moves in a chest is represented in this blue diagram no worries at all but yeah for your more understanding how actually from some coordinate I comma J you can move to other coordinates if you are at some coordinates here comma zero if you want to move to a directions just simply add let's that's the reason I just showed from 0 comma zero to actually the new coordinate location so if you have any coordinate I comma J just simply adding this one comma 2 in I you add a 1 into NJ you add a 2 then you will reach this particular point which means to move to the eight directions simply add these which means in corresponding X add your I it is simply how you move in a grid in four directions in eight directions in simply how a knight moves itself so that is how I showed you that okay how a knight can actually move in from any coordinate I commodity from here to comma zero you saw it moves to one comma two if it had been I comma J so it would have moved to I plus 1 comma J plus two and that's how you can simply move to all eight coordinates all eight directions you can simply move on now coming up back to what we have to do that's how we saw the problem okay that is what it is given but at each time the Knight moves what happens it choose one out of eight possible moves uniformly at random that is one word uniformly at random which means that one out of eight moves are as equal which means every move every one which means every move out of those eight moves are actually equal so basically just says the they choose one out of eight possible moves uniformly at random every word has a meaning one out of eight moves no it's sorry but yeah one out of eight moves choosing uniformly at random which means every move has equal probability to get chosen cool now it just say okay even if the piece is out of the Grid or no word is what still so basically what we know from this part is that if a knight moves from one location to the next location and we know that every location has equal probability of being a chosen right every location has a productive being chosen we know let's say the probability of being chosen of every location is X it is X x and you know it is equal we know it is equal right and also we know that the sum of probability is always equal to one so basically it is says 8X is equals to 1 or X should be equal to one by eight so basically saying that going on to this particular point out of or simply you can easily say that you have eight points you can easily say that one out of eight possible locations I have that's simply I can say that one by eight is a probability of movement of a knight it's not that night it is night which means the actual piece right um to move from to move in one of the eight directions now you know okay see both ways you can find the probability it is just how we read it and it is how we mathematically Define it right now cool no worries that you have got how we can find the probability of movement of Knight at one point now the Knight continues moving until it has made exactly cable so basically make sure that Knight will keep on moving until it has made exactly K moves or it has moved off the chessboard if it has moved off the chessboard so for sure it moves will stop right at there right we have to return the probability that's the reason we just specifically stressed on probability itself and it is something we were while reading the question itself we were building out okay one out of eight possible uniformly at random okay that's a one by eight probability now we have written the probability that the Knight remains on the board so basically I am concerned of the night remaining on the board after it has stopped moving which means after completing exactly K moves if the Knight Still Remains on the board that is how I've got to know the probability of the Knight now coming back see now we have understood the problem itself because the problem understanding every part is very important and to grab every information now coming to the example now we will try to grab the information of the example itself from problem we got information about so ever we needed now we need more information to actually how to solve for that example will help us fixing the first example we will start from a row 0 comma 0 and then we have to do exactly K moves so remember this part now as we saw that every time the Knight moves its probability get reduced by eight because initially it is one initially the Knight is inside the grid it is one at moves to zero as soon as it just moves it just have another move it probability will get reduced to one by eight right so what will happen is initially starts from zero comma zero it is here now it has eight possible options outside is shown by the this dotted line right so that's to know okay there is also possibility going outside but it will for sure not go because outside it cannot go but yeah it is one such possibility so you will see that okay the six possibilities are actually outside and the remaining two are inside cool that is how we know okay the contribution of the outside one is actually a zero but the condition of inside one will actually be a will actually be something now it has done just one move it has just done one move so right now I cannot find my answer by just saying okay the answer is one by eight plus one by eight because it is a probability and we want to find the probability if it stays inside and for sure the two options to stay inside after one move are actually one might plus one by it which is a two by eight so I can just easily would have set up a one by four which is 0.25 but one by four which is 0.25 but one by four which is 0.25 but it is saying move to so basically I have to just keep on going until all moves are done so basically one move is done I have to again do another move now you will see that okay right now it is here again I will have to start right now it is here again he has to go and start for all the eight options you will again see that the other X option are outside the grid and the remaining two are inside the grid okay uh also you remember it is always doing a one by eight because as soon as every time it just tries for one move it's possible it is probiotic it reduced by eight so it was already one by eight so it will become one by sixty four one by 64. again for this one must switch one by 64. and for sure I want to find the probability simply there can be this or this right so that's the reason I just added things down and it became a 4x64 which is actually a 0.0625 became a 4x64 which is actually a 0.0625 became a 4x64 which is actually a 0.0625 and that is actually the answer now you know one thing you will start from a point you will keep because you have to go to next Point as you go to the next point you know if you go outside you have to return a zero so that it will not be counted return a zero if you are inside return oven you if you are inside return a one but also make sure that if you are inside at every step at every K you keep on reducing by eight because at every K I am keep on reducing by eight itself right cool that is how we have got so far information from the question number one and that's way too much information now coming back to question example number two um simply saying okay I start from the row comma row and column as zero comma zero uh I have done a no I have to do no moves at all and still it will remain inside so basically no steps taken it will for sure remain inside 100 probability of him staying inside that's the reason answer is one so for sure we know and that is also what we saw in here also that okay if it stays inside I will simply have a one as the contribution for that particular number but as the K as the moves are done as another move is that we as another move is being done I will for sure to do a television by eight here itself it I would have asked I would have said that okay the probability is right now one but as the moves were done it's probably to keep on dividing by it because it has eight options to go to and that we saw from here itself that how it has eight options to go to and the probability of every movement is one by eight because this uniformly at the random uniformly at random cool now coming back to actually what we inferred from the example one an example two was just the addition example one was more than sufficient to actually help you out now inference from every example that at every step okay I am we have eight options so basically we are reducing by eight cool now probability at every step for other new steps is basically how we find it by dividing by K same as other one and for sure if it goes outside then we have no options we have no contribution for that so if it is even if it is outside so simply return a zero for that if it is inside then I can return a one but make sure when you return a one you will have to accumulate a kind of modified depending upon K because if it is inside okay it is inside but still its value is one but as the another step one move is being done okay it is one by eight another move is being done it is one by Super 1 by 64. so contribution of being inside is 1 by 64 and then okay it is inside saying that I will just simply say okay it is one the contribution can have okay 1 by 64 again also for the ones outside but their contribution is actually a zero that is how simply we can infer that okay once for inside we'll count the contribution for outside will not count so simply by saying okay if outside returns 0 if inside return one and this thing will keep on going sideways keep on dividing on every K that will make sure when we write the code but yeah there is something which we need to infer from the question itself which means um the first condition it just says okay if it goes outside now how to know if it goes outside simply by saying your RNC coordinates if it actually as your as you know how to move in eight directions you know exactly how to move your interactions these directions you will know you will make simply a 2d array of these directions and simply will keep on adding your directions of I comma 1 or I comma 0 in your X and Y and by this you can simply keep removing the interactions by simply using a for Loop of moving if you have done the graph questions of how to move in the grid uh how to move in the interactionally uh Matrix how to move in the four directionally matrix it's same as we move in there itself if you don't know I highly recommend you should have watched the Bob Craft series that would be very helpful now coming back to okay we know that we will see the movement it will outstanding it we will simply return a zero inside the grid which means moves left remember if the moves left are actually zero then we will return a one because we remembered if the moves left were the moves left move here initially I started so ultimately you will remember okay it will keep on dividing but I have to stop when the moves that are actually zero so okay if the moves left has zero then return a one and this condition should be written after this condition why because if the move left are zero but still it feels outside bit so it should have been zero right so firstly make sure that it is inside grid which means if it is after this condition then only it will just make sure that I'm inside the grid and then moves Delta zero so simply return a one now for sure we know that okay it will just keep on repeating which means I started from here itself then it went to here then again for this it just went to here then it can have multiple options at every point it will again have options and so on so forth so simply it's a simple recursion problem the work is being done again and again why should I the contribution of x coordinate I'll simply keep on adding in my R and C to Simply get the new RN new see that's how I can simply get my new RN you see by this directions array right you don't have to manually go and do plus this press this simply make an array then simply keep on keep it trading on this array from 0 to 8 and then simply get actually your new coordinates and you are a new C now coming back to as I did one move for sure for my moves will actually get reduced by one but you also remember at every move I was keep on dividing by it so I simply divide it by 8 it is 8.0 if you don't know it I 8 it is 8.0 if you don't know it I 8 it is 8.0 if you don't know it I simply divided by eight now I have done one move I have simply divided by it but you also remembered I was adding in my probabilities I will initialize my probability with zero then I will keep on simply adding in this variable cordless probability so as to get the actual probability and you will know it is actually a recursion so it will go and again ask for the above problem so it will again go and ask hey bro what is for the next move it will again go and return that so if it returns a two by eight for this let's say for this step right here it again for this story um let's quickly remove it bro please just get done yep so as you saw damn this very slow cool as you saw here that uh it just again the contribution one by eight so one byte was already there it was just again doing a one by eight here and one by eight here because we know at every new place I go on I just did a one by eight so basically it will just go and ask the answer for this it will again go and say a two by eight because it was for one for this particular and one for this it will ultimately do what to buy it upon eight that's you know that at every move this eight will keep on it will be there so it will keep on dividing at every move it will keep on dividing that's how you know that okay at every move this will actually make sure that okay your eight is gonna increase again and again eight into eight and select that like that now you're simply added in the probability and that's how you can just get the some of the probabilities because it's nothing but okay either it can be this or this the final locations of the actual art night now that's a rough picture which we drew off from actually the example one which we got now coming back to the recursion which we have made for sure we can make the recursion but as we are making the recursion we know that okay it can be pretty big it can go pretty big so just looking backwards is there any repeating sub problem can we see for sure in the example itself we saw that if the knight at the stage at the move one it landed here and here now at the move two it will again try to go at other moves other places so he just was able to go here and go here let's say if I had asked you it also has a move three so it will again start from here and again try to go here and here you now know one thing right you also know one thing that when I started off with zero comma zero itself right and it again went back to zero comma zero itself now if I had again asked you and you know for sure it is again the same stuff which means at Step at step k equal to it is again at zero comma zero so I would have if I just ask you if I had steps let's say three so it would have again went on from this point and went here and then again from here and here so it is the repeating problem which these both will do for step two because they are the same location so if they are at the step when they both have to repeat the same process then why not memorize it I know it's the recursion I simply sorry it's a question but simply I can memorize it so what I will simply do is I know that I have NC to represent the above thing I showed in picture although you should have inferred from the picture itself that it has it is again going to the same place again but if not then you start from the 0 comma zero at k equal to you have eight options but I drew only the ones which are which people like which I can actually show you baba one so it just went on to this one and one comma two at k equal to one which means one move done now for the next move it again has key options again has eight options so at every time eight option eight options will open up for this is you will see here it is the repeating sub problem at k equal to 2. and that's you can have inflict many repetitive problems on infinite many pretty sub problems in this so for sure you would know that okay you have recursion you know it's a repetition problem simply apply a memoise thing how simply you know RNC will for short change and then at every step you know that your recursion involved K also the number of moves so for sure that also needs to come in picture so you have to memorize your R comma C comma K simply make a 3D array or simply make a string of this particular r c k which means R plus C plus K as a string and when you make a string please use a delimiter which means either a space or a hyphen or anything like that between three constants and then you can simply use that as a string and then memorize it by simply using a map or anything like that or you can also use them add itself a 3dr itself for memorization now you have got entire the logic I'll say highly event quickly pause it and just go and pour it out but if not and then simply let's see the code for sure we know that we have to also memorize it and we know that okay we can either use a 3D area or if we can also use a simple R string we can simply make a string out of this RS comma C comma K which is R plus some string which is hyphen or space or I put my name as a string or plus C which is RN plus C plus methyl plus K that is how a string key will be made and for that key I will simply have a value which is being memoized again and again so I'll simply have a memorization of a strain to double because I know that my probability is a double and for sure as you saw above that I have a directions array which I have made I know how I made you also know how we made it I showed you above and then it is the main function which is Knight probability I simply go and ask my question hey bro can you please find out what is the probability um starting with k moves and starting with r comma C it just goes and just do the same stuff as you saw above we have two base cases if it goes outside bounds of my entire Matrix which means R less than zero are more than equal to n a c less than zero or a c more than equal to n simply just return a zero and if it is inside and the moves have reached zero then simply return a one see if it is inside if it has reshare which means it is inside and the moves are zero will simply return a one cool my base skills are done now simply the comes the part which comes with the memorization part simply I will memorize it as I showed you I will just convert my R to a string add a delimiter a c to a string I had a delimiter and then I moved to a string and then my string key is made and I'll simply go and find if that key is already there if they are simply return that key if not then simply go on the recursion part in the recursion part I initialize my probability as zero simply go on to all the directions and simply go on fine okay moves minus one the new R coordinate the new C coordinate and also make sure to entirely divide by eight because at every move I know that I have a division by eight now I will simply add this down because for sure either it can be this or this right simply add this down and simply I will get the probability now simply memoize it which means simply put that in your map and simply return that particular part and by that you can simply do the actual recursion plus my position plus probability plus Mass everything is being called that's a very good question so simply the compression is n into n for R into C into k for number of moves and the eight for all the directions which you which we go on uh space Also n into K but it's actually a string which is being made uh so that is a one kind of space Factor also conceptual comment picture so that is how you can simply solve the problem the code is down below I hope that you guys got it see questions of probability it can be very hard depending upon how bad is your probability or how badly you hit probability right I was one of the persons who hate like I used to usually get confused on the things the probability and stuff but thinking from the example itself and seeing how they build the example is actually very helpful so I did not start from scratch and just say okay that is how you can simply think of as probability and made my own example I just use the example of the question itself and then build it out there can be chances that okay the example is not that perfect in the question but there's a high chances that in Gold forces course chef and liquor as well the example will actually be very good at to actually start you and give you all take care bye foreign
Knight Probability in Chessboard
knight-probability-in-chessboard
On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`. A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. The knight continues moving until it has made exactly `k` moves or has moved off the chessboard. Return _the probability that the knight remains on the board after it has stopped moving_. **Example 1:** **Input:** n = 3, k = 2, row = 0, column = 0 **Output:** 0.06250 **Explanation:** There are two moves (to (1,2), (2,1)) that will keep the knight on the board. From each of those positions, there are also two moves that will keep the knight on the board. The total probability the knight stays on the board is 0.0625. **Example 2:** **Input:** n = 1, k = 0, row = 0, column = 0 **Output:** 1.00000 **Constraints:** * `1 <= n <= 25` * `0 <= k <= 100` * `0 <= row, column <= n - 1`
null
Dynamic Programming
Medium
576
1,381
hello in this video i'm gonna solve lead codes problem 1381 which is design a stack with increment operation it's a custom implementation of stack in general in programming when we have a stack it's a pile that we fill so i have push and pop operations and push i just add to my stack so let's say i received push 2 i put 2 in my stack and then i received push five i put five on top of the stack and then push six i put six on top of the stack nine i'm just adding to a stop and then i receive a pop operation and in the pop operation i just remove the element that's at the top so i'll return eight and remove it from my stack i return nine and remove it from my stack return six and remove it from my stack and then if i receive a push i'm gonna add at this location on top let's say four and i'll keep doing push and pop operations but here we'll do things slightly in a different way first of all i need to determine the size the maximum size that i can my stack can handle and then i need to do the push and pop functions i need to implement them as i explained and finally i have a custom function here which is called inc which would increment the bottom k elements in the stack if i read the hints the first hint tells me to use an array to represent my stack the push will add new integers to this array pop would remove the last element in the array and increment will just increment the first k elements of this array so i they want me to use an array i can't just use the stack that comes in my programming language in fact i'm implementing a stack and they want me to use the array also it tells me that this solution should run in order of one for push and pop therefore i can't copy my array into a new one and add to it i'm not using a list i'm using an array and it's i it's telling me that i just can't copy into a new array and increase its size so therefore i need to find a way to iterate inside my array not to copy it also i can use order of k per increment that means i can iterate over all the k elements that i wanna increment so let's start with something easy since i know i'm using an array and it wants me to declare its max size let's add a couple of common variables between all the functions i'll add first of all a stack position variable that would remember my position inside this array and i'll declare my alex so i have int stack array i didn't initialize stack array here in fact i'll initialize it in the custom stack function after i receive max size so stack array equals mu and of max size so i have an array that's of max size if i look here i have max size of 17 therefore i have elements from 0 till 60. let's see how can i push into this array that's representing my stack and i received a push here i put the element that i receive in the index that i'm in i'm starting from zero i put it here 2 and move to the next index i'll wait at the next index so 8 and move to the next index 7 and move to the next index and let's say i received a few pop requests i would return what's below and decrement my position and then i'll do it again so i just returned nine and seven let's say just let's focus on the push and i received a push request and again let's say i'm pushing five i'll put five and move to the next one i'm not erasing from the array i'm just moving inside this array to keep my number of operations constant as requested and if i want to push 7 this time again i'll overwrite 9 with 7 and move to the next element and i'll keep moving inside my array till i reach 16. so i just filled 15 with 7 index 15 with 7 and at index 16 i received a push that is 2 and i move to index 17. and from here on i just can't add to my array in fact it says adds x to the top of the stack if the stack hasn't reached the max size so after i filled 16 i can't add to my array i have to check i have to start first of all with checking if i've reached my max size or not to do that i'll go to the push function and add an if statement i'll start with an if statement that checks if i reached the max position so stack position should be equal less than or equal to my arrays length that's equal to max size i can either use stack array.length use stack array.length use stack array.length or store max size in a shared variable so i'll just use stack array dot lens minus one since here i have a stack array that length of 17 in my example i'll check if i'm at 16 if i'm less than or equal to 16 i can also make this a bit simpler i can just use less than and stack array that length since i'm increasing in whole numbers in integers it will check if i'm less than 17 if i'm at 16 it's okay it will proceed otherwise it will not so in fact i don't need this semicolon inside these curly braces inside the if i'll just do what i did on excel that is i will add x at the position that i'm already in stack array at index stack position will receive the value of x and i'll move to the next position so stack position plus that's for the push for the pup we know how it works we want to just check the boundary conditions so i'm at index 17 and i received a pop request i'll decrease to index 16 and return 2 and i'll receive another pop request i'm at index 16 i'll decrease to index 15 and return the 7. i'll decrease to index 14 328 if i receive a push i'll do as before i'll overwrite this one and move to the other one so i'll keep popping till here i just returned the 8 and i received another pop request i'll decrease my position as i said and return the two this means that my stack is empty so if i'm at index 0 already my stack is empty i have to see what to do it tells me that if the stack is empty i have to return minus one so i need to check in fact that before returning anything if i'm already at index 0 or not so i'll start with an if statement to check my position to check if my position is not equal to 0 and in fact since i'm dealing with positive indices or and i'm just decreasing them i can use greater than zero so if i'm not at position zero i'll decrease my position and return the element at my new position return stack array at stack position otherwise if i'm already at index 0 that's else i'll return minus 1. now i can delete this else because inside an if statement i have the return i won't reach this else i'll just keep it for clarity even though our work isn't complete let's run the code just to make sure that it's working somehow and here i'm i've pushed to one and two and i'm popping it gave me two and at the end i'm popping again i pop till the stack is empty and it gave me minus one as expected these values are different because i need to increment them i didn't increment them so let's see how to implement the increment function it says that the ink function would increment the button k elements by the value val so i need to start from the bottom of the stack and usually we don't do this in normal stacks we're doing here we're doing it here in a custom stack and increase k elements it's also saying that if there are less than k elements in the stack i'll just increase all the elements in the stack so here i have 17 elements if i have k20 i'll just increase the 17 elements that's from index 0 till 16. so to do this i need a for loop and i'll use an i in this for loop i'll declare it inside the for loop to iterate over the k elements that i have and it's increasing and i'll check if i is less than the length of the array so if i is less than stack array.lens is less than stack array.lens is less than stack array.lens this will tell me if i'm still less than the total number of elements in the array so i don't keep increasing and receive an error so if this condition is satisfied i'll increase stack array at index i by val so that's stack array i plus val and i can rewrite it in a better way that's plus equal this is more concise this in fact would work this is efficient but it has one problem for every element i'm checking if i'm less than the length of the array and i can instead check if k is greater than stack array that length since i'm starting from index 0 i'll have no problem doing that so i'll check if k is greater than stack array that length and in that case i'll just replace k by stack that length this means that if i receive the k of 20 and my array is of length 17 k will become 17 and the for loop would iterate over 17 elements and now i can just remove this if statement let's run our code to see if we have any unnoticed typos it's accepted and let's submit it the code seems to be very efficient and it's working fine it passed all the test cases so as a summary we had a stack we designed the stack that would increase on its stop and return the element that's on its top using an array so that's a custom stack we implemented a method that uh indicates the maximum size of this array then we implemented the push function that would add on the top of the stack since we're using an array it would iterate inside the array it would add at the index that it's in and increase the index we use the pop function that would decrease the index that we're at and return what's in the new index and we implemented the increment function i hope you enjoyed this if you have any clarifications let me know in the comments
Design a Stack With Increment Operation
maximum-score-words-formed-by-letters
Design a stack that supports increment operations on its elements. Implement the `CustomStack` class: * `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack. * `void push(int x)` Adds `x` to the top of the stack if the stack has not reached the `maxSize`. * `int pop()` Pops and returns the top of the stack or `-1` if the stack is empty. * `void inc(int k, int val)` Increments the bottom `k` elements of the stack by `val`. If there are less than `k` elements in the stack, increment all the elements in the stack. **Example 1:** **Input** \[ "CustomStack ", "push ", "push ", "pop ", "push ", "push ", "push ", "increment ", "increment ", "pop ", "pop ", "pop ", "pop "\] \[\[3\],\[1\],\[2\],\[\],\[2\],\[3\],\[4\],\[5,100\],\[2,100\],\[\],\[\],\[\],\[\]\] **Output** \[null,null,null,2,null,null,null,null,null,103,202,201,-1\] **Explanation** CustomStack stk = new CustomStack(3); // Stack is Empty \[\] stk.push(1); // stack becomes \[1\] stk.push(2); // stack becomes \[1, 2\] stk.pop(); // return 2 --> Return top of the stack 2, stack becomes \[1\] stk.push(2); // stack becomes \[1, 2\] stk.push(3); // stack becomes \[1, 2, 3\] stk.push(4); // stack still \[1, 2, 3\], Do not add another elements as size is 4 stk.increment(5, 100); // stack becomes \[101, 102, 103\] stk.increment(2, 100); // stack becomes \[201, 202, 103\] stk.pop(); // return 103 --> Return top of the stack 103, stack becomes \[201, 202\] stk.pop(); // return 202 --> Return top of the stack 202, stack becomes \[201\] stk.pop(); // return 201 --> Return top of the stack 201, stack becomes \[\] stk.pop(); // return -1 --> Stack is empty return -1. **Constraints:** * `1 <= maxSize, x, k <= 1000` * `0 <= val <= 100` * At most `1000` calls will be made to each method of `increment`, `push` and `pop` each separately.
Note that words.length is small. This means you can iterate over every subset of words (2^N).
Array,String,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Hard
2272
1,721
okay so today we're looking at question 1721 swapping notes in a linked list i don't know if it's swap or what yeah but here given please excuse me if i pronounce it wrong uh you're given the head of a linked list and an integer k return the head of the linked list after swapping the values of the k note from the beginning and the k note from the end note that the list is one indexed so we're given like a few examples we can see that in this case k is two so um we want to swap this note and the k from the end so that's like note 4 so we return 1 4 3 2 5 and the second example we have this pretty long ish example k is five so we go one two three four five and k five from the back one two three four five that's eight so we swap seven and eight and in an example where there is only one note in the linked list we basically don't swap it and if it just so happens that the k node and the k from the end node are the same node is the same node um don't swap it as well so here are some constraints number of notes is n and denoted by n and k is less than n and ranges from 1 to both k and n ranges from 1 to 10 to the power 5 so we won't have to deal with the situation where it's like an empty linked list and the note values ranges from 0 to 100 yep i guess that's it for the problem description so let's just see um like start talking about how we can go about solving this let's shrink this a bit so uh let's just use example two for um illustration so we have seven nine oh i need two likes draw a shorter arrow right because we have quite a few notes six seven eight three zero nine five and we have k s5 so what we can do is um basically okay so we now already know which note is the k note right that's like pretty straightforward because we just go like i'm starting from here we just go like one two three four five i mean sorry it gets one index so this is one two three four five this is our um what do you call it the k note k pointer right but the problem is that we don't know what's the k from the nth node um right and it's like we don't know the length as well so we have to figure out like a way to find out which is the k note from the end so the approach to solving this is actually um making use of the fast slow pointer approach but in this case um it's a little bit different from our usual fast little pointer where we increment fast pointers by two slab and so pointed by one step right so uh what we can do is um we assign another pointer fast pointer to this at this position and then we okay maybe let's try a different color okay fast p to this and we start um a pointer uh slope okay so now at this position we basically traverse the uh fast p until like the last node so onto this position and at that point in time slow p will end up in position of the k note from the end so let's try and see if that works so from this point to this point we go one two three four five steps right so slow p goes one two three four five just nice we see it um like ending up in this position and at this point in time what we want to do is basically let's use red maybe green okay green sign um swap these two values and we can return our list yep so this will work for other examples as well so let's just try on example one case one up case two so we have k pointer pointing to this let's draw this a bit further away so we have key pointer to this and fast pointer when it reaches this position right um slow p okay because fast pointer started off here right slow p starts off here and um it's like right behind fast p so slow p will end up here okay so yep we can then swap this to and we're done okay so now let us try implementing it yeah so first off initialize our initialize stuff powerpoint is so we have k pointer first and we basically traverse oh oops for range k should it be k or okay so in our example two we can see that we want k to go from this first note one two three four so but k is five so we need to minus one to it okay in this range k pointer we keep walking it down at this point we can point our fast pointer to it so now we need to get our other pointer the slow pointer in place right so we'll do okay uh now that we have our fast pointers and slow pointers in the correct position we can start walking it walking the fast and slow pointers down to the last note the first pointer to the last note so while fast pointer dot next um what we want to do is walk them down okay now they're in the correct positions we just have to swap the cave pointer with the slow the values right so and return okay let's try and see if this works okay great so that's it for today's video and thank you for watching
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
10
Hello Guys Welcome To My YouTube Channel And Pleasure From Thank You Good Discuss About S Regular Expression Matching It's Hard Category Problem Combine Sub Scan Back Solution Dynamic Programming In This A Problem Statement Given String And Pattern Basically Ne Jab Bigg Boss Pattern President Not Three Do It Means subscribe button is that subscribe button is i office given s duos love it means iss attend vidro time president time can be considered a time or money waste time k please like this thank you a friends tourism in the time of life and water crisis at can Be replaced by anything can be liquid characters can be divided by visiting a b c d a b default tree like hole dots easter vs dot right to have seen the is match with dots subscribe to that etc drive from stride and being replaced By BSF Inspector can be replaced by K President can be considered by other actors even tried to others on basic idea behind the pattern matching and old new look mode in detail like by solving in the dynamic programming for data table subscribe particular that a prem etc serve Today End Date Fixed Fuel Tank String Isse Zameen Definitely Is Point Ko 12000 Fidoud Nothing Can See What Is The Hindi Meaning Of The Match 1.25 Test Is Point Ko 12000 Fidoud Nothing Can See What Is The Hindi Meaning Of The Match 1.25 Test Is Point Ko 12000 Fidoud Nothing Can See What Is The Hindi Meaning Of The Match 1.25 Test Match Special Cases Like Subscribe And Torch Light And Different Languages ​​And Torch Light And Different Languages ​​And Torch Light And Different Languages ​​And Spring Tribes In This Condition Vote Can Happen In This way can take Akram only 10 times This can take screenshot 200 Vacant 18000 This can be divided MP Spring 100 times solve This particular case which can be considered as one should This particular case using different for look for the time Disposal of cases Code Office Late Go through this dynamic fair election the condition arises like this for the character this is the spelling of subscribe the amazing means a the spring of come and notification pattern ujjain 1972 characters and not matching beneficial and will not given directly 2000 in such a condition replaced by - - - - - 2000 in such a condition replaced by - - - - - 2000 in such a condition replaced by - - - - - - The Video then subscribe to subscribe And subscribe The Amazing Please Like This Jhala Vinod Changes To Condition Is Pay Turnoff At Start And Deposit - To That Is Shravan Is Start And Deposit - To That Is Shravan Is Start And Deposit - To That Is Shravan Is Vansh Youth Effective 180 Conditional Straight Condition For Example Less Time Columbus Right Now Both Are Different Aspects Of Daughter And Can Be Represented By Id Two Minus One Subscribe Now To Different 202 People Like This Tiger Value Definitions Of Management And Replace The Defeat Of By Enjoy Dedh-Dedh Replace The Defeat Of By Enjoy Dedh-Dedh Replace The Defeat Of By Enjoy Dedh-Dedh With Diploma In This Wealth Fried Eggs Star Fennel Apps In A Poochega Ch-8 Check This Star Fennel Apps In A Poochega Ch-8 Check This Star Fennel Apps In A Poochega Ch-8 Check This Ped Anuj Star Bodyguard The Amazing 2090 Name Gurgaon Two Countries In The World Chess Pet 900 To 1000 Subscribe Admission In This Condition 1ST Year Remedy Double Pallu Pattern Upaj - 1ST Year Remedy 110 Pallu Pattern Upaj - 1ST Year Remedy 110 Pallu Pattern Upaj - 1ST Year Remedy 110 Pattern Urja - Valid Cities Equal Talent Pattern Urja - Valid Cities Equal Talent Pattern Urja - Valid Cities Equal Talent For Video Replace Just Once In 3D Cube Minus One Injured As We Fight Your Destination Was He Checking For This And Travels Going To Condition Deposit Interest Half Hour Or Currency Of In The Case Of Visiting Enemy But If It Is Not 110 Check Weather Report In How Many Times The Prince William Acid Attack In The Sense Of Itself Will Bf Check The Richest - - - - Itself Will Bf Check The Richest - - - - Itself Will Bf Check The Richest - - - - That Election To The Country Of Different Will Submit 502 nodes Subscribe to this tree point f-18 more subscribe Different 0008 subscribe The Amazing Subscribe My Channel Subs 2018 1 Day Ago Quartz Albert The King Is Back Blouse Pe Sangat Which You Can See A Different 09 2010 Different Na Dheer Wa The - 2010 Subscribe - 105 Video Subscribe - 105 Video Subscribe - 105 Video Subscribe Different Operating System Software Check The Subscribe April Fool PDF Like And Swedash Ji - April Fool PDF Like And Swedash Ji - April Fool PDF Like And Swedash Ji - 2017 Check Weather This And Values ​​Equal 2017 Check Weather This And Values ​​Equal 2017 Check Weather This And Values ​​Equal Tasty Accused 112 Pattern Of Organizing - In Tasty Accused 112 Pattern Of Organizing - In Tasty Accused 112 Pattern Of Organizing - In It Is Not Equal To 100 To 9000 Different 9.The Can We Subsidy Bhi Help Liye Se 9.The Can We Subsidy Bhi Help Liye Se 9.The Can We Subsidy Bhi Help Liye Se Bigg Boss Youth Vway No Difference Appointments Different 100 The Valley School Don't forget to subscribe Sona 1000 Replaced by Problem Dayanand Label 200 CR Equal Panchami Festival Give One is the Last Row and Column Value of Eggs Subscribe and Particulars Subscribe Torch Light I Hope You Get No Idea Of How You Are Feeling Is Particular Are Droid And Your Airplane Mode Turn On This Is It Straight Relationship More Latka This Is The Cost Of Coming To B.Sc B.Com And Young Girls Baby B.Sc B.Com And Young Girls Baby B.Sc B.Com And Young Girls Baby Was Not Taking Care Of Spring In that first and declared a leader to offer 0512 200 for baking 10 right in hair oil checking for watching this type of the world is the currency of ABC 10 subscribe The Channel And subscribe The Amazing 2013 4 5 6 And subscribe my channel subscribing Don't Forget Solution Means Till Call A Long Leaf Is With Long Minus To Subscribe Now To Receive New Updates Subscribe And Subscribe The Last Open Diner Dash Directly Subscribe 1500 And A Difficult Situation Is Particular Today Are Right This Is The Real Vitamin See the first time writing from it and placement and one to one plus one write stance from roy's decimal values ​​and columns write stance from roy's decimal values ​​and columns write stance from roy's decimal values ​​and columns and values ​​and migrating from and values ​​and migrating from and values ​​and migrating from particular you can say this point spot light solar check and giving - 151 - soft condition that was solar check and giving - 151 - soft condition that was solar check and giving - 151 - soft condition that was subscribe to the Page if you liked The Video then Setting condition work only pattern 112 star midfielder condition in that case SEBI First Diary Singh Ved Abdul Aziz - SEBI First Diary Singh Ved Abdul Aziz - SEBI First Diary Singh Ved Abdul Aziz - Youth Olympics Live Video Problem - The Youth Olympics Live Video Problem - The Youth Olympics Live Video Problem - The Video then subscribe to the Page if you liked The Video then subscribe to subscribe and subscribe 112 Tie - 110 Adheen The Will Be Replaced With 112 Tie - 110 Adheen The Will Be Replaced With 112 Tie - 110 Adheen The Will Be Replaced With - Rule Middle Class And Subscribe - - - - Rule Middle Class And Subscribe - - - - Rule Middle Class And Subscribe - - - - The Last Not The Play List Ko Deeds Are At A Peon In School And Password Vid Ooo that and I think it will pass all the best places in all its independence Amir Khan subscribe thank you can't not subscribe my channel thank you so much ooo
Regular Expression Matching
regular-expression-matching
Given an input string `s` and a pattern `p`, implement regular expression matching with support for `'.'` and `'*'` where: * `'.'` Matches any single character.​​​​ * `'*'` Matches zero or more of the preceding element. The matching should cover the **entire** input string (not partial). **Example 1:** **Input:** s = "aa ", p = "a " **Output:** false **Explanation:** "a " does not match the entire string "aa ". **Example 2:** **Input:** s = "aa ", p = "a\* " **Output:** true **Explanation:** '\*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa ". **Example 3:** **Input:** s = "ab ", p = ".\* " **Output:** true **Explanation:** ".\* " means "zero or more (\*) of any character (.) ". **Constraints:** * `1 <= s.length <= 20` * `1 <= p.length <= 20` * `s` contains only lowercase English letters. * `p` contains only lowercase English letters, `'.'`, and `'*'`. * It is guaranteed for each appearance of the character `'*'`, there will be a previous valid character to match.
null
String,Dynamic Programming,Recursion
Hard
44
797
Hello hello everyone welcome to twenty match apne bilkul channel hai follow great time subscribe after node from 0 to avoid all subscribe - 1800 214 0232 subscribe 13023 must subscribe to-do list taraf pimples and if e must subscribe to-do list taraf pimples and if e must subscribe to-do list taraf pimples and if e explain with example together with video Ooo Loot Mein Latke Started Veg Uttapam All Pass Room Soft Target Liquid Se Kyadhi subscribe this Video plz subscribe Channel subscribe to subscribe our let's go ahead and creative veg sandwich subscribe to this select famous and you should not forget you listen this element and What is lucidly sporting club school subscribe to that undo cement so will create a copy of this particular path that distracted solid classes subscribe loot-loot do you loot-loot do you loot-loot do you live one subscribe to the president of india through the same thing that flex Pulao date of birth element 051 celebs ko subscribe and subscirbe 0 subscribe to ki aunty list direct apne body they do subscribe this Video subscribe and subscribe karo to take e want listen this ambitious plan to celebrate this element shoulder wishes subscribe lutaaye1 under Have a view to every one should celebrate subscribe 2021 I hope you understand this logic and notification subscribe to the Page that is nothing new idea certification the best lines and to your to-do list of your to-do list of your to-do list of sentences examples to set answers down there Lives in To-Do List 251 Adhir Vo Video Subscribe New Subscribe Nau Hai Aur Laptop in Teachers Kyun 10 List Andhe Tube Do Subscribe What is the Elemental Subscribe Video Subscribe To That I Will Get Between Connection Wicket Office Do Subscribe Video Subscribe Ko WHATSAPP THIRD ODI 2018 LIVE VIDEO SUBSCRIBE TO के व्रिक्ष मैड़ीवी मैड़ीटी इडियाटी सुस्करी टो
All Paths From Source to Target
rabbits-in-forest
Given a directed acyclic graph (**DAG**) of `n` nodes labeled from `0` to `n - 1`, find all possible paths from node `0` to node `n - 1` and return them in **any order**. The graph is given as follows: `graph[i]` is a list of all nodes you can visit from node `i` (i.e., there is a directed edge from node `i` to node `graph[i][j]`). **Example 1:** **Input:** graph = \[\[1,2\],\[3\],\[3\],\[\]\] **Output:** \[\[0,1,3\],\[0,2,3\]\] **Explanation:** There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3. **Example 2:** **Input:** graph = \[\[4,3,1\],\[3,2,4\],\[3\],\[4\],\[\]\] **Output:** \[\[0,4\],\[0,3,4\],\[0,1,3,4\],\[0,1,2,3,4\],\[0,1,4\]\] **Constraints:** * `n == graph.length` * `2 <= n <= 15` * `0 <= graph[i][j] < n` * `graph[i][j] != i` (i.e., there will be no self-loops). * All the elements of `graph[i]` are **unique**. * The input graph is **guaranteed** to be a **DAG**.
null
Array,Hash Table,Math,Greedy
Medium
null
342
hey this is Topher with a lonely Dash and today we're going over lead code question 342 power of four which states given an integer n return true if it is a power of four otherwise return false an integer N is a power of four if there exists an integer X such that n = 4 to exists an integer X such that n = 4 to exists an integer X such that n = 4 to the x X power and these are the important ones integer X and integer 4 in order to solve this problem so they gave us three examples uh for example we if they give us n equals 16 we know 16 is a power of four because 4 to the 2 power is in fact and I'm going to double check this just for my own brain uh okay four to the 2 power is in fact 16 five cannot be because there is no power of four that will get us to five and there is no power oh there is a power of four that will get us to one four to the zeroeth power will give us one right and the trick is that power zero is an integer two is an integer there's no integer so that power has to be an integer that will get us five so that's what we're really working with here is trying to figure out what that x value is X such that 4 to the x equals n so how are we going to do that and for me it comes down to mathematics so let's use a very simple example okay so four uh let's say 4 the 3 power uh is equal to 64 right and this I want you to rethink this as thinking 4 to the x is equal to n right because they're going to be giving us n and in this case is 16 and in this case is 64 so 4 to the 3 is equal to 64 and we're going to think logarithmically right logarithmically so we can rewrite write this right here this can all be Rewritten as the log of Base what is it log of Base 4 of 64 is equal to three and we're going to be thinking over here okay well that's really log uh base 4 of n is equal to X cuz we're really looking for that X okay uh and that can even be Rewritten a little bit more down to log base 10 because we're going to be programming and I like to have everything in log base 10 so in our case log base 64 over log sorry log base 10 64 divided by log base 10 4 is equal to 3 and again this is just going to be log coming over here log of 64 is our n divid log of 4 is equal to X okay and really this is as far as we need to go because we're going to be taking this equation CU we don't really need to know what x is we don't care what x is the only thing we care about is whether X is an integer or not because we're returning true or false based on the fact that it exists as an integer right so in our case when we're kind of writing out what we need to do we're going to say hey okay is log of n divided by our log of 4 is this an integer and the way we're going to do that at least for our purposes today is we're going to take this and we're going to modul it by one and we're going to say hey if this ends up equaling zero then we know that our X will be an integer now there are other languages you say hey is if log of n ID 4 is an integer if it is an integer then return true otherwise return false but for me this basic mathematics of using um using a modulo of one is the perfect solution because it'll work in every language no matter what you're typing in and so this is really all of the math that we're going to be using to solve this we're going to say hey uh is our log of n over the log of four uh an integer and you're golden but there's one other thing that we need to consider and I'm going to say that um in our edge cases so let's move on and see if there are any edge cases okay so for our edge cases and it's not really an edge case I just want to make everybody aware when we're thinking mathematically that the N can never actually be negative right because four to any power is never going to give us a negative n right so we can at the very beginning since we know n looking at our constraints could possibly be anywhere from -2 to 31st up to 0 that we anywhere from -2 to 31st up to 0 that we anywhere from -2 to 31st up to 0 that we should take care of that first if we can just say hey is n less than zero great we're going to return false um while not an edge case it's just something to consider right off the bat so let's keep that in mind and move on to some pseudo code okay so keeping uh in mind what we just talked about for our edge cases and though it's not really an edge case we can deal with it first so if n is less than or equal to zero right then we know that it's going to have to be return false um because there's not really uh an x value uh an exponent value that will give us the integer that we need to find n otherwise this is really simple very short uh we're going to return uh WEA I have no idea if that's the right weather I'm really bad at choosing weathers whether the log of n right divided by the log of four is an integer and that's it that's all of the pseudo code work we really need for this question so let's copy let's paste it and let's get going okay here we are working Python 3 area of the lead code website first thing we need to determine is if n so if n is less than or equal to Zer what do we just return false okay that takes care of the first line and then we're just going to return whether the log of n divided by the log of four all in base 10 is an integer so we're just going to say hey return uh we're going to use math. logbase 10 math log 10 of n right divided by math. log 10 of4 is an integer then we're just going to say hey we're going to modul that by one and if it equals zero then it's an integer and that's it uh that should be the code that we need to make this determination just looking at everything math uh we'll hit run hopefully I did everything right come on now oh I can't see it I'll just hit submit and have my fingers crossed for everything so yes it is accepted and memory wise that works really well I'm going to scoot out just a little bit um we're hitting up there at 96% of good memory it's not the at 96% of good memory it's not the at 96% of good memory it's not the fastest apparently uh when using python but that's really hard to kind of Judge uh I'll just hit submit again and see if we can get a little bit better on our runtime no we get worse fair enough but for me when we're dealing with powers of things Oh see now here I hit it again and now we're in the 96 percentile for runtime and low on memory um but for me if I'm going to be solving any questions powers of four with the exception of the question power of two um if you haven't seen that video of ours go back and look at that the power of two I use binary search algorithm because it actually is faster but in this case absolutely I would use pure logarithmic mathematics to solve this problem not only because it's pretty quick but also because it looks so simple on the page so hope that helps um happy coding
Power of Four
power-of-four
Given an integer `n`, return _`true` if it is a power of four. Otherwise, return `false`_. An integer `n` is a power of four, if there exists an integer `x` such that `n == 4x`. **Example 1:** **Input:** n = 16 **Output:** true **Example 2:** **Input:** n = 5 **Output:** false **Example 3:** **Input:** n = 1 **Output:** true **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Bit Manipulation,Recursion
Easy
231,326
212
hello everybody and welcome back in this video solution let's dive into the problem word surge2 i'm going to explain the solution in detail because it is a complicated one there are multiple different components that we need to figure out before we can write the solution let's get started the first thing you want to note is the word search 2 is just an extension of the previous problem word search one and so we'll want to quickly go over it because there's one or a couple of things that we'll borrow from word search one and that is going to make our answer a lot easier to understand okay so what is the problem description we're given a board and this is just a 2d matrix of characters and you're given one word that you have to search inside of this grid in this case let's say the word is abc ced so inside of this grid instead of this board you have to somehow search for the word abc ced at the end you can return true or false saying that okay i have found the word into or i haven't found this word now we'll also want to discuss the solution so okay what are we trying to do let's say that i give you a pen and paper and on that paper is a giant board drawn okay and i'll give you this pen and say that do whatever you want now what would you do how would you think about it in terms of brute force approach well the first thing you want to do is you will want to start and you will want to find the starting point which is the word of zero because you know for a fact that this entire string is going to start from the character a you'll start looking for the character a inside of this giant board and once you've found that character a what will you do next from that point you can run a dfs and search in all the four directions looking for the next character so we started off with the character a and let's say that we were at this category okay now the next character is b so since i have found the character a i want to start looking for the character b which is in the surrounding of which is in the neighborhood of this particular a so in this case i find two neighbors s and d and both of them do not match to the character b and so i'll say that in that case okay you know what it's no use to continue exploring in this case i'll just hit it on so we'll go on and we'll find another a okay great so we found another a let's try to run a dfs from this point and so we found this a let's try to look for the word b let's try to look for the character b inside of its neighborhood so in this case we do indeed find that we have a character b and so we can move on to the character b from this point we want to look for the next character c so we'll try to look for the character c in its neighborhood and we do indeed find c and so on and so forth we can do and we can do the search for every single one of these characters now we also want to talk about the complexity analysis for this question because understanding that will lead us to couple of observations that we can later exploit okay first things first complexity analysis the complexity analysis in terms of time is going to be order of m which is number of rows times n the number of columns times 3 to the power of l now there's a common misconception or a common mistake that people make and write it as 4 to the power of l that is incorrect and that's because even though it is easier to explain and understand that we're looking in all the four directions it's it is incorrect logically because we are not looking in all the four directions because it does not make sense to look at this way let's say that we are at this character b we have already considered the character a and now we are at the character b from this point i want to start looking for the character c which all directions will i check i'll check to the top i'll check to the bottom and i'll check to the right i will not check in the direction to the left because i have already explored that i've already considered a and i don't need to consider it again so in fact there are not four directions that we're checking at each point there are just three directions we're checking at each point and we're doing this for every single character inside of this world of length l and this is where you see the time complexity as this the space complexity is going to be m times n and this is just the height of the recursion call stack because in the worst possible case you may have to explore the entire grid so each of those values will keep stacking in the recursion call stack okay i think we're pretty much clear on what word search one means so now we can start to build upon word search two the first thing we note is that you're given the same board let's say we're given the same board and instead of one word we're given multiple words that we have to search inside of this grid so let's say the word was a b c e d and now we have to search a couple of more words like acc and so on and so forth for each of those words now we want to return this to our false signal and at the end we want to return this giant list of all of the words that we were able to find inside of this grid okay what is the time complexity going to be expanding upon the previous solution expanding upon the previous brute force solution this brute force solution will give us a time complexity of w times what we saw before all i'm trying to do is i'm just going to pick this word and i'm going to do word search one again then i'm going to pick the next word i'll do word search one again so on and so forth for each of those words inside of the word list and that is why we have w over here which is the length of the words now this clearly does not look too good in fact if you write and type out this brute force solution as i have mentioned in the my blog down below it will give you a time limit error and in especially in python it will most definitely give you a time limit error so we want to optimize that we want to start to figure out something that can get us a better complexity space is still fine we are not messing with space time is the issue so observations as i always suggest it's a good idea to look at a couple of small basic cases and build on top of that but this question is complicated and the question we want to ask first is what are we looking for i don't know what i'm trying to optimize so let's instead zone in and zoom in onto this w thing because earlier we had this m into n into 3 to the power l which seemed to work fine but now we certainly have this w added can we optimize this w and so w is just a list of these words so we'll try and see what we can find inside of this list of words and now let's look at first case we had abc ced and we had acc so nothing really special over here let's keep on iterating let's keep on finding new cases let's say that we have a b c e d and a b c what do we observe over here in this case the string abc is repeated again and again in both of these cases abc ends with this and like abc is the entire string over here and abc is a substring in this case so maybe we're looking at substrings or maybe we're looking at a dynamic programming approach it's very hard to say at this point and maybe dp will be very complicated to implement so we'll keep that aside for now let's keep on finding more cases and let's look at this case over here let's say that we have the case triple a b triple a c triple a x d what do you observe in this case all of them start with the same triple a right and after triple a we have a b in this case c in this case and x in this case it looks like maybe dynamic program is something we have to do or maybe not let's actually look at a visualization of this and maybe we'll understand it better in this case i have sort of designed this structure over here and these are the strings that we want to search and let's say the grid itself has this kind of structure the grid is sort of optimized in this way and so we have triple a and we do find that triple a b exists triple a c exists and triple a x d exists would you also observe as i said before it looks like there is a repetition of these triple a characters and so it would be good idea to have this information okay you know what these prefixes are being repeated prefixes as the idea that we've just previously seen yesterday in the question implementer prefix tree can we exploit that over here yes we can if you observe if we can somehow compress the information of all of these triple a's into aaa b triple a c triple a x d then we can more easily find what is the remaining part of those characters remaining part of those words and so we are looking at a solution which involves prefix trees now if you don't know what they are you can refer back to my previous video but i'll also quickly go over a couple of slides that will help you understand how we're building this tried data structure let's say that we have the word ax that we want to add this is a completely different example just to demonstrate the use of prefix trees let's say that we have the word ax that we want to insert inside of this data structure so we'll create a as a node on itself we'll split it out character by character and we'll have a as the first node then we'll have x coming as a child of this a and so we'll make x as a child of a and mark x to be the end of the string end of the word at this point we can start to add more words so we'll have app and you'll quickly realize that even though we have this app as another completely different word both of these abb and ax share the same prefix a and in this way we have compressed the information just a little bit but we can compress it even more let's take the case of apple now let's say that we want to insert this word apple inside of this data structure and so you'll realize that we don't need to have this another pathway going storing the word apple we can just use what was previously there also note that i haven't messed around with this ending marker this will still remain as is app does indeed mark the end of a word what we have over here and apble is marking the end of another word over here similarly we can add one more swirl say api and you'll realize that there's a lot of compression happening there's a lot of efficiency in this data structure when it comes to these kind of problems and in fact i think it's a general node because you're looking at words and you're trying to search for words itself should remind you or at least get you thinking about prefix trees let's add quickly one more string bb and uh yeah again this is the hash thing is something i've explained previously why we need to have that but now we have this entire data structure in our hand which is able to store this compressed dense representation of all of the words and so i think we can first start coding up this node entry prefix tree okay let's first implement the nodes and the trees because that's the most simpler thing so we'll have a class called node and this is a class storing all of the nodes so what does a node have well a node needs to have this character in hand as well as the ending word which i'm going to say to false and what it means is look at this case over here a node has three pieces of information first what is its own character which is in this case a second who all are its children which is represented by the green lines in this case it's x and p and third if it is an ending character or not if this particular character marks the end of a word or not right and in this case you see that x here marks the end of a word which is ax let's implement all of these three we'll say that self dot sequence to c will have another uh child we'll call it a dictionary and we'll store all of the children in here which are represented by the green lines and we have the self dot end equals to n we'll say that you know end equals to fall by default because most of the characters are not ending characters only some are and will specify that differently okay now i'm going to write the class try okay we'll go ahead and initialize that we don't need any extra parameters that's fine and we want to specify the root to be a node having this character hash this is the character hash and this is the root of the try okay we also want to have this ability of adding words so add word self and the word how do we add a word to this data structure well we want to first split it out character by character we'll do that and we'll do some computation we also want to be able to go over all of these characters one by one so we can't mess with the root so let's just create a copy saying current equals to self dot root and this current is uh what is this current going to do this current is going to uh let's say that initially current was here then the current will move on to this character a and then it will move on to this character x so i want to have current equals to the current of child so current.child over here and the so current.child over here and the so current.child over here and the character c now it's not always necessary that we have this dictionary character setup so we'll want to do that so if c not in current.child uh let's create a node for this so we'll have a current dot child of c equals to one node sorry equals to a node with the character c i think this should work and then we'll have at the very end we also need to be able to mark these ending characters saying that this end marker signifies the end of ax word so we'll say current dot end equal to true once we are done with the iteration of all of the characters we'll just set current rotating equals to true okay we're finally done with the code of the street data structure so now we can move on to the second part of the solution and we'll actually talk about how to extend word search 1 to word search 2. it's going to be very simple changing perspective so let's get started okay let's get started with the second part of the solution this is a bit more complicated but if you understand word search one properly there are going to be a lot of parallels that you can drive into word search too okay let's start from the very basics which is the search function previously had x y and i x represented the x coordinate y was the y coordinate and both of these specified where we are inside of this board what character we are currently looking at the i was the very special index which told you where you were inside of the world x and y told you where you were inside of the board i told you where you are inside the word because remember in word search one we're looking for a particular word and the function search returned a true or false at the end saying that yes we found a word or no we did not find the word and the generation case of like exploring in all the four directions by the way was looking up down left and right as simple as that now if you understand this well the word search 2 solution is going to look extremely similar the function search is still going to have this x y and current now this current is very similar to the i x and y simplify uh sorry x and y simply mention where you are inside of the board as before the current mentions where you are inside of the tri data structure previously we were only considering one word the word search one was only looking at one word but since this is word search two we are looking at multiple words we learned how to store that in a compact representation a data structure called a try a prefix tree and current specifies where you are inside of that data structure so very similar in ideas there is going to be one small implementation level detail that we have to add later on but that's very easy to understand then we have returning here we're going to return true or false saying that we could find this word or not in this case we have to return none because things are a bit more complicated it's true and false for every single word so that's not exactly easy instead of returning anything we can just store all of the words that match all of the words that we were able to successfully find we can store all of them and we'll return that at the end the generation case is going to be exactly the same we are again looking at up down left right with 3 to the power l complexity whatever and with that being said we can jump onto this coding of the search function with x y and correct values the first thing i like to do is get started with checking whether these x and y's are present inside of the bounds so we'll say x should be between 0 and m where m is the number of rows and y should be present between 0 and n the number of columns now if that happens to be true if both of these x and y's are inside of the grid then that's good that's what we want but if that is not the case but if any of them step out of the grid we can return right away and what do we return none we return nothing in this case as we saw before okay once that is handled we can move on to why is first extracting out the board of x y so we'll get the character we're looking at so this is the character c now here is when things gets uh things start to get a bit more interesting let's look at this visualization over here let's say that this hash is the current we are sitting at the root right now this current only has two valid children a and b and so the question we want to ask is whatever the current board of x y we're looking at whatever the current c is that inside of this valid children range or not so we'll write it out saying that if c in a current dot child or not recall how current or child is a dictionary over here which we fill in with the appropriate values so if the c is inside of the current or child which means that the character we are looking at is inside of the data structure that character is inside of this giant tree data structure and that means that is good that is what we are looking for but if that is not the case if this character is something else something entirely else then we don't have to even consider it we can again return nothing we can say you know what if you're not inside of the violet children if you're not a possible valid child then i don't care about you can just go away okay what do we do now as we saw before this is the part of backtracking and so we'll set the board of x y equals to be blank and we'll say that we'll mark this board as visited okay at the end we also want to do board of x y equals to c so we are sort of we have this character c saved beforehand and so we'll reset it to c and in between we can have these multiple search functions so this will go to x y and current but is it going to be current it's going to be current dot child of c see as soon as we go past this line 25 we have ensured that a child sorry the current dot child of c exists right because that is present in the dictionary otherwise we would have returned to nothing so assuming that current.child.c exists so assuming that current.child.c exists so assuming that current.child.c exists we can now set and we can move the current pointer to move forward so let's say that the current character the board of x y was a and the next step what will happen is this current will move from this root node over here to this a over here and similarly the valid children will also move forward and so on and so forth it will keep on going so we can do this kind of computation over here now this is something we'll go ahead and copy paste we'll do x plus one x minus one basically we want to explore in all the four directions you can also write a for loop for this be a bit smart about this but this also works as well so what does x minus one mean we're looking at the upward position right we have a cell and we want to look up format x plus one means that we're looking down y plus one that means that we're looking at the right hand side and y minus one looking at left hand side cool so if you realize this sort of entire search thing is sandwiched between this board of blank and board of c and this is what makes the backtracking work if you're confused about this section by the way the sandwiching thing feel free to refer to the link down below or the info card that should appear over here okay uh are we done there's one more thing left to do what is the base case like when are we ending this see we are always returning nothing but we also want to store these matches right we want to store all of the cases where we have successfully found a word now how do we find a word uh just after this line we can say that you know what we since we found this current of child of c is this also an ending word is this current character marking the end of a particular word and if that is true then we can ah do answer dot append uh word okay but word what word there is no word inside of the search function anywhere okay this is a bit tricky what do we do about this word how do we get this word and so what we can do is uh this is just one little change that we're going to make we're also going to store whatever the path we took up till now and so with this path we can take the path previously there and we can add c to it and this will be added in the answer we'll also do this over here center the paths over all of these guys and do path plus c cool i think this looks good do we have any more things to do over here i don't think so cool now we can finally do a quick setup of the basic variables we need we have length of broad board and of board of zero the number of rows and the number of columns we want to iterate over all of them and for each of them i want to start the search so i'll go in search of x y also i want this current guy which will store very soon and the path initially can be just an empty string i also want this answer over here that stores all of the answers and we can return this answer at the end um also we need to initialize the tree so let's do that so 3 equals true ah try is initialized and then all right we also want to add all the word for word in words try dot what is that add word function add word the current word cool so this is the entire data structure by the way that we're forming uh i'll show you this is the beauty of writing good code we have sort of in those two lines uh first initialize the try and then added all the words so in those two lines we have constructed this entire thing so pretty cool right two lines and we're done um what else do we need are we done okay we also want this current thing so let's specify the current to be tri dot root because this current will start from the root of the tree as we saw over here okay so before we submit this let's do one little mental check we've put this answer as a list but is it actually a list well yes indeed we do want to return this answer list at the end but should we store it these answers as list or not the thing is there can be cases of duplication let's say that the entire grid is full of a's okay there's a four by four grid full of a's and the string that you want to search is a and that's the only string your code will return all of the single possible combinations of these aas what we want is just one single combination so to prevent those duplication cases let's create this answer not as a list but as a set and we'll do answer dot append instead of this we'll do answer dot add and in this way uh okay so we'll just do a list of this over here and this will handle the cases of duplicates as well so finally we can try submitting this and just hope it works because this is a long video cool this works out okay good so this is it for the problem word search 2 and i'll see you in the next video
Word Search II
word-search-ii
Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_. Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. **Example 1:** **Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\] **Output:** \[ "eat ", "oath "\] **Example 2:** **Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\] **Output:** \[\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 12` * `board[i][j]` is a lowercase English letter. * `1 <= words.length <= 3 * 104` * `1 <= words[i].length <= 10` * `words[i]` consists of lowercase English letters. * All the strings of `words` are unique.
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
Array,String,Backtracking,Trie,Matrix
Hard
79,1022,1433
1,859
Jhaal Hello Bhai - Friends Welcome to my Jhaal Hello Bhai - Friends Welcome to my Jhaal Hello Bhai - Friends Welcome to my YouTube channel Radhe-Radhe YouTube channel Radhe-Radhe YouTube channel Radhe-Radhe Loot Subscribe To Ki Bhaad If you will be able to convert the setting then for example you will see the input here. After subscribing to this sentence for pun, we have to write this subscribe Take and subscribe village subscribe is spirits and if you see that and we return to this return add 200 will come to us in a body so that all this dear has come to us hey what will we do now with this nectar but Now we will create a template here inside this and we will put the reports in here hero is lieutenant you park porn site this is requested video ireland start length oil plus seat and then what we will do is appoint subscribe this festival this If you see all of us, then instead of this, let us do something, if you are able to see then subscribe, there are more numbers in the village appointed, then there are the accused, you understand, then what will we do now, if we will joint it, then we will have Six Mishri Hey, we are two, all these people have come to the number, we want the number, now we will cut it, okay, it is that you, we have the number, we came first, I am in the village, you have the number, now we will set it. What to do and which will remove the result return and what will we do now the result from a requested time create and now what will we do for light from which or from this will go to the temple that dot length and time is plus in timepass loop and American what to do to retain bread So result ok so now we will see if the exam will be cleared we are appointed here but now we village good we will do something we will ask shampoo dot hey at this time but there is nothing result sports sorry result push here But we will use time temporary which is the area, we will press our time introduction, we will press the slice of tempidaje that dot and we will remove the youth of and that means the first one who will put our subscribe, then the accused is this number, so now we subscribe to it, we all appoint village. Will create havoc Subscribe to That Reddy BRC We have turned it on now, so if our sentence is almost complete, now we will join it here and this is our opportunity. If we need it, we have got the sentence, so it is a little bit but it is a very good remedy to clear which one, so now what will we do in this, our control is going on Thursday and appointed and we will submit it and create that our purpose. If you understand then you can see our answer. If it is successful this time then if you have any question then please comment subscribe video subscribe my channel then thank you for watching my video thank you jhal
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
120
hey everyone welcome back and let's write some more neat code today so let's solve this question triangle pretty simple but you definitely need an iq of at least 130 if you want to be able to solve this problem just kidding with enough practice an iq of 90 is more than enough and don't forget to like the video it supports the channel a lot so this is presented as a pretty simple problem we're given a triangle array and we want to return the minimum path sum from the top to the bottom so what is a triangle array it's a nested array right so we have one array a second array a third array and a fourth array and they tell us that the minimum path sum from top to bottom is 11. we have a two as the first one a three from the second one a five from the third one and a one from the last one so that's the minimum path sum when we're going from the top to the bottom but this is a nested array how do we even visualize that so this is what we're given right we're get i'm i rewrote this right so it's a little easier to visualize we're given a list of arrays where the first array is dimension one this one has two elements it has three elements and this has four elements but even this we can redraw this to make it a lot easier to understand since we're looking for the minimum path sum why not draw this similar to a tree so i redrew this as a tree of some kind right like we can see that for two it has a pointer to both of these children right like both of the nodes at the that the lower level but it's not a true like binary search tree right like look three has access to six and five but four also has access to the five why did we do it like this why did i draw it like this well when you look in the instructions they say for each step right we're trying to get the minimum path sum from top to bottom and they say for each step we take you can only move to an adjacent number on the row below so any adjacent number so while this is similar to a tree it's not exactly equal to a binary search tree but it's similar enough that we can use that to our advantage so we know from the example that from starting here that this is the minimum path sum from top to bottom and the sum happens to be 11. but how can we find it well one way is recursively right we know we have to include two but am i gonna go left or am i gonna go right even though three is smaller it's not necessarily true that this is gonna guarantee the smallest path because what if we have a four here but what if this was a zero and this was a zero in that case we would have this as the minimum path so one way to do this is recursively right like depth first search first find the minimum path sum from here and the minimum path sum from here right sub problem territory we know for three we can more easily do that sub problem right like so now from three we're gonna do the exact same thing recursively we're gonna do a sub problem right so now i wanna know what's the minimum path sum containing the six and the minimum path sum containing the five and so we can repeat that recursively continue to do sub problems until we get to the base case so for three i wanna know what's the minimum path sum i can get for each of its children so for six and five what's the minimum path sum we can get and we see that six is not done yet it has a couple children of its own so we gotta repeat that process what's the minimum path sum for four and for one now finally we get to the base case it has no children right so we can consider its children to essentially be zero so then what's the minimum path sum for four it's just four this is the base case so i'm just going to mark that right here so we know the minimum path sum for this is 4. now we can repeat the same thing for this it's also a base case these are zero so i'm just going to put a little one here though it's probably not necessary because we see these values anyway so now since we did this recursively we gotta go back up to our parent which is six so for this six i want the minimum path sum so am i gonna do six plus one or am i gonna do six plus four clearly this one is smaller so we're gonna say the minimum path sum 4 6 is 7. so i'm gonna mark that right here we know that the minimum path sum for this 6 is 7. and we're going to repeat we're going to go back up to our parent three now for three we know that the left path is gonna be three plus seven but what about the right path over here well we didn't compute it yet because we never looked over here we never looked at this eight we already visited the one over here so that's repeated work we don't have to do that but this eight we know it doesn't have any children right so we're done with it we can mark it as an eight it's a base case and then when we go back up to this five we can see clearly that the minimum path is five plus one not five plus eight so next to this i'm gonna mark the minimum path as six so it's getting a little messy but i hope it's still a little bit readable so remember what we were trying to do right this three plus seven comes from here that's one of our choices the other choice we have is clearly a three plus six now right so which of these is smaller clearly the bottom clearly this one right three plus six is nine so next to our three we can mark the minimum path sum as being nine now we can finally go back up to our root node we can go up to the two and now we wanna know what's the minimum path sum of this starting at this two because that's what we were trying to get originally right so we have one choice if we go left the minimum path sum is going to be 2 plus 9. but what about the right choice now i can show you how to you know we can repeat the process that we just did over here but we know that the solution is on the left side but you know just for visual purposes it's obvious looking at the picture the minimum path sum from this 4 would be going down here to five and six which is going to be 10. so our choice is 2 plus 9 or 2 plus 10 we know 2 plus 9 is 11 which is smaller so this is our minimum path sum so we just did it recursively but is there an easier way to do it we know that the base case for all of these is they have children as zero basically right so let's actually do the dynamic programming solution let's start at the bottom and work our way up so for four i know the minimum path sum is four for one it's one for eight it's eight for three it's three now let's work our way up so at six all i have to do is take the minimum of my two children right so compare four and one i know that four is greater than one right four is greater than one so we want the smaller element so we do six plus one is seven let's repeat that for five so i have two children one and eight i know that eight is greater than one so i'm going to do five plus one which is six and last but not least in this row we're going to look at four we know eight is greater than three so we're going to do four plus three which is seven so now let's work our way up to the next row we wanna look at three what's the minimum path sum with three well seven is greater than six right so we want six we're going to do three plus six is nine repeat that for four we see that seven we have a seven on the right we have a six on the left six is smaller we're gonna do four plus six which is ten and now we get to two the left is nine right is ten we're going to do two plus nine is eleven so our solution is 11. so that's the dynamic programming algorithm the main thing to notice about the dynamic programming solution is that for this row we only need the bottom row which is only zeros right and for this row we only need to use this row so if we want to compute this row we only need the bottom row similarly if we want to compute the second row we only need to use this row and then to compute the last one we only need this row so we only need to save one row at a time so that tells us that the memory complexity is going to be big o of n where n is the number of rows that we have in our input now the time complexity i think is roughly o n squared because that's roughly the number of elements that we have in our input so the code is actually even simpler than you might expect because we're doing the dynamic programming solution so i'm gonna have dp this is like the bottom row that we're gonna keep track of remember we only need to keep track of one row and we're gonna fill it with zeros now how long is it gonna be it's gonna be the length of the bottom row plus one and the reason is because we know that every row is get every row below increases by one now we want to iterate through each row in the input and we want to do that in reverse order so in python we can do it like this so we just want to reverse triangle and then iterate through it now i want to go through every single value in this row in python i'm gonna do it like this so i'm gonna get i'm gonna enumerate this row so we can access the index and the value at the same time so remember how dp contains the row below so we want the minimum of the two children of i we can get that with dp of i and dp of i plus 1 and then just take the minimum of it so we want to take the minimum of the children and then add that to n which is the value that we're looking at right now and we also want to put this in the next row so we can actually overwrite dp of i because we're doing it in such an order that we'll never need to use this value this original value again so all we're doing here is getting the minimum path sum from this value which is at this index in this row we're looping through every row every value getting the minimum path sum so literally that's it we're done what can we return well we want the minimum path sum from the root so by the time this is done executing we will have the minimum path sum stored in the first index of this row so just to visualize it i'm just going to show you really quickly what the algorithm is going to do so and remember initially we're going to have all zeros and notice how we have five of them because that's because in the bottom row we have four values and we're just gonna add one so next for four we're gonna take the minimum of these two add it to four so next we would replace this zero with a four we would replace this one this zero with a one we would replace this with an eight replace this with a three and then we don't have to look at this row ever again next we would replace this four with a 7 we would replace this 1 with a 6 we will replace this 8 with a 12 and then we're done with this row we don't have to look at it again 3 values here we have three values here so next we would replace this seven with a nine we're going to replace this six with a ten and now we took these two values and now we have them here we don't even need this anymore but it's going to be stored in the array regardless we don't even care about it we never have to look at these again we just have one left and since this 9 is the smallest we are going to end up with an 11 over here and that's what we're going to end up returning that's why we return the value at the zeroth index so i hope this was helpful please like and subscribe if you enjoyed it supports the channel a lot and i'll hopefully see you pretty soon
Triangle
triangle
Given a `triangle` array, return _the minimum path sum from top to bottom_. For each step, you may move to an adjacent number of the row below. More formally, if you are on index `i` on the current row, you may move to either index `i` or index `i + 1` on the next row. **Example 1:** **Input:** triangle = \[\[2\],\[3,4\],\[6,5,7\],\[4,1,8,3\]\] **Output:** 11 **Explanation:** The triangle looks like: 2 3 4 6 5 7 4 1 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). **Example 2:** **Input:** triangle = \[\[-10\]\] **Output:** -10 **Constraints:** * `1 <= triangle.length <= 200` * `triangle[0].length == 1` * `triangle[i].length == triangle[i - 1].length + 1` * `-104 <= triangle[i][j] <= 104` **Follow up:** Could you do this using only `O(n)` extra space, where `n` is the total number of rows in the triangle?
null
Array,Dynamic Programming
Medium
null
1,197
what is going on everybody it's your boy average leader here coming at you with another video today we're tackling minimum night moves number 1197 on leak code uh it's commonly asked by mathworks facebook doordash amazon google and a few other companies so without further ado let's get right into it uh in an infinite chess board with coordinates from negative infinity to positive infinity you have a knight at square zero okay so this is important negative infinity to positive infinity there's no bounds but we have a knight starting at zero uh a knight has eight possible moves it can make as illustrated below each move uh is two squares in the cardinal direction and then one square in the orthogonal direction so basically any l shape from its current uh position so this l and so on so forth return the minimum number of steps needed to move the knight to square x y it is guaranteed the answer exists okay so off the bat and this is screaming uh do a breath for a search um and the reason i say that is because we're asked to return the minimum number of steps or the minimum path between two known uh locations or two known positions so basically if we're given a starting position which we know the knight is at zero and an ending position which we will be given through our parameters x y and we're asked to get the minimum path in between this is a very standard bfs question so we'll just start from our current position and we'll search on every single position or coordinate that is l shape away that is n l shape away okay and after we do that we'll just go to that position and then go another l away and then from that position another loa until we find of our target x and y so let's get right into coding this thing um so what are we returning well returning the number of moves so let's make a moves variable and i'll just make it zero in the beginning and uh you know for bfs we typically will use a q so um i guess the question is what are we storing in this queue well uh you know everything is given to us in xy coordinates uh we have like a starting coordinate of zero we have an ending coordinate of like x y so like let's just maybe store some coordinates in our uh in our cube i mean i think that makes sense because when we go you know search for like the next possible x y coordinate x y pairing it'll just be easy to hold a coordinate so how can we actually do that i think a very easy way to do it is by making a coordinate class um so that would look something like class coordinates oops my bad not that and in the class we'll have two instance variables we'll have an x position and then a y position and then we'll have a constructor that will assign our x position y position to whatever we want it to be so let's go ahead and do that here it's y and we'll do this dot x equals x and this dot y equals y so remember uh this dot x is referring to this instance variable are the coordinates the our coordinates x variable and this x is like whatever we're passing in so we're setting our coordinates x to whatever we pass in and we're doing the same thing for the y okay so now we have our coordinate class okay so let's go ahead this queue is going to store coordinates and um we will initialize it to be a new link to list remember we can't initialize it to a queue because q is an abstract data type so we need to make it a linked list and awesome so what is going to be the very first thing we put into our queue well we're told that the knight will start at zero so let's go ahead and add coordinate zero so q dot add new coordinate zero awesome so now uh after we okay so now a typical bfs implementation would be uh you know while this queue is not empty we get the size of that q and iterate through all the coordinates in that size and for each of these coordinates we encounter will add their neighbors or any points that are an l away from that coordinate we'll just add those to the queue so that would look something like this um while the queue is not empty um we'll grab the size and we're gonna you know reinitialize the size every time we're in our while loop oops uh equals q dot size and uh we're going to iterate you know through everything that's in the side so we'll do this by doing like a quick for loop four ends i equals zero i is less than size i plus awesome so we you know created this for loop to iterate through the neighbors or through sorry we created this for loop to iterate through everything that's in our q and then find all of its neighbors so how do we actually get these neighbors well since we're working with x y coordinates we know that to get to a neighbor point uh we need to add 2 to all the cardinal directions as shown here in the instructions and then one square to the orthogonal direction um so if we're going to so if we're traveling two squares left to right then we're gonna we know we're gonna have to go one square up or down right to actually simulate that l and similarly if we're going one square left and right then we're gonna have to go two squares up or down to also simulate that shape of the l so uh one way where we can kind of like simulate these or like hold these directions is by maybe utilizing some extra storage to hold uh the you know these directions so i can do that up here and yeah keep in and keep in mind so in our directions if we look at the x direction specifically how many places can we go from our current position well we can go negative 2 to the left negative 1 to the left positive 1 to the right and positive 2 to the right so let's just do that uh in our x direction and this is gonna be an array of integers we can go negative two to the left negative one to the left one to the right and two to the right and what direction can we go in our y well you know so while we're negative two right now while we're negative two to the left we can go up one or down one so basically plus one in the y direction are negative one in the y direction so let's just pair the negative two with a negative one and a positive one and uh before you know the way i can do that is by adding two of each of these uh x directions so that we'll have two negative twos um two negative ones and then two ones and two twos and you know like i said to in when we go in the negative two direction we can go uh plus one in the y direction minus one in the y direction so that's exactly what i'm gonna have here minus one and in the m when we go minus one in the x direction we can go plus two or minus two in the y direction so i'm gonna do that right here minus two uh two and when we go one it's going to be very similar we're gonna go minus two and plus two in the y direction so we'll just do that minus two uh two and finally we're gonna go minus one and one in the y direction when we have uh when we're going you know two to the right in the x direction so uh perfect now we have all the directions that we can traverse through okay so from our current points uh we can get our current point about by just popping off or like removing an element from the queue so i can just do that by doing something like this coordinate p equals new oh sorry equals q dot remove and now we're going to iterate through our x directions in our y directions and add each individual direction pair to our current uh coordinates x and y and then add that new overall coordinate to our q um so that's exactly what we're going to do so i'm going to iterate through one of these arrays i'll just iterate through the exter equals zero j is less than x stir dot length j plus and we're gonna make create like a new position or a new coordinate so i'll just do uh int p x or sorry new p x equals p dot x which is going to get this uh this p's x coordinate plus x der i so it's gonna basically go through all of these x's and add uh add that current direction to our p uh to our current coordinates x position and we're going to do the same thing with the y's so p dot y plus wider we're going to index it at the in the you know i oh my bad not the i it's got to be in the j because you know we have j here so not i j okay great good thing i caught that um and we're going to add this new coordinate point this new x y coordinate to our cube new coordinate uh new px new p y awesome and now finally uh you know remember what are we trying to output it's the minimum number of moves so at some point we know we have to increment this moves variable so when would we do that well um you know by iterating through all the directions that could be added to all the coordinates in our cube we are simulating one more move that could be made from our current position so in other words after we go through all the coordinates in our queue or after iterating through you know after going through this for loop um we can just add one to our moves so finally uh since we're returning the number of moves um when would be a good time to return like our moves well if our coordinate that we're removing if that x position and y position equals what we're what's passed in then we know that we're at the target uh position the target coordinate location so let's just do like a quick check if px equals x and p dot y equals y we know we're at the target location so let's just return the number of moves that was created or that were made to get to that position and otherwise you know like if we don't have another return statement up here uh this is not going to compile so you know this should well and since we're since we know that the answer is always going to exist this is going to be the return that's always going to trigger but like for whatever reason uh maybe we're just giving like empty input or something like that we'll just return negative one okay so this is how you do it guys so let's run it perfect this is the first time on this channel that has actually uh worked uh first time so let's go ahead and submit this and that is the video guys let's just uh you know thanks for watching they ask you how you are you just have to say that you're fine when you're not really fine but you just oh shoot oh man we got a time limit exceeded well okay so i guess you know most of you guys can see that this wasn't necessarily the most efficient way we could do this right um but you know we're pretty close i'll give you guys that so you know when we're given a bfs how can we make the solution a little bit more efficient when we're working with a search type problem i think the easiest two efficiencies that we can make is one make sure we're not uh visiting the same coordinates over and over again and two try to maybe uh make our search space smaller okay so those are the two efficiencies that we're going to keep in mind while we work through this problem you know if we take some time to think about this and you know maybe visualize it or if we draw this out in our current implementation we'll quickly see that many coordinates end up being visited a few times uh and we're not caching any of these so similar to my course schedule video i think we need to key you know find a way to keep track of all the coordinates that we've visited so far so we don't visit them again and a quick way to do this is by adding maybe like a hash set or a visited set and storing these coordinates in the hash set and making sure that we only add coordinates that aren't in this visited set okay so first let's work with that first uh so let me go ahead and do that now let me create a set here and what would this hold well you know it's gonna be hard to store coordinates here because we need to figure out a way like the contains method uh calls like the equals method and you know in the equals method we don't really have like an equals method in like our coordinate class or like meant for coordinates we would have to overwrite that implementation and i think that would just be like a little you know cumbersome in a small you know time period so i think uh easier way to do this something that i always tend to go to is just maybe let it hold strings or string and i'll just like convert our coordinate into like a string so um i'll do it something like this uh set visited equals new hash set and i'll add the all right since we have like our first coordinate at zero i'm going to add zero and this is how this is going to be the uh representation of all my coordinates that i'm going to add in the visited setting i'm just going to have the x coordinate and then a comma and the y coordinate very straightforward so where do i where else would i need to add this you know add coordinates to our visited set well i would have to do it when i add uh add something to the queue so i'll also do visited that add and see we made this real nice and easy we got the x coordinate we got the y coordinate so all we're going to do is new px or you know just to make this even like as clear as possible uh clear i'll just make like a new string and i'll call it s equals uh new px plus with a comma plus nu py um and you know this by just adding this string right here this will convert this entire thing to a string and now we'll add uh we'll add this s to our visited set now when are we going to now with the information that we you know were provided like we just said we're not going to add coordinates that are already in our visited set so we'll do that we'll make it a conditional while we're adding to the queue so if um oh okay so if uh visited that contains and you know what i'm just gonna move this string before it i'm gonna do it right there so if it's contained if it doesn't contains s then we'll go ahead and add it to the queue and add it to our visited so this is a quick efficiency uh to make this a tad bit better and you know if we run it i think this will work but let's see if this is if lead code will allow this it's running no another time limit exceeded let's see uh you know what tests have passed it looks like all the tests have passed but it's still taking uh a bit too long so let's just think about one last way one more way we can make this a little bit more efficient so remember how i said earlier another thing we could do is to make our search space a bit smaller um and just look at like just looking at our you know graph here we see that you know it doesn't really matter like what direction you're going or like it doesn't really matter if we are given a target of like a negative number or a positive number uh in other words if we had to go to negative four negative two that takes two moves to get to right we know it takes two moves to get there but if we were going to positive four positive two that would take two moves to get there too um but you know if we had to go to positive for positive two our immediate directions that we're going towards is like in the negative direction based off of how we have it in our implementation i do think it's important to go through the negative direction in case you know for some moves we have to like go we have to jump a little bit forward and come backwards by utilizing this negative direction but the key to this problem really is understanding that everything is symmetric um or in other words if we were given a positive x and a positive y uh let's say 5 and we were given a negative x and a positive y are negative 5 it take it'll take the same number of moves to get to both so if since you know knowing that what if we just reduced our search space to just maybe like only positive numbers um that's like the quickest way to you know make our search space even smaller so if we were you know giving numbers negative 5 or sorry negative 4 or negative 2 we know it takes two moves but if we just searched only in the first quadrant for positive four positive two and only looked in this you know top right quadrant that will significantly cut out like a good chunk three-fourths of our like a good chunk three-fourths of our like a good chunk three-fourths of our search space so let's just do that um let's only look at positive the positive uh values um so what if we were given negative values well it's easy we'll just take the absolute value of them uh and that would look something like and we'll just do x equals math.abs x we'll just do x equals math.abs x we'll just do x equals math.abs x and y equals math.absolute and y equals math.absolute and y equals math.absolute and we'll only look at the uh top right quadrant so every time we're searching for a new px and a new py let's make sure that is that value remains uh in that top right quadrant or in other words we can just check to see if px is greater than or equal to zero and py is greater than or equal to zero so and new px is greater than or equal to zero and mu p y is greater than or equal to zero so let's just think about this we've drastically cut out like we cut out so much of the board we're only looking at this top right quadrant let you know let's just make sure that we're reaching all the points um you know it's time to like test out our code test out you think of a few test cases that might possibly fail so i'll give you guys a few seconds to think about that you know pause the video here and unpause whenever you guys are ready but in this particular situation is there any point where sometimes because we are given the freedom of going in the negative direction could there be a space where it's smarter to go or it saves it takes less moves to go out of the board or like out in the negative direction and then back into the positive direction well let's just look at coordinate one first if we went to one in our uh in our original code without looking with by only constraining ourselves to the top right quadrant we'll notice that it takes four moves to get there but if we go outside of the board and then come back in it'll take two moves so let's just be a little bit uh well we'll just be a little bit lenient and recognize that to get there maybe there are a few spots on the board that require us to go outside of the board at least just one time so at a max it can go two spaces to the left or two spaces down um and you know anything after that'll just be more than one move in the in outside of that first quadrant so let's just be a little lenient here and we'll say if our as long as our new px is uh a greater than or equal to negative two and as long as our new py is greater than or equal to negative two thus allowing ourselves to make one and only one move out of our bounds to go back in order to make like maybe like a bit of a better more efficient solution um and let's see if this works okay perfect it passes that one let's see if that passes the whole perfect greater than 50 of java uh you know runtime is better than fifty percent memory better less than forty eight percent so let's talk about the runtime of this entire thing um i believe since we are not visiting uh already visited uh coordinates um then i think this would be o of n where n is the number of moves we'd have to make and our space complexity well since we're utilizing a q in a visited set which can also hold like at max like uh you know n moves i think our space complexity is also of n and yeah guys that's how you do that problem let me know what you think let me know if this was helpful you know this time around i didn't go straight for the ipad i like coded it out how i thought of the problem um and then made it a little bit more efficient after that tried to kind of simulate how we'd go through in an interview um but yeah let me know what you think let me know if there's a video you want me to do and oh you know always if you like this video if you thought you found some value from this video make sure to like and subscribe you know give me a comment i'll make sure to respond back to you um and yeah guys i hope you guys have a good rest of the day
Minimum Knight Moves
parsing-a-boolean-expression
In an **infinite** chess board with coordinates from `-infinity` to `+infinity`, you have a **knight** at square `[0, 0]`. A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction. Return _the minimum number of steps needed to move the knight to the square_ `[x, y]`. It is guaranteed the answer exists. **Example 1:** **Input:** x = 2, y = 1 **Output:** 1 **Explanation:** \[0, 0\] -> \[2, 1\] **Example 2:** **Input:** x = 5, y = 5 **Output:** 4 **Explanation:** \[0, 0\] -> \[2, 1\] -> \[4, 2\] -> \[3, 4\] -> \[5, 5\] **Constraints:** * `-300 <= x, y <= 300` * `0 <= |x| + |y| <= 300` "t", evaluating to True; "f", evaluating to False; "!(expression)", evaluating to the logical NOT of the expression inside the parentheses; "&(expression1,expression2,...)", evaluating to the logical AND of 2 or more expressions; "|(expression1,expression2,...)", evaluating to the logical OR of 2 or more expressions.
Write a function "parse" which calls helper functions "parse_or", "parse_and", "parse_not".
String,Stack,Recursion
Hard
null
1,792
hello everyone let's take a look at this local problem next maximum average pass ratio so this problem is third problem in the context and um this contest um like this week it's not very hard context okay let's take a look so the problem uh just as follow the following is if you haven't read it you can take some time to read it so the problem here is uh we need to make the maximum average ratio and how can we make it let's take this example so for the first student like which classes we should assign to of course we should assign the brilliant student to a class so that we can maximize the average score okay if we assign students to the first class like we can get additional like 0.1666 like we can get additional like 0.1666 like we can get additional like 0.1666 if we assign to second class we can get 0.0666 0.0666 0.0666 if we assign it to third class we can get nothing so it's pretty a good graded approach we should assign the four students to class one so that we can get some maximum increase from it okay so we can use probability q here we can compare them by the increase the value right so this is the solution this is our compare function uh like this is already an original pass ratio and if we assent a student to him and this is a new pass ratio and this is increased mu minus or original so we need a maximum heap here so that we can place some maximum increase class in the top and every time we will pick some maximum increased class okay then we have a priority q here and we need to push every class into this priority queue not clear we pass by the pair instead of the vector of integer since the overhead effective integer is pretty large so we will get to here if we push vector in into our out priority queue so we need to push a pair into our product queue okay let's use this example first we have three classes and actual students is two so we push the three classes into our priority queue next we need to iterate those actual students when you assign them one by one to each class so at first we get one two since one two will be the top element in our other queue since it has a maximum increase next i assign this brilliant student to this class the one who becomes two three and i push it back to our queue okay in next iteration we pick the elements at stop it's 2 3 which has the maximum increase if we assign the students to this class then we as uh increase two three becomes three two and we push it back okay now the iteration finish we can collect this score the pass ratio okay so sum is uh like 3 divided by 5 plus 2 divided by 2 plus 3 divided by 4 and the average part ratio is sum divided by the number of classes which is 3 in this example okay that's it so the core idea here is uh we need to use gridded approach to assign each brilliant student and in order to make the approach faster we can use priority q here thanks see you next time
Maximum Average Pass Ratio
find-the-most-competitive-subsequence
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` number of students will pass the exam. You are also given an integer `extraStudents`. There are another `extraStudents` brilliant students that are **guaranteed** to pass the exam of any class they are assigned to. You want to assign each of the `extraStudents` students to a class in a way that **maximizes** the **average** pass ratio across **all** the classes. The **pass ratio** of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The **average pass ratio** is the sum of pass ratios of all the classes divided by the number of the classes. Return _the **maximum** possible average pass ratio after assigning the_ `extraStudents` _students._ Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** classes = \[\[1,2\],\[3,5\],\[2,2\]\], `extraStudents` = 2 **Output:** 0.78333 **Explanation:** You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333. **Example 2:** **Input:** classes = \[\[2,4\],\[3,9\],\[4,5\],\[2,10\]\], `extraStudents` = 4 **Output:** 0.53485 **Constraints:** * `1 <= classes.length <= 105` * `classes[i].length == 2` * `1 <= passi <= totali <= 105` * `1 <= extraStudents <= 105`
In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right?
Array,Stack,Greedy,Monotonic Stack
Medium
402,1159
250
hello and welcome to another Alico problem we're going to be doing count uni Valley subtrees and it's a premium problem of the week for this week so in this problem given the root of a binary tree return the number of uni value subtrees a uni Valley subtree means that all nodes of the subtree have the same value so for this okay so we have this tree and so what they mean by uni value subtree is it can be any subtree with a root and like the rest of its nodes have to have the same value but it doesn't have to be a complete treat like this could still be a subtree even though there is no left node and so from the example you could see that any Leaf node is always going to be a subtree because it's only going to it's going to be a tree of length one so that's always going to be a sub tree now um let's think about like what we need to be doing so the easiest way to do problems for uh four trees in general is going to be recursion but like what recursion are we going to have right and so it's pretty straightforward so what we can just do there's a few ways to do this I'm going to do this with a global variable so we're going to take a global variable called like result right and we're going to just you can there's a bunch of tricks you can do you can have it being on local you can have a result be an array of length one and then just update the value there you can do a bunch of different things but regardless so what we're going to do is we're going to have a traversal function that's going to Traverse all the way down to like the leaves and then simply when we get to a null node we can just return so we're going to have uh we're going to have a few return values we're going to have a return value that is actually the value of all of the nodes in the tree and so I'll show you what that looks like and then we're going to have another return value like negative Infinity meaning you know we had a null node but it's still fine and then we're going to have another return value Infinity meaning like the rest of the subtree is no longer you know a unique uh or a unival tree or whatever the name was so let's take a look what this is going to look like let's take a look at our results so we're going to have a result right here and we're going to Traverse all the way down so we're just gonna Traverse all the way down so like for example let's just say we Traverse left right so we're going to go over here then we're going to go over here and we're going to be at this node is going to have no children but what I will do is I will still go into the children and so when you go into the children these children will just return negative Infinity and so their turn for this left will be negative Infinity and this right is going to be negative Infinity and then what you simply do is you make a left and right value for the return values once you recursed back up so we'll recurse back up and we just have to check okay is the root value the same as the left and right value or you do that has to be the same as the left or right value or those values have to be negative Infinity meaning any value works so that's how I'm going to symbolize it in mine you can do it in a bunch of different ways but so for this first example you're going to return up to negative five you're going to check the left and the right and you're going to compare it to itself because they're both negative Infinity that means they're fine like we don't if they were something else then it wouldn't be fine like if they were six or something so that means this is a uni value subtree and so we would have one here now we would return back up here and then the number we're going to be returning is going to be the value of the uni value subtree so if some other subs like if some of its nodes were Infinities we're still going to return the value of the nodes if it's a null node we're going to turn negative Infinity but if it's a actual node that we care about we're going to turn the value so we're going to turn a 5 up here now we're going to recurse right and we're going to do the same thing on this node where it's going to have two negative Infinities and so when we check the negative Infinity is with itself that'll be fine so we're going to add one to the result now we're going to return a 5 up here okay and now that we return back up to this one node up here we're going to check then the one to the left and the right and now these are no longer negative Infinity so we actually have to compare the values and so because the one has to be equal to both the left and the right and it's equal to neither that means this is not a uni value subtree and now when we return we need to send a message to the node that called it saying like now this is no longer a uni value subtree and so what I'm going to use to represent uh not a uni value subtree is actually going to be Infinity I just want values that like we can't we don't have so I'm going to return Infinity up here and now here we need to go to the right child and then we need to go to the right child again this will be a unique value subtree same kind of thing here where it'll have a negative Infinity for the two nodes so then we're going to add another one here we're going to return the value 5 up here now we're going to compare this 5 to its left and right child so it only has a right child which is 5 which is fine and then it's left is going to be negative Infinity which is also 5 like I said you either have to have the values be equal or they have to be negative Infinity so this is a fine unit value subtree this one right here and so we're going to add another one and now we're going to return finally the value of this 5. so we're going to return the value of this 5 and remember here where you turned Infinity symbolizing like everything we're returning everything we're turning upwards is no longer going to be in Union Valley subtree so this red child is equal to the node but this left child is infinity so therefore that's not a uni value subtree the left child either has to be five or negative Infinity to be a uni value sub tree and that's pretty much all you need to do you just recurse down to the nodes you have something to symbolize a any value State and then you have something to symbolize a nothing from here will work like let's say like once you get an infinity and you start returning up you're never going to get a union value subtree to anything you return like once you're once your subtree is not good it's never going to be good anymore hopefully that makes sense why that is and yeah so like let's say we would return up here we would always just be returning infinity and then nothing would work and that makes sense right because when we're cursing up that means like the root and all of the children which we just came from have to be the same value and we're sending them staying there or not I guess that's pretty much everything we're gonna need to solve this problem and now let's do it so like I said I'm going to have a result value you could declare in a bunch of different ways so I'm just going to declare it actually need to reset the code okay so what I'm actually going to do is I'm going to declare it uh here and I'm just going to make it an array of size one you can do it you could do this you can you could give it a value you can make it non-local I it a value you can make it non-local I it a value you can make it non-local I guess I'll do that just to show them on local so we're going to say our result is zero now we're gonna have a helper function we'll call that Traverse and then we're just gonna have a node so remember if the node does not exist so if not node just return negative Infinity right okay now if the node does exist we need to go to the left and the right so that's pretty straightforward left equals reverse the left right equals Traverse no dot right we're going to visit Boston right first before comparing to the root and so the left and the right have to either equal the root or they have to be negative Infinity either one works and so now we just have an if statement here so if uh left equals negative Infinity right so negative infinity or left equals the value of the node and so that's going to be uh there we go and it needs to be both of these so the left needs to equal one of these and then the right needs to have the same thing that we need to have an and here and we can probably just do like something like this because this is going to take a lot of space so we can do something like this okay let's just copy this code over here so right means to either equal negative infinity or the value of the known correctly yeah and so now we do this so if that's the case that means we do have a valid uh unival subtree and so we're going to call a result we don't have access to it so we need to do this you could also make it a class variable and then call self on it either one's fine res plus equals one that means we have another Union value subtree and so if this is the case if this whole like let's say we're at this whole thing if this is Union Valley subtree then we need to pass back up its value right so we need to return dot val otherwise uh otherwise it's not a uni value subtree and so we need to return negative Infinity to symbolize to every parent of that we're no longer going to have a unibody subtree so we can return infinity or Infinity here you can use other numbers just look at the constraints so I think this is like negative a thousand to a thousand you can use ten thousand to symbolize or whatever you wanted to actually you can probably just even return like because it's python you can just return a different type you can return like false or something I think that would work too but yeah um so now what we need to do is we need to return uh Infinity right okay and so now finally we need to call Traverse on the root and we need to return the results so let's see how many things we screwed up as always okay it looks like we did not okay so pretty efficient um yeah and so the other way you could do this is like you can technically not use a res hair you can probably pass down values and add them up but I think this is pretty clean and uh yeah if you don't like using this non-local you can just like using this non-local you can just like using this non-local you can just make it a class variable if you don't want to use that okay and uh yes I think uh that's gonna be it for this problem now let's just do the time and space here that's pretty straightforward for almost all three traversals we need to visit every node so it's going to go then for every node and space straightforward as always so for a space for a balanced ish tree it's going to be log n and the worst case scenario our entire tree is um as always gonna look like this right so our entire tree is not balanced at all then we're gonna have to have this whole recursive call stack saved in space and so that's going to be a big oven worst case but if it's somewhat balanced it's gonna be log in because it's a tree with two children okay so that's going to be it for this problem hopefully you liked it if you did please like the video and subscribe to the channel and I will see you in the next one thanks for watching
Count Univalue Subtrees
count-univalue-subtrees
Given the `root` of a binary tree, return _the number of **uni-value**_ _subtrees_. A **uni-value subtree** means all nodes of the subtree have the same value. **Example 1:** **Input:** root = \[5,1,5,5,5,null,5\] **Output:** 4 **Example 2:** **Input:** root = \[\] **Output:** 0 **Example 3:** **Input:** root = \[5,5,5,5,5,null,5\] **Output:** 6 **Constraints:** * The number of the node in the tree will be in the range `[0, 1000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Binary Tree
Medium
572,687
1,920
hello everyone so in this video we will solve liquid problem number 1920 that is Bill Danny from permutation so I have already solved this problem using order of and space and this time I will solve it using order of one space so for knowing more about the problem description and solving it in order of and space please refer to my previous solution video I will provide the link in the description section so let's come to the example part given input array that is nums is equal to 0 to 1 5 3 4. so this is our nums array and we have to return a new array or the same array in the form of where answer of I that is each element in the array is equal to nums of I yeah so we have to do it in a constant space that is order of one space and for doing it in order of one space we are not allowed to create a new array so what we can do is we will update this array only and we will return it okay so I'll write one thing for the reference that is value of I nums of I and lumps of nouns of I of nulls of I for I varying from 0 to 5. 0 1 2 3 4 5 and answer 5 is 0 2 1 5 3 4 and answer 5 will be 0 1 2 4 5 3 so if we directly update the nums array then we will lose initial value and we won't be able to proceed further like if we directly update this nums array then for the first element the nums of nouns of I will give us 0 for the second element the numbers of nums of I will come 1 but for the third element that is uh for the two the nums of I will be 1 and if we go and check the one position that is one index now then the element present over here is one so this element will come as 1. but it should be 2 so if we try to directly update the array then we will get the wrong values so we have to update our array in such a way that we don't lose our initial value and also we are able to put the final value that is nums of I into this so for doing that we will use multiplication division and modulo operator so here the number of elements in the array that is n is equal to 6 so this is our array that is 0 to 2 1 5 3 4. yeah okay just let me erase this yeah four so this is our initial array and now we have to update it as nums of I so for the first element the nums of I will be 0 but we are not going to put 0 directly on the first place we are going to put it as a multiplication of 6 like 0 plus total number of elements in the array is 6 so 6 multiplication the nums of nouns of I that is 0 so this way we got the zero I can write in this is multiplication then again for the second element and that is uh nums of I that will come as one so we will do 6 into 1 and here it will be plus yeah so for third element again we will do like that and this times 6 into what is nouns of norms of I for the third element it is two yeah so for the fourth element the nums of I is 4 so we'll put it like six into four for The Fifth Element the nums of null suffice is 5 so we'll put 6 into 5. for the Sixth Element it is 4 plus 6 into 3 so I'm just showing you how the expanded version will look like but the value stored at the those index of the array will be 0 8 here it will be 13 20 29 and I will give you 30 plus 33 and here it will be 16 18 and here will be 22. yeah so for getting the initial value we will use the modulo operator that is a number modulo 6 so if we do uh this number modulo 6 we will get the initial part if we do this mod a num if we do this number modulo 6 then we will get two if we do this number modulo 6 then we will get one so we are keeping the initial value as well as the new value in this array so at last what we will do is we will use the division operator and by using the division operator we will remove the initial part so if this number is divided by 6 then we will remove this part and this 0 will come out as a output and if this number is divided by 6 then we will remove this R2 part and one will come out as output that is nums of norms of I yeah so and if this number is divided by 6 then 1 will be removed and we will get 2 as an output that is nums of I so now let's code this in C plus yeah so n is equal to number size that is a number of element in the array and here I am iterating through all the element and I am updating the value by nums of norms of I and I am keeping it in the multiplication of n I've used modulo and over here so that I can get the initial value and At Last I am using the division operator to remove the initial values so if we remove the initial value then we will get the nums of I so let's run for one of the test case yeah so there is another use of Undeclared Android file and so it should be end and start science yes so this is accepted now let's stand for all the test cases yes so this is also accepted yeah so thank you for watching the video and if you find this video helpful please like share and subscribe the channel
Build Array from Permutation
determine-color-of-a-chessboard-square
Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it. A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**). **Example 1:** **Input:** nums = \[0,2,1,5,3,4\] **Output:** \[0,1,2,4,5,3\] **Explanation:** The array ans is built as follows: ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\] = \[nums\[0\], nums\[2\], nums\[1\], nums\[5\], nums\[3\], nums\[4\]\] = \[0,1,2,4,5,3\] **Example 2:** **Input:** nums = \[5,0,1,2,3,4\] **Output:** \[4,5,0,1,2,3\] **Explanation:** The array ans is built as follows: ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\] = \[nums\[5\], nums\[0\], nums\[1\], nums\[2\], nums\[3\], nums\[4\]\] = \[4,5,0,1,2,3\] **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < nums.length` * The elements in `nums` are **distinct**. **Follow-up:** Can you solve it without using an extra space (i.e., `O(1)` memory)?
Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern.
Math,String
Easy
null
732
732 which is a hard question so we are given events with a start and an end value and timestamp the event and time stamp is not inclusive which means that the event ended before this time stamp and we need to figure out the total maximum number of events that can that are that can like occur at the same time so which the maximum number of events that overlap so for example here we have given 10 and 20 so we are booking for event 10 and 20 and is there any overlap with this event no because this is the only one event here again next event is 50 and 60 is an overlap at timestamp between timestamp 10 20 and 50 60. now there is no overlap the next event we have is now 18 and 40 is there any overlap yes there is an overlap between 10 20 and 10 40. so the maximum number of Interest intersections is equals to 2 so we return a value two now and so on so how can we actually solve this problem so let me just write all the timestamps even so given 10 5 and this ends at 15. yeah so this ends at 15 here this ends at 15 again the other one starts at 5 and 13 and the other one starts at 25 it ends at 55 now as we see um there are two events starting at five and at ten there are two events starting at 10 once events ending at 10 so we take the sum of these like if it's starting we add one if it's ending we subtract one so we get a value one here next year it's ending at fifteen so we subtract one it's starting so we add a 1 at 25 yeah one at four TV reduce minus one right 50 we add one at 55 feet so subtract and at six TV out of one and now what we do is we Loop over these values and add these values and return the maximum of these so um the maximum we Loop over the first value and the maximum is 2 so we'll turn two now we add these two and then we return the maximum value of those which is equals to three now we add minus 1 to the result and then return the maximum which it was three again because this is the maximum so that is how we go about solving the problem so writing the code let me let us create an array and I will initialize an error when my calendar three object is called and now every time I every time my booking is called I push the book into the array with water start if it is the start value I'm sorry if it is the start I push the one if it isn't any value push a minus one value with it foreign minus B zero or a one minus B one so how is it sorting so it's sorting based on the start or end indexes so given this we have given an array 10 20. uh five and thirty so suppose this is the in values at indices zero so if we compare 10 and 20 and if these are not equal we sort them in ascending order suppose we have one more thing here now 10 and these values are equal right so we order this paste on the Velvet index one suppose the valid index one was the one value here and for the other 10 it is a minus one value here so what which is one is bigger one or minus one is bigger right so we sort minus one first and then one after that so what we get is something like uh for this one what we get is if you are sorting this value then we get is a five comma zero comma pain command minus one comma 10 comma one so this is what we'll get after sorting this one and now we look over the for Loop we Loop over the array and we need to create two variables per end result so current will add all the values and result will return the maximum of current or the result itself and then return the result at the end let's run our query okay it's Max okay um ah I need to value minus one value at index one great
My Calendar III
my-calendar-iii
A `k`\-booking happens when `k` events have some non-empty intersection (i.e., there is some time that is common to all `k` events.) You are given some events `[startTime, endTime)`, after each given event, return an integer `k` representing the maximum `k`\-booking between all the previous events. Implement the `MyCalendarThree` class: * `MyCalendarThree()` Initializes the object. * `int book(int startTime, int endTime)` Returns an integer `k` representing the largest integer such that there exists a `k`\-booking in the calendar. **Example 1:** **Input** \[ "MyCalendarThree ", "book ", "book ", "book ", "book ", "book ", "book "\] \[\[\], \[10, 20\], \[50, 60\], \[10, 40\], \[5, 15\], \[5, 10\], \[25, 55\]\] **Output** \[null, 1, 1, 2, 3, 3, 3\] **Explanation** MyCalendarThree myCalendarThree = new MyCalendarThree(); myCalendarThree.book(10, 20); // return 1 myCalendarThree.book(50, 60); // return 1 myCalendarThree.book(10, 40); // return 2 myCalendarThree.book(5, 15); // return 3 myCalendarThree.book(5, 10); // return 3 myCalendarThree.book(25, 55); // return 3 **Constraints:** * `0 <= startTime < endTime <= 109` * At most `400` calls will be made to `book`.
Treat each interval [start, end) as two events "start" and "end", and process them in sorted order.
Design,Segment Tree,Ordered Set
Hard
729,731
1,250
hello so continuing this week's contest 161 this is the last problem it's problem number 1250 and the problem says to check if it is a good array that's a title now let's look at it what the problem says so we have an array of positive integers and we want to select a subset of that array and then take each element multiplied by some integer doesn't have to be the same and then get the sum of all those and this array is said to be good if we can get the sum that some of that I just mentioned to be equal to one and so we return true if the array fits this definition of a good array and false otherwise and so an example here we get this array and then the if you pick five and seven multiply 5 by 13 and 7 by -2 we get 15 minus 14 5 by 13 and 7 by -2 we get 15 minus 14 5 by 13 and 7 by -2 we get 15 minus 14 which is equal to 1 for this array 29 6 and 10 multiply 29 by 16.3 and 10 by and 10 multiply 29 by 16.3 and 10 by and 10 multiply 29 by 16.3 and 10 by minus 1 you get twenty nine - ten - um minus 1 you get twenty nine - ten - um minus 1 you get twenty nine - ten - um some number but the sum is one right so let's see okay so let's see how we can solve this so to solve this problem there are a couple of things that are useful to know so mostly math stuff so for example the first thing is visit identity which basically just says that it says that if we have a and B integers right and that are not so basically if you have two integers like this and the common divisor the GCD of both is equal to some value D then that means that a that means that there exist two there exist x and y such that a multiplied by X plus B multiplied by Y is equal to D so that's literally the definition of this theorem and you can look it up and look at the proof if you want but we are just going to consider this one the other thing is the definition of co-prime integers so basically a and B are co-prime we can so basically a and B are co-prime we can so basically a and B are co-prime we can say that they are co-prime if their GCD say that they are co-prime if their GCD say that they are co-prime if their GCD is one and the only numbers two numbers that can give your GCD to be one is when they are co-prime because really they are co-prime because really they are co-prime because really co-prime means that this one this here co-prime means that this one this here co-prime means that this one this here means that their only common divisor is 1 right and that's really the definition so you cannot have well that just the definition they are called when two numbers have the greatest common divisor to be 1 that means that i co-prime there to be 1 that means that i co-prime there to be 1 that means that i co-prime there is nothing else that divides them because the greater 1 is 1 so there is nothing else that divides i'm right so that's one thing so what does that mean here for our problem so our problem says that we get a we get an array with some values let's say X 1 X 2 X 3 and then maybe something like this X I and maybe X N and we want to find the subset let's say subset s in array such that the GCD of all for X let's say Y i for a why I in like that else the GCD of all of them is 1 right so that's what the problem is asking so one other thing you need to know is that if you have GCD of a bunch of numbers we'll say X 1 X 2 and then some other numbers and then a and then some other numbers and then B and then some other numbers right if a and B are co-prime which means they're and B are co-prime which means they're and B are co-prime which means they're GCD is 1 then this entire thing has to be equal to one why because if you have let's say two numbers that there is no number that divides both of them only one is the greatest wanted device both of them right one is the greatest one that divides both of them if you add six to those numbers while six doesn't divide any of them because the greatest one that divides numbers so the problem also just one thing the problem says positive integers so if the greatest one is one that means there is no other positive numbers that divides them right and so if you have any other positive numbers it won't divide it want to divide a and it won't divide B no matter what so any other number in this list right in the array we are sure if a and B are co-prime it won't divide a and it won't co-prime it won't divide a and it won't co-prime it won't divide a and it won't divide B right so that means that we don't need to find every subset right we can just find if the GCD of all the elements in the array if that's equal to one that means we have a subset that has a GCD of one if that doesn't exist that means we don't have that because if we have it no matter how many other elements we add into that set of these two core prime numbers worst we will we don't have we won't have to do one but if we have them no matter what numbers we add a positive number we add will still have GCD equal to one so that basically means that we'll just do something like this to solve the problem we will just say okay we'll start out with the value let's call it J and that would be the array of zero and then we'll just go through every element in the array after that so what from 1 onwards and then we'll just compute the GCD of that element with the GCD we have so far maybe it would be easier to do it if I put it like this GA right and then we can just at the end return j port one so the trick here to notice that we don't need to generate every subset right because if we have any two numbers that have GCD one if we add more numbers it doesn't matter that GCD what we want the thing is we don't know these two numbers well they are they may be here and here right so we can just take the entire thing and check if the GCD is one and yeah that's pretty much it for this problem so loss code it and see if it passes the test cases okay so I just type it the code that we just mentioned in the overview which is start with the first number the problem says that we have an array of at least one number so we don't need to worry about empty arrays and then we take we go through the rest of the array and we should see the everyone with the other with the new value and if the entire array GCD of the entire array is one then we have a solution otherwise no matter what we don't have a subset that has juice if you want and this GCD function I can just import from pythons math library and what's the submit or on it on an example first okay so it passes novels just submit okay so the solution passes in terms of time complexity here it's just our van right because we are just going through the array once so it's just open and space complexity you are not using any extra space just this variable which is constant so the time complexity the space complexity is open yeah so that's a for this problem thanks for watching and see you next time
Check If It Is a Good Array
longest-common-subsequence
Given an array `nums` of positive integers. Your task is to select some subset of `nums`, multiply each element by an integer and add all these numbers. The array is said to be **good** if you can obtain a sum of `1` from the array by any possible subset and multiplicand. Return `True` if the array is **good** otherwise return `False`. **Example 1:** **Input:** nums = \[12,5,7,23\] **Output:** true **Explanation:** Pick numbers 5 and 7. 5\*3 + 7\*(-2) = 1 **Example 2:** **Input:** nums = \[29,6,10\] **Output:** true **Explanation:** Pick numbers 29, 6 and 10. 29\*1 + 6\*(-3) + 10\*(-1) = 1 **Example 3:** **Input:** nums = \[3,6\] **Output:** false **Constraints:** * `1 <= nums.length <= 10^5` * `1 <= nums[i] <= 10^9`
Try dynamic programming. DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j] DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise
String,Dynamic Programming
Medium
516,583,1170,2309
1,964
welcome to Pomodoro doe for Sunday May 7th 2023. today we're looking at the code problem 1964. find the longest valid obstacle course at each position this is a hard problem so you want to build some obstacle courses you are given a zero indexed integer array obstacles of length n where obstacles index I describes the height of the ith obstacle alright so we're given a list of obstacles and their heights for every I between 0 and N minus 1 inclusive find the length of the longest obstacle course in obstacles such that number one you choose any number of obstacles between 0 and I inclusive okay so you can choose any obstacle up to that index you must include the ith obstacle in the course so it has to end with that obstacle you must put the chosen obstacles in the same order as they appear in obstacles alright and finally every obstacle except for the first is taller than or the same height as the obstacle immediately before it return an array ants of length n where ants index I is the length of the longest obstacle course for index I as described above all right so to summarize this we're given an array obstacles where each value in the array is the height of some obstacle in an obstacle course our goal is to create the longest possible obstacle course that ends at each one of these obstacles with certain rules so each of our obstacle courses has to consist of only obstacles that came before that particular obstacle and we can only have increasing or the equal height obstacles before this obstacle meaning we cannot have a decrease in obstacle size in our course all right so we'll put 25 minutes on the power timer and we will get started so this one is basically an increasing subsequence problem we have to choose a certain number of obstacles that come before our current obstacle so that will be some subsequence of these obstacles and they all have to be of increasing or equal value so there are several different ways you can approach it the problem but the key Insight really is that when you look at any particular obstacle you need to end your Optical course on that obstacle which means that you can essentially look for any obstacle course that you've built up previous to this obstacle look at their last obstacle in that course so if that last obstacle in the course is less than or equal to this obstacle in terms of its height then you can just put this obstacle at the end of that course and make that course one more obstacle in length or one length one obstacle greater in length so that being said what we really want to do is just look at any particular obstacle and then find any previously built obstacle course that ends in some obstacle that is equal to or less than the size of this obstacle and then we can just add that obstacle to the end of that course and we have a new obstacle course that's one longer than that Optical course I'm not explaining this well at all right so let's get started we will have some result let's see our result will just be an array and we'll return the result at the end okay so the approach I'm going to take with this one is looking at Obstacle Courses by length so if we look at any obstacle course and find its length and then look at the last obstacle in that course that's pretty much all the information we need in order to determine whether or not we can put this current obstacle at the end of that course and make that course one obstacle longer so we're going to start with some length of obstacles so here's my I'll call it a stack well it's not really a stack what will I call this I'll call this obstacle course final obstacle by length no that's terrible name okay I'll have some courses by length so the value will be the last obstacle in the chorus and the index actually represents the length of this course so the index here will be the length of the course and the value here will be the last obstacle in that course so the idea with this is let's say you have a course that is a hundred obstacles long if the last obstacle in that course is of height a thousand then you could put anything with height 1000 or above at the end of that course and make that course one obstacle longer all right so we have our courses by length here now all we really need to do is go through every obstacle in our course and see where it fits into this courses by length array all right so for every obstacle in our obstacle list we'll just check first do we have any courses so far if we don't have any courses then this is a one length obstacle course so if we don't have any courses yet then we'll put this obstacle as a one length course and of course we also need to update our result so our result here would just append one because at this point we can't have any courses longer than one because we don't have any courses at all so far so there's this is our very first obstacle course and it only has one obstacle in it and it's the very first obstacle in our obstacles list and at this point we can just continue all right now we have an obstacle and we have some obstacle courses we've already built so far so if we've made it this far means that we have some obstacle courses in our courses by length now we need to figure out where do we put this obstacle in this list of courses do we create a new obstacle course with length one that has this obstacle in it or can we add this obstacle to the end of an obstacle course that already exists now if we look at this value here this is the last Optical in the course so basically what we need to do is we need to look at all the last obstacle courses finding the one that will best match our current obstacle so for this case we're actually looking for something that is less than or equal to our current obstacle and since we're looking for the longest obstacle course we can we'll start at the very end of our courses by length and we'll work our way backwards to the smallest or shortest obstacle course so let's see I'll call this the insertion point where are we going to put this obstacle and we're going to start it at the end of our courses length here okay so the idea here would be if we find the longest course that we have which will be the end of this course is by length we find the longest course that we have if it ends in an obstacle that is less than shorter than or equal to this obstacle then we can put this obstacle at the end of that course and increase that course by length one so let's see I'm trying to find the insertion point so basically I'm going to say while the obstacle at the end of this course is greater than my current obstacle I can't put this obstacle at the end so let's see okay so we're going through our courses by length backwards so from the longest course to the shortest course and looking at the final obstacle in that obstacle course if that final obstacle is greater than our current obstacle we can't add our obstacle to the end of that course we need to look for a different course a shorter course with a shorter obstacle all right so at this point we need to change our insertion point so we keep looking backwards in our list of courses by length now we don't want to go outside of our bounds here so we better check that we're greater than or equal to zero so at this point we've found the insertion point for our current obstacle which one of these courses can we add our obstacle to make that obstacle course one obstacle longer now at this point we've actually gone one step too far so we need to increase our insertion point by one okay so now this is our true insertion point all right so we've gone through all of our courses from the longest to the shortest looking for some obstacle course that ends with an obstacle that is less than or equal to our current obstacle in size now when we've found that point we've actually gone one step too far sort of so we've gotten to the point where we have this insertion point we know that our obstacle is greater than or equal to this current obstacle which means that we can add one obstacle to the end of this particular obstacle course by adding that new obstacle our current obstacle to the end of this obstacle course that we just found we're actually increasing the length by one obstacle which means our insertion point is really the next obstacle course up we can actually go one step further all right so now we've found our insertion point we have a couple different edge cases we have to consider here if our insertion point is at the very beginning of our array or the very end of our array then we'll just need to append this particular obstacle to our array so let's just check here so if our insertion point is actually at the very end of our array then we just need to append this obstacle to our array and of course we need to update our result as well now how long is this obstacle course well it's going to be the length of our array here all right so this gets our first Edge case out of the way now if it's not at the end so that takes care of that edge case now if we don't have this Edge case where we're just adding an obstacle course to the end we're actually adding this obstacle to some existing Optical course so we have to basically grab our existing obstacle course at this insertion point and now we're going to add our obstacle to the end and of course we need to update our result as well now let's see what's the length of this one well it's just going to be this insertion point plus one because this is a zero indexed all right so it'll be our insertion point plus one all right this should be it let's see if this works and that works all right I'll go through this one more time because it's a little bit confusing we're going to be keeping track of all of our obstacle courses that we've seen so far by the length of the obstacle course so the index into this array will be the length of the obstacle course and the value in the array will be the last obstacle in the course so essentially the maximum obstacle in that course all right now we'll go through for every obstacle in our list of obstacles this one just starts the whole thing off if we don't yet have any optical courses then we'll create our first obstacle course by putting in the very first obstacle and we'll have our result with a one length obstacle course at index one or index 0. okay now if we do have obstacle courses we need to find the obstacle course the longest obstacle course that we can with the last obstacle that is less than or equal to our current obstacle so that we can add this obstacle to the end of that course so we'll just start at the very end of our list of courses here so that's the longest course that we have we'll go backwards until we find some obstacle that is less than or equal to our current obstacle that means the last obstacle in that course is less than or equal to our current obstacle which means that we can add this obstacle to the end now when we find that I'm calling it the insertion point but basically it's the course length of our obstacle course that we can add this obstacle to the end of once we find that we can actually go one step further and this is where I guess it gets a little bit tricky but the idea here is if we found an obstacle course that has uh how do I put this okay so the idea here is once we found an obstacle course with an obstacle that is less than or equal to our current obstacle when we add our new obstacle to the end of that course we're actually lengthening that course by one obstacle which means our insertion point is really one above our current insertion point we've found the insertion point which means we found the very first obstacle course or the longest obstacle course where the ending obstacle is less than or equal to our current obstacle but as soon as we add this new obstacle to the end of that course we're actually increasing the length of that course by one which means it's going to actually take place take the place of the next value in our array because the index needs to match the length because we're adding a new value to this course its length increases by one so we actually need to update our insertion point we need to increment it by one to take the place of the new length of this obstacle course that we're creating now if the insertion point is at the very end of our array then we just need to add that obstacle to the end of our array and of course we need to update our result if the insertion point is not at the end of the array then we need to update the value at the insertion point to our obstacle because it was previously greater than or equal to our current obstacle so essentially if we had two obstacle courses both of length 100 but one ended with an obstacle that was a thousand units high and the other ends with an obstacle that is 10 units high well we want the one with 10 units high because that gives us more options for future obstacle courses so we're essentially replacing whatever was at this insertion point which was a greater obstacle height with our current obstacle height and then of course we need to update our result okay I'm going to submit this and see how we do and we pass although we do a terrible job we only beat six percent for runtime and 19 for memory so not a very good job now I'll just point this out I'm not going to get into it but one thing we are just going through doing a linear search for this insertion point there are ways you can improve upon this linear search you could probably do a binary search hint one thing you can do I'll just break this out really quick let's create a function for getting the insertion point so instead of doing this basically I'm going to move this into a function and instead of doing this we'll just say the insertion point is equal to and we'll just call this function all right so this should be equivalent we're just calling a function to find the assertion Point instead of finding it in line and see if this makes any difference probably won't makes no difference at all still six percent for runtime it's a little bit worse in memory nine percent memory but if you were to optimize let's go back here now we've made this a little bit more modular you can keep this basic function the same you can just change this find insertion point function make it more optimal maybe make it a binary search if you change this find insertion point to be a better find insertion point function that will improve the overall performance of this entire program all right so I know this one's confusing I know I didn't explain this very well but that's the basics of this one there are different ways you can do this but this is the best way I found to do it so far all right hope you enjoyed this hope you had fun hope you learned something hope you can go out and write better code
Find the Longest Valid Obstacle Course at Each Position
find-interview-candidates
You want to build some obstacle courses. You are given a **0-indexed** integer array `obstacles` of length `n`, where `obstacles[i]` describes the height of the `ith` obstacle. For every index `i` between `0` and `n - 1` (**inclusive**), find the length of the **longest obstacle course** in `obstacles` such that: * You choose any number of obstacles between `0` and `i` **inclusive**. * You must include the `ith` obstacle in the course. * You must put the chosen obstacles in the **same order** as they appear in `obstacles`. * Every obstacle (except the first) is **taller** than or the **same height** as the obstacle immediately before it. Return _an array_ `ans` _of length_ `n`, _where_ `ans[i]` _is the length of the **longest obstacle course** for index_ `i` _as described above_. **Example 1:** **Input:** obstacles = \[1,2,3,2\] **Output:** \[1,2,3,3\] **Explanation:** The longest valid obstacle course at each position is: - i = 0: \[1\], \[1\] has length 1. - i = 1: \[1,2\], \[1,2\] has length 2. - i = 2: \[1,2,3\], \[1,2,3\] has length 3. - i = 3: \[1,2,3,2\], \[1,2,2\] has length 3. **Example 2:** **Input:** obstacles = \[2,2,1\] **Output:** \[1,2,1\] **Explanation:** The longest valid obstacle course at each position is: - i = 0: \[2\], \[2\] has length 1. - i = 1: \[2,2\], \[2,2\] has length 2. - i = 2: \[2,2,1\], \[1\] has length 1. **Example 3:** **Input:** obstacles = \[3,1,5,6,4,2\] **Output:** \[1,1,2,3,2,2\] **Explanation:** The longest valid obstacle course at each position is: - i = 0: \[3\], \[3\] has length 1. - i = 1: \[3,1\], \[1\] has length 1. - i = 2: \[3,1,5\], \[3,5\] has length 2. \[1,5\] is also valid. - i = 3: \[3,1,5,6\], \[3,5,6\] has length 3. \[1,5,6\] is also valid. - i = 4: \[3,1,5,6,4\], \[3,4\] has length 2. \[1,4\] is also valid. - i = 5: \[3,1,5,6,4,2\], \[1,2\] has length 2. **Constraints:** * `n == obstacles.length` * `1 <= n <= 105` * `1 <= obstacles[i] <= 107`
null
Database
Medium
null
438
Hello friends today I'm going to solve liquid problem number 438 find all anagrams in a string so in this problem we are given two strings S and P and we need to return an array of always start in this case where we could find the anagrams of p in s so what's an anagram it's basically a permutation of the string p in string s so that means um the characters in The String P could be rearranged in any order in the string s and that would be the anagram of string P so let's look at this example here so what do we have here the string p is ABC and the string s has these characters right so now let's find the anagram of P what would be the anagram of P so basically we have a b c and uh it would be any arrangement of these three characters so it could be b a c it could be C B A and so on right so let's see do we have any of these three characters that are together in the string as well is of course we have one character a one here and a gram here which starts at index 0 and the next one is at here at this index so that's at index six if you would count zero one two three four five and six right so that's what our answer is our answer would be an array which consists of value 0 and 6. so this is our answer so that's all we have to do so if you have done the little daily challenge of February 4 then you would know that this problem is quite a similar problem but always the difference is that we have to find the area of the starting indicious but in the liquid daily challenge on February 4 we just had to find if the permutation or the anagram exists or not so quite the same problem quite the same process just the difference is we need to for create an array so what are we going to do is we're going to use sliding window with uh two pointers so and we are also going to use a map to store um the number of uh characters uh in the string s so basically the frequency of the characters in string s so um what we're going to do is we are going to use a sliding window of length that will be equals to the length of the string P so that would be equals to 3 for now and then we start from we start the two pointers that is our left and right pointer would be at this index here and then what do we do is we check if this string if this character is in this string P then we are going to increase the um uh increase the index R the value for index R which will point at in B character B and our count will keep a count okay so you end account and we'll increase the value from 0 to 1. so this means that we have found one character for our string P that would be an anagram and now we move to the next character and found the character B which is also present in this string P so we increase the count by one which becomes equals to two and then we increase the index of R and now our R is at index a pointing to a and since a is also present in the string P so we got our count value which is equal to 3 that is equals to the length of P so now what do we do is we note that we found a permutation an anagram and then we push the Val um we push the value of L to our result so our result we have the value 0 here now what we do next is um our index L is at index 0 our index R is at index 2 right now which is pointing to character a and we increment the value of R now the value of R is equals to 3 and since the difference between these two characters is equals to 3 which means that there are four characters now in this window so what do we need to do is we need to um certain the window size that is to create only the Windows size of three so we will increase the value of index l so now L will point to index one so now I will point to index one and then we will have a window of size equals to 3 from 1 to 3 inclusive so in that way we keep on moving and if we uh find this value the count equals to 3 then we are going to push the value of L to our resulting area and we um reset the value of count every time the length of the sliding window becomes greater than 3. so now that we know how we need to solve this problem let's actually solve this problem so first of all we are going to create a map foreign so we'll create map for our character for all the characters at string P so map um okay I'm going to use not this but string literals so if map C is equals to if map C is present I will go we are going to use that value else we're going to we are using 0 and increment it by one now that we have our map what are we going to do is we're going to use a while loop while um okay before that let's define our left and right pointer and the count equals to zero and our result array okay and our while uh we will Loop until left the right pointer is less than the length of the string because we are incrementing the right pointer every time and left pointer will always be less than or equals to R so we need to check if the right pointer is less than the length of the string s right so that's what we are doing here and we are going to check if um the character in our right index add string as is present in the map that is if it's greater than zero then we are going to increment the count and every time we are going to decrease the value of the character in the map and we are going to increment the value of our right index and we are going to check if the value of count is equals to the length of the string P then we are going to push to our result the value of um the value of L in XL and also if um L minus R equals to 3 that is if the sliding window is greater than 3 then we need to reduce the size right not 3 actually it's the size of the string P then we are going to reduce the size um of the sliding window that is we need to increment the value of L we also need to reset the count so we need to reset the count um if okay if um we use that okay greater than equals to zero if the um if that character was used to change the value of count if that character change the value of count that is when we are going to reset use to reset our account all right and thank you and then we also need to increment the value of the map now that we have this thing finally we are going to return our result now let's try to run our code okay what's wrong here something okay sorry this is not left minus right minus left because left is always less than the right index all right let's submit this solution now great so let's look at the time complexity so this will take um let's assume that the length of string s is M and P is in so this would take off and time complexity and the while loop here um since we are looping over the length of the string as so that would be of M so the total time complexity is O of M plus n and the space complexity is constant because even though we are using a map the maximum length of the map can only be equals to um 26 that is the length of the English alphabets right so that would be constant
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
410
everyone welcome back and let's write some more neat code today so today let's solve the problem split array largest sum this is a hard problem now there is a solution to this problem that's kind of intuitive but it doesn't really get accepted on leak code and then there is a solution that's a lot harder so i would say this is probably borderline a crackhead problem which we haven't solved one of those in quite a while so this should be pretty interesting i'll try to do my best to explain it in a very simple way so we're given an array of nums which consist of non-negative of nums which consist of non-negative of nums which consist of non-negative integers so zero or positive integers and we're also given an integer m which is basically the number of subarrays that we want to split nums into and they have to be non-empty and contiguous have to be non-empty and contiguous have to be non-empty and contiguous which is usually how subarrays are but we want to split it in such a way that of those m sub arrays if we found the one that had the largest sum that the largest sum would be minimized that's our goal so let's understand this with an example so suppose this is the input array and we have to split it into two groups one way would be to split it like that so then one sub-array has a sum of that so then one sub-array has a sum of that so then one sub-array has a sum of eight and the other sub-array has a sum eight and the other sub-array has a sum eight and the other sub-array has a sum of 24. so what's the largest sum among these two sub-arrays of course it's 24 these two sub-arrays of course it's 24 these two sub-arrays of course it's 24 not eight so the question is were we able to minimize the largest sum is there a way that we could split this array where the largest sum would be less than 24 definitely right you can tell that just by looking at it this is the optimal place that we would have to split it the sum on the right side would be 18 i think on the left side it would be 14 so the largest sum in this case is 18 and that's about the best that we can do if we try to split it you know if we try to go over here this sum is just going to be larger than 18. so no matter where we put the you know thing it's always going to be larger than 18. so in this case we would return the largest sum which we found to be 18. now the first way to kind of tackle this problem is definitely the brute force and when i say brute force i mean kind of backtracking going through every single possibility in this case this is our input array we have m equals two we need to split it into two groups so how can we do it well we can say that this is the first group or we can say this is the first group or this is the first group we can't say that this is the first group because if we do that then we have no more values left for the second group so this is the largest that the first group could possibly be so basically for our first decision we have four different branches that we could take for each of those branches you know suppose that the first branch was if we just take seven as the first subarray then after that we'll pretty much only have one choice because in this case m equals two we have to take the remainder of the elements to be a part of the second group so in this case since m equals two it's a little bit simplified but you know that m could be three it could be four it could be a lot larger and then our tree would be very large as well so that wouldn't be very efficient but if you do code up this backtracking solution you can find out that the main parameters that you're going to be passing in to the backtracking is going to be one i the index that we're starting at as we go through the subarray as we build groups and every time we build a group we're going to take our m parameter and decrement it by one so that's the second parameter we're going to be maintaining so we're maintaining two variables so we can use these to cache them so we can cache our back tracking based on these two variables you'll also notice that inside of the function itself you're going to have a loop if you do code it up though it doesn't get accepted on leak code but you're gonna have a loop you're gonna you know let's say we're building the nth group you know this could be the nth group etcetera so that's where that while loop comes from so we can just kind of assume that a while loop is going to have a big o time complexity of n where n is the size of the input array so the number of times we're going to be calling and caching our recursive method is going to be n comes from this i because i could be at any position in this input array m is just an input parameter itself uh and then within that function itself we're also going to have a big of n while loop so the overall time complexity is going to be n squared times m we could code that up but it doesn't get accepted on leak code and just to kind of give you a glimpse this is what that solution would look like i'm not going to go in super detail and actually this does sometimes get accepted on leak code it's kind of random sometimes it does sometimes it doesn't because we added one little if statement over here which is kind of a micro optimization it doesn't change the big o time complexity but i guess it makes it efficient enough so that it can pass on leak code you could also take this memoization solution and get the true dynamic programming solution if you wanted to but there's actually an even better solution which is the crackhead solution in my opinion it's not something that you'd probably come up with by yourself okay so now let's get into the much more difficult solution let me tell you what it's going to be and then how we can code it up it's going to be a binary search solution now once i explain it to you i bet you're going to think yeah that actually does make a lot of sense but you're also going to be wondering how would i ever be able to come up with that by myself and that's a good question honestly i don't know the answer to that i hope that your interviewer would give you a hint so suppose we're given the exact same input array and just to make things a little bit more interesting let's say we have m equals three and remember we're trying to take this input array split it into m sub arrays such that the largest sum of those m sub arrays is going to be minimized the first question is what's the range of possibilities that the largest sum could even be what's the minimum it could possibly be well the minimum has to be whatever the largest individual integer is in the input array and actually i just realized i put an 18 over here instead of an 8 but that doesn't really change anything significant but remember every one of these integers has to go in some sub-array either this is going to be a sub-array either this is going to be a sub-array either this is going to be a sub-array by itself or it's going to sub-array by itself or it's going to sub-array by itself or it's going to include some other integers but still since all of these are going to be greater than or equal to 0 that means that the smallest the result could possibly be is going to be whatever the largest individual integer is that's simple enough now what is the largest that the result could possibly be well in theory it could be the sum of the entire input array but you're probably thinking well we have to split it into three subarrays right so we can't possibly have this as a solution and you're right but this is still the easiest way to do it because if we don't do it that way what would we do would we find the largest of this group and then the this group and then this group as well to make sure that we're actually splitting it into three groups we could do that but that's going to be less efficient so we're just going to take the sum of the entire input array and say that's the largest that the result could possibly be so remember the minimum that the result could possibly be is the maximum of the input array the max that the result could possibly be is the sum of the input array so if we take this as our left boundary and this as our right boundary we can try to create a binary search on this range of possible solutions so then these are going to be our left and right boundaries and at that point we're going to kind of do a standard binary search we're going to add these two together find the midway point in this case we'll just round down so we'll say that the midpoint happens to be 27 but now you're probably wondering what does this value even mean and how can we use it to actually do our binary search well first of all remember these represent the possible range of solutions the solution we're looking for is what's the largest sum among those m sub arrays so now the very simple question we need to answer with this value is can we take the input array split it into three groups such that the largest sum of those three groups happens to be less than or equal to 27. if that's the case that means we found a new minimum because initially this is the range that we're searching on so we're gonna initially assume the worst we're gonna say that the best solution we can find so far is 37 but if we find that we can take the input array split it into three groups where the maximum sum of those three groups is less than or equal to 27 that means we found a better solution so instead of saying 37 is the solution so far we're going to say 27 is the solution so far but the question is how can we take the input array and determine if we can split it into three groups where the maximum size of each group is less than or equal to 27 well that's actually the easiest part it's a very simple greedy algorithm so what we're gonna do is start at the beginning of this input array seven so okay we have a sub array so far of seven that is less than the maximum target that a sub array could be so we are good there so we'll add another value now the sum is nine we're still below the threshold then we add a five so now we're at a sum of 14 we're still under the threshold then we add a 10 now we're at 24 still below the threshold okay but then we add an 18. so at that point we're definitely over the threshold so what do we do well we say that we can't have this be a sub ray but we can have this be a sub ray this was the biggest sub array we could have created we were being greedy so now when we want to include this 18 we're going to put it in a separate subarray and we're going to continue the algorithm but we find we ran out of values but we only have two subarrays we were trying to create three so my question is this a problem that we only have two subarrays it's not a problem at all let me tell you why the goal was to create three sub-arrays where the maximum sum three sub-arrays where the maximum sum three sub-arrays where the maximum sum of those three sub-arrays was less than of those three sub-arrays was less than of those three sub-arrays was less than 27. we created two sub-arrays that 27. we created two sub-arrays that 27. we created two sub-arrays that followed that condition so it would be very easy for us to create three if we wanted to we could literally just take this one and split it so that we have three right we know that if the entire sub array is less than 27 then if we split it's definitely going to be less than 27. so in this case we found that yes we can split the input array into three sub-arrays where the maximum into three sub-arrays where the maximum into three sub-arrays where the maximum sum of those three sub-arrays is less sum of those three sub-arrays is less sum of those three sub-arrays is less than or equal to 27. so at that point we would change our binary search world first we would say our result so far now instead of being 37 is 27 and now we would update our binary search we would update the right portion because initially it was 37 but now we would set it to be 27 minus 1 26 because we already know that 27 is a valid value so there's no need to search it anymore we're going to go one below that and then this would be our new binary search range and we would basically just continue that binary search until we found the smallest result possible so that's pretty much the algorithm coding it up is not too difficult i think coming up with it is definitely the hardest part by the way the time complexity since our range that we're going to be searching over in the worst case the size of the range could basically be what the sum is suppose if the max number was you know let's say 1 then the range would be defined by whatever the sum of the input array is so the time complexity is going to be log of s where s is the sum of the input array but also remember we have that algorithm where we have to check can we split it into three groups you know below this so that is going to be an o of n time algorithm so n times this i think what makes this hard compared to other binary search problems is usually with binary search you're just doing a single comparison but in this case we have a linear time method that's being used alongside the binary search but with all that said let's code it up now okay so now let's code it up remember we're gonna have two boundaries left is going to be the maximum of nums that's basically the smallest result that we could possibly return the maximum result we could possibly return is the sum of the entire input array nums and initially we're going to set our result equal to be the larger of the two because we want to just initially assume the worst we could also set this to be float of infinity but this is the largest that the result could possibly be so this is a little bit better i guess and then it's mainly going to be a standard binary search while left is less than or equal to right we're going to compute the mid i'm not calling this m because remember we have a separate variable m but usually what we do uh to compute the middle is left divided by right left plus right divided by two but sometimes this can lead to overflow it definitely can't in python but in other languages it can so the slightly better way to write this where it won't ever lead to overflow is write minus left and then take left and add that to it so this is doing the exact same thing it's just doing it so that it can't overflow this is still computing the midway point between left and right but then we want to know this mid using this mid can we split nums into m groups where the largest sum of those groups is less than or equal to mid so i'm going to create a helper function to kind of help us do that i'm going to call it can split and we're going to pass in mid as the largest that it can possibly be if we can split it what do we know well that means we've found a smaller result so our result can be set to mid and we're going to update our binary search range to look for smaller values now we're going to set right equal to mid minus 1. in the else case that means we could not use this as a result so we're not going to update our result but we are gonna take our left pointer and set it to be mid plus one so now to actually implement the can split method uh the parameter is going to be whatever the largest number happens to be and the question we're asking is can we split nums into m groups where the max size of those m groups is less than or equal to largest well first we're going to basically count the number of sub-arrays basically count the number of sub-arrays basically count the number of sub-arrays that we can create and we're also going to maintain what the current sum is initially we're going to set it to be 0. remember this is a greedy algorithm it's very simple we're starting at the beginning going through every single value adding to the current sum and if we ever get to the point where current sum exceeds the largest that it can possibly be allowed to be then we're going to say that okay this is going to go in its own group we can identify that by taking our subarray count adding one to it and then updating our current sum uh not to be zero but to actually be n itself because we know after adding n to the current sum that's when it exceeded the largest so what we're saying is we don't want to add n to the current sum we want n to start in a separate subarray so that's why current sum is initially being set to n and then after this loop is done the question we're going to ask is the number of sub-arrays less than or the number of sub-arrays less than or the number of sub-arrays less than or equal to m but we can't just make this comparison because notice how we're only adding one to the sub-array after we adding one to the sub-array after we adding one to the sub-array after we have to create a second subarray so actually the total number of sub-arrays actually the total number of sub-arrays actually the total number of sub-arrays is going to be sub-array is going to be sub-array is going to be sub-array plus one or you could initially set subarray equal to one but i feel like that's a little bit less readable if this blind doesn't make sense it's actually simpler than it might seem i would just recommend running through an example on like pen and paper so basically if this is true that means we can split if it's not true that means we would have exceeded the largest threshold okay and by the way i forgot that in python if you're doing nested functions we should probably define that function before we actually call it down below but other than that there's not really any changes necessary this is the entire code let's run it to make sure that it works and as you can see on the left yes it does and it's very efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Split Array Largest Sum
split-array-largest-sum
Given an integer array `nums` and an integer `k`, split `nums` into `k` non-empty subarrays such that the largest sum of any subarray is **minimized**. Return _the minimized largest sum of the split_. A **subarray** is a contiguous part of the array. **Example 1:** **Input:** nums = \[7,2,5,10,8\], k = 2 **Output:** 18 **Explanation:** There are four ways to split nums into two subarrays. The best way is to split it into \[7,2,5\] and \[10,8\], where the largest sum among the two subarrays is only 18. **Example 2:** **Input:** nums = \[1,2,3,4,5\], k = 2 **Output:** 9 **Explanation:** There are four ways to split nums into two subarrays. The best way is to split it into \[1,2,3\] and \[4,5\], where the largest sum among the two subarrays is only 9. **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] <= 106` * `1 <= k <= min(50, nums.length)`
null
Array,Binary Search,Dynamic Programming,Greedy
Hard
1056,1192,2242,2330
795
welcome to june's lego challenge today's problem is number of sub arrays with bounded maximum you are given an array numbers of positive integers and two positive integers left and right left is less or equal to right return the number of contiguous non-empty subarrays such that the value non-empty subarrays such that the value non-empty subarrays such that the value of the maximum array element in that subarray is at least left and at most right the length of nums will be in the range of one to fifty thousand and the numbers themselves will be zero to uh whatever ten to the ninth power now given this constraint here the length of nums at first it sounds like we can do a n squared solution by doing a nested for loop and checking every single contiguous sub array keeping track of which ones like which value is the maximum if the maximum is in range of left and right then we can update our output but we can kind of intuit here that there's probably a greedy approach keeping track of some sort of information as we go along say that we want to solve this problem here two one four three what are our possible three sub arrays well you can see right here it's either gonna be two itself it's gonna be two and one or it's gonna be three notice how when we hit a number that's out of range or specifically greater than right it almost wipes out everything that comes with before and we kind of start over it's almost like this is its own separate sub like array so surely there's some uh greedy approach that we can take here so say that we i just said this example what information do we need to keep track of as we move along well there's three possibilities for our numbers right it's either going to be less than left it's going to be you know in range of left like whatever or it's going to be greater than right and if it's greater than right we kind of know wipe out everything wipe out all and so here but if it's left less than left what do we do it kind of depends say that it's all ones at this point and we have a left of two and a right of threes like that like all these ones don't matter but that's only because there's no numbers that are in range or the maximum number is not in range that comes before it so we almost like need to keep track of that somewhere like if we find if it's less than left but we know that at some point before we found some numbers that are in range to say that we had a 2 here we need to add uh we need to add however many numbers we've seen so far that have been in range so if it had like two to two like this like uh once we run one here we know we can do this right so why don't we keep track of how many numbers that we've seen so far that are in range whenever we see a number that is outside of the bounds or it's greater than the right then we'll just wipe it out because none of that matters anymore hopefully that kind of makes sense so if we find like the in range and maybe we'll use a stack or something then we'll add whatever amount is inside of our stack we can't add the number itself here but we can add as long as we include this number we can add that so one thing yeah so basically um as we move forward like let's just say it's all ones at this point we can add one right and the reason for that actually if you think about it is uh say that we had like two here how many numbers can we have well if two was here we can add this we can add everything so obviously we realize here that index number actually needs to be taken care of we have to keep track of the last index point that we've seen a number in bounds and that way we could subtract whatever numbers that come in between so say this wasn't in here then we'll subtract two like if we're on one here we're going to subtract two because these don't count but we could add two here and we can add whatever comes before that all right now if it's inbounds um we could definitely add itself right we can add itself and pretty much we can add everything that came before so okay here's what we're going to do we're going to keep track of two things we're going to have a stack of the numbers that are less than left and we're going to have a stack of the numbers uh that are inbounds and we're also going to keep track of um the last index point that we've seen a number that's in bounds so we'll have two stacks one for in uh one for low range and one for inbounds we'll also have to keep track of the last index point that we've seen in balance now if we find that the number is greater than right it's out it's yeah the max is out of bounds it's greater than right then we have to just wipe out everything okay so that much is simple so let's start by actually just coding this out and we'll just build it up as we go we're gonna have a stack and we don't actually need to have a stack itself we just need to keep track of how many numbers uh that were in low range and how many numbers are in range so i'll call this i don't know l stack for low range and i stack for inbounds we'll also keep track of our output which is going to be zero as well as the last index point that we've seen a number inbounds so i'll call that last i will start with like negative one okay so for i n in enumerate nums there's three possibilities now if i is less than left else if i is or i should say left less or equal to i less equal to right i'm sorry it shouldn't be i should be n and else the only possibility is n is greater than right that means we're going to wipe out our stacks we're going to say l stack equal zero and i stack inbound stack equals zero and we're not going to add anything to our output obviously okay so if the number is less than our left what do we remember we have to remember that uh it totally depends on whether we've seen a number inbound so far so if it's less than left and if we find that our not our stack if inbound stack is greater than zero that means we've seen a number in bounds before so let's add to our output then whatever our i stack is plus whatever our l stack is remember this keeps track of how many small numbers we've seen now recall that i gave you that example if we see like a 1 at this point and say that we have like 2 that's it kind of depends on um like any if these were all ones it doesn't actually really matter like none of this matters we can still add all these numbers right that comes before but if this was a one we can't add that right so basically we'll just add everything and then we'll subtract from the last index point this part right here so to do that all i have to do is say okay output minus equal this index point wherever we're at subtracted by the last index point that we've seen in inbounds and we'll subtract one now that would be it all we have to do now is that l stack we'll add one here because this number counts as a low number stack okay so if it's inbounds that's fairly easy all we have to do is add to our output the i stack plus l stack plus itself and we'll increase our inbound stack by one finally return the outputs oh and one thing to note is each time we do this we have to keep track of the last index which would equal i because that's the last time we've seen this in balance all right so uh hopefully that made decent sense let's see if this works and it's hard to know if it works until we submit it so let's see and there we go that's accepted time complexity is going to be o of n and constant space because these are all just integers now i looked at some of the solutions and found that this was actually pretty different from how other people did it lots of other people tried to keep track of the left and right index points kind of like a two pointer or they kept track of the midpoint which was a little more mathematical tonight um i would have expected this i feel like is more understandable it's not as clean but it's the one that i came up with so i'm just gonna explain this one uh i don't know if it's good or the best or whatever but i do know it's of n and o one constant space so uh even though it's not the most clever and clean clever solution like i think it's good enough all right thanks for watching my channel remember do not trust me i know nothing
Number of Subarrays with Bounded Maximum
k-th-symbol-in-grammar
Given an integer array `nums` and two integers `left` and `right`, return _the number of contiguous non-empty **subarrays** such that the value of the maximum array element in that subarray is in the range_ `[left, right]`. The test cases are generated so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[2,1,4,3\], left = 2, right = 3 **Output:** 3 **Explanation:** There are three subarrays that meet the requirements: \[2\], \[2, 1\], \[3\]. **Example 2:** **Input:** nums = \[2,9,2,5,6\], left = 2, right = 8 **Output:** 7 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `0 <= left <= right <= 109`
Try to represent the current (N, K) in terms of some (N-1, prevK). What is prevK ?
Math,Bit Manipulation,Recursion
Medium
null
451
hello guys welcome to the chord man produce problem is sort characters by frequency so we have a given input string we have to short it based on the occurrence or frequency of the each character so let's say if a given string 3 the output should be ERT let's understand with the example so we have T only having occurrences 1 are also having only frequency as a 1 and for character e we have 2 times the occurrence so based on the frequency of the each character so II will get first precedence and then R and T so if the frequency is the same for the character order does not matter so if II appears twice and R and T appears once so based on that we need to give the output to solve this problem there are two things we need to take care one is we need to find out a frequency of each character and second thing is like based on that frequency we need to sort the characters so to form and to map the frequency with the character we can use a hash map where your key could be our character and frequency could be your number of occurrence of that character in this string and to short the based on the frequency we can use a priority queue and sorting will be like based on your the frequency of those characters so let's start with the code editor we first create a map in priority queue so map will be our character as key and integer as your value okay now let's define the priority queue okay we'll give a comparator in a constructor to short based on their frequency so here that's to input an x and y and we'll short based on the matter of can't sorry Y minus my x okay so you define the mapping power to you now let's feel over me let's go to the iteration to the string comma is to carry and my C comma let's check first whether we do have when you present in the map or not so map don't get all default if it is present then it will return the value otherwise it will return a 0 okay and then plus +1 to that then plus +1 to that then plus +1 to that okay so we have fill our map now let's add this value to the priority queue from the map so now let's go to the priority queue it right over the has said iterate over the key set and then let's offer those characters to the priority queue so let's go to the 4 character C comma map dot he's sorry he say okay now let's offer those to the priority queue so while offering it will again also short because of the comparator we have given in the constructor so we have our priority queue reading and the sequence will be maintained as per their frequency now let's create a result from that will iterate over the priority queue until it gets unti and we will create a new stream and we will return that string so now let's first create a new string builder okay now let's iterate over the priority queue okay so until it gets empty we will iterate it so let's first take the character PQ Pole okay now we will iterate over those many frequency which is there in the map to generate those many times that character in the result so let's do that now okay for time T zero is equal to zero I less then map don't get the count of that frequency so to get the count and then I plus okay now we will I will append this character to the one string builder so let's say we have SV sorry dot append to the string later ch okay so after that we will return the string builder when you ESPE dot so this is the solution let's sit on it oops there is a typo we took ch instead of C's let's correct it okay now let's run it okay got accepted so we have given an input string as a tree the output is the ERT which is expected let's submit the solution okay it got submitted so that's it for this video hope you liked it please do subscribe for more videos thank you guys
Sort Characters By Frequency
sort-characters-by-frequency
Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string. Return _the sorted string_. If there are multiple answers, return _any of them_. **Example 1:** **Input:** s = "tree " **Output:** "eert " **Explanation:** 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr " is also a valid answer. **Example 2:** **Input:** s = "cccaaa " **Output:** "aaaccc " **Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa " and "aaaccc " are valid answers. Note that "cacaca " is incorrect, as the same characters must be together. **Example 3:** **Input:** s = "Aabb " **Output:** "bbAa " **Explanation:** "bbaA " is also a valid answer, but "Aabb " is incorrect. Note that 'A' and 'a' are treated as two different characters. **Constraints:** * `1 <= s.length <= 5 * 105` * `s` consists of uppercase and lowercase English letters and digits.
null
Hash Table,String,Sorting,Heap (Priority Queue),Bucket Sort,Counting
Medium
347,387,1741
36
hi everybody how's it going so today we're going to solve leak code 36 valued sudoku now this is a very famous uh interview question it's also a medium question and it's a fun one so this question gives you a 2d board a sudoku board a 9x9 grid containing 81 cells and you should determine whether that sudoku board is valid according to some rules so if you don't know the sudoku game it's really easy to learn i would advise you look it up real quick or i'm just going to quickly read the three rules that we're going to follow in order to determine whether a sudoku board is valid so a circuit board contains rows and columns and each row must contain the digits one two nine without repetition uh each column must also contain the digits one two nine without repetition and in the overall grid we also have sub grids we're going to call them sub boxes we have nine sub boxes you can see them here this one is a sub box two three four five six seven eight nine and these ones should also contain the digits one through nine without repetition so for example we do have a five here in this particular row there should only be one five in this particular column there should only be one five and in this subgrid there should only be one five now let's make this example a little bit bigger so we can visualize it a lot better all right so we have the following sudoku board now what we're gonna do is we're gonna determine whether or not this board is valid so for us to determine whether or not this board is valid we have to follow three rules first rule is a number should occur only once in the row that it's part of so for example we do have 5 here i'm going to circle it 5 should occur only once in this row it should not be repeated and also the second rule is a number should occur only once in the column that it's part of so five should occur only once in this column that it's part of and also a number should occur only once that's the final rule it should occur only once in the subgrid that it's part of the subgrid is this one this is a subgrid and we have nine of those we have one two three four five six seven eight and nine so five should occur only once in this subgrid in this case 5 is a valid placement because it occurs only once in this row in this column and in the subgrid so we're going to do that check for every single number in the sudoku board back to the question a few things to note however is that we're going to have empty cells we're going to have boards that are partially filled and those could be valid if they have numbers that appear only once in like rows columns and sub grids so the board doesn't have to necessarily be completely filled and only the field cells need to be validated according to the mentioned rules so empty cells would be represented with a period like this and yeah there it is so how do we solve this question well this is a pretty standard iterative question what we're going to do is we're going to iterate through the entire board and whenever we get to a particular number we're going to check if that number occurs more than once in the row that it's part of in the column that it's part of and then the subgrid that it's part of and we're going to do this in a very smart way what we'll do is we're going to initialize an array of hash maps representing every single row every single column and probably every single subgrid i'm saying probably now because we're going to get there later we're going to have a hash map that represents the first row and in this hash map we're going to map numbers to how many times they occur in this row so while we're iterating through this row if we come across 5 again say here then we'll know that we've seen 5 twice and then we can just return false also when we're iterating through this column if we come across five somewhere in this column we know that five occurs more than once then we can uh return false so that's it and we're going to do the same thing again for the sub grid as always it's going to be really simpler to explain as we go through the code so bear with me as we go through the code so what's the time and space complexity of this algorithm well for time complexity we're going through every single row and every single column so that would arguably be o of row times column but we already know there are most nine rows and nine columns so that's a total of 81 cells that we're going to go through and in big o notation which are constants so time complexity is technically of one and then for space complexity also we're storing an array of hash maps that are going to have a finite amount of values in them because the hashmap for row one can only take at most nine elements and all of those can only take at most nine elements each column can only take at least nine elements each subgrid can only take at most nine elements so we already know that there's a finite amount of values that can be stored in the hash maps so those things are constant and in big o notation we drop constants so space complexity is o of one so that's it for this question let's dive into the code alrighty so the first thing we want to do is create an array of hash maps representing every single row and every single column so oh my god map we're going to map integers to integers and that's going to map a particular number and how many times it occurs so this is going to be an array let's call it rows those equal to new um hashmap and we're going to have nine of these because we have nine rows and then we make another one manager to integer commons new hash map and then we're also going to have nine of these and then we make another one for the boxes the sub grids so now that we have that let's initialize every single hash map for each row and each column with like an initial empty value so let's say four and i is equal to zero i is less than nine zero i plus and then we say for rows of i that's for rows of zero through nine this is equal to new hash map and then this should be integer and then we do the same thing for columns and boxes okay i feel like i should add some comments so i'm just going to say initialize is that how you spell it initialize one hash map for each row and column and box sub grid so under the hood this is what's happening we're creating an array of hash maps kind of like this so if you visualize it so we have like an array containing hash maps with key value pairs so for row zero that's for the first row we're going to have key value pairs say for the integer five how many times it occurs for the integer six how many times it occurs and then say for like for example row second row that's row of index one same thing row of index two third row same thing so this is what's happening under the hood now let us iterate through the entire board and then check how many times each number occurs so we say for integer i is equal to zero i is less than board dot length so i represents the rows uh i plus and then we do for integer j that's equal to zero z is equal to zero j is less than board of i dot length uh then we can just say j plus also we can straight up just say nine because we know we're given a nine by nine grid but i'll kind of like it this way and then let's get the current character that we're looking at so let's get character let's call it current that would be equal to board of this row and this column so now that we have the current character we need to make sure that it's not empty and empty characters are represented by period so if something is not a period then we know it's not an empty character it's actually a number so if current is not equal to period then it's a number so we can convert it to like an integer that would be integer of current cool all right so now we can update how many times we've seen this number in this row and column so how do we do that we can just say rows of i have rows referring to this map here i referring to the particular referring to this array i referring to the particular index of the hashmap that we're looking at and then we're going to put what are we putting we're putting this number and then what's going to be the value is going to be whatever is in there if we already have something in there so map that get or default i hope that's how you spell it we're going to get the number if it's not there we just return 0 if it's there we add 1 to it so that's it and we're also going to do the same thing for the columns so copy it and this is going to be columns of j it's not going to be i because i represents the rows it's going to be concept j to put um it's going to be columns of j again uh that's pretty much it cool so now that we've taken care of these two cases i'm going to get to the third case in a bit it's going to be easier if i do it last so now that we have this what we can do is we can check how many times we've seen this number in this row and in this column what we've done here is we've just updated the number of times it occurs we haven't really checked whether it's duplicated so uh checking whether this number is duplicated so we can say if rows of i that get num if this is greater than one at the number of times it occurs if it's greater than one then we know it's duplicated or if columns of j that get num that's a particular number if it's also greater than one then we know that it's duplicated if this is ever the case what we do is we just return false and what we've done so far is effectively going to check whether um this particular number is duplicated in the row and in the column that it's part of now how do we check the subgrid um there are two ways to do this oh i'm sorry there are a ton of ways to do this i've only tried two of them and one is faster than the other so i'm going to do the faster one for first and surprisingly the one that's faster actually has more lines of code than the one that's slower so for the faster one what happens is we're going to calculate like where this grid starts what's the start index of this grid what's the start row and what's the stored column and then we're gonna iterate through that grid because we know that grid is a three by three grid it has three rows and three columns so we're going to iterate through that grid because we already know where it starts and then we're going to check whether we've seen this number in there so i'm going to say this code is theoretically faster so let's say ant let's call it grid start also sub grid start so how do we determine the start of the subgrid well it's a simple formula we just do row divided by three that's going to offset the row and then we multiply it by three and then we do the same thing for the sub grid start so this should be subgrid row start and this should be the sub grade column start and that you guessed it j over three times three now what's happening let's go back to the example okay stay with me now so imagine we're iterating through the board and we're currently at the cell and this cell has a value of eight and the cell is at row two column two but the sub grid that this cell belongs to starts at row zero column zero that's where the sub grid starts so we wanna get sorry this should be zero row zero column zero so we wanna get the start index of the sub grid we wanna get where the row starts and where the column starts of this particular sub grid because we want to iterate through the subgrid to see if we have eight so the current formula that we have to calculate where the row of the current sub grid starts and the column starts is let's say start row i'm just going to say sr is equal to current row it's row over 3 times 3. so how does this give us the start rows index of the start row of the subgrid so the current row that we're at is 2 that's for the cell of value 8 divided by 3 that's an integer division what's this going to give you it's going to give you 0 times 3 what's this going to give you this is going to give you 0. and then we already got 0 sorry this should be 0. we already got 0 for the start row and now we do the same thing for the start column what's the current column that we're at column two it's the same calculation two over three times three zero times three gives us zero so in the end we're gonna get 0 representing the start index of this grid that we're at the start cell of this grid that we're at now it works for all the other grids on the board i'm not going to do the calculation for all of them please try it out if you want to make sure so let's dive right back into the code all right so what we're going to do now is we're going to iterate through this entire subgrid so we're going to say ant i'm just going to do l for row and m for column so it's equal to zero um l is less than three because sub grids are three by three l plus and then we do another one for columns we call it m is equal to zero m is less than three and plus now we're going to have a very lengthy condition that checks whether we've seen this particular number in the subgrid while iterating through the subgrid but we have to make sure that the cell we're currently iterating through in the subgrid is not the same cell as i and j because what happens is while we're iterating through the subgrid there's a very high chance that we're going to come across this cell i and j and we want to skip it because we've already checked it right it's the same thing we're looking for something repetitive we're not looking for the same thing so we're going to say if i is not equal to subgrid row start plus l that's the current row that we're iterating through in the subgrid and we do the same thing for the column j is not equal to our sub grid column start plus m and the board at this cell in the subgrid if it's equal to this number if it's equal to the board at this number then we know that this value is duplicated so we can say board at subgrid i'm just going to copy this at this row in this column sub grid column start plus m if it's equal to board of i and j then we know that this particular number is duplicated so we say we've seen this character and then we can just return false that's it that's how you solve this question so if we've gone through all of this and we did not find a number that's duplicated on the rows the columns and the sub grids then we can just return true to figure out where this ends and just return sure now let's run this make sure everything works cool it's accepted i'm going to submit this and then let's see how fast it is all right so it's faster than 36 percent of the submissions and it ran in five milliseconds now let's do the second way which is a little bit slower but it has fewer lines of code so i'm going to comment this out all of this here i'm just going to comment it out and the second way to do this is to enumerate every single box so every single subgrid we can enumerate it with this um formula so let's say int box index that is it's very similar to the previous one so row divided by three times three now we're gonna add column divided by three let's see how this works okay this is all going to be over series i promise you just a few more minutes and you'll be done with this so if we're enumerating every single subgrid this is going to be sub grid 0 subgrid 1 subgrid 2 all the way to the nine sub grids that we have this is going to be sub grid 8 right 7 6 3 4 5 etc now we want to enumerate this subgrid we want every single cell in this subgrid to be enumerated to zero so cell has information of rows and columns and this is the formula that we're using now let's apply this formula let's say we were at 8 and we want to get we want to know that we were at subgrid 0. so what we do is what's the current row that 8 belongs to current row is 2 so 2 over 3 times 3 plus what's the current column that it belongs to column 2 over 3. so what's going to happen is 2 over 3 integer division returns 0 times 3 returns zero plus two over three zero so this returns zero so now every single cell in the subgrid when we apply this formula to it returns zero so now we know that every single cell in the subgrid belongs to subgrid zero the same applies for all the other sub grids as well so that's it if you want try it out which i really do advise you do try it out for a few other sub grants and cells and see how it works so back to the question now we do the same thing we update how many times we've seen this number in the subgrid so i'm going to say well i'm just going to say box because i've been using sub grids and boxes interchangeably so please know that i mean the same thing when i say sub grids and boxes so boxes that's the hashmap that we created you'll notice that we haven't used it since so box index of this particular subgrid we're going to put this number and boxes of box index dot get or default and then in this if condition we can just add an extra condition and say if boxes of box index dot get num is greater than one then we know that it occurs more than once in the subgrid and then we can just return false i've come into this code out so it's not this one here is not going to be run and let's try this all right cool accepted let's submit this and see how fast it is oh it's the same they both ran at five milliseconds let's submit it again and see what happens three milliseconds cool let's run this again i'll submit it all right this is exactly what i was looking for so for some reason the one with the hashmap that supposedly has the constant lookup feature when looking through the subgrid boxes it's a lot slower than the one with just the loop that looks through the subgrid feature so this is something that i noticed yesterday while solving this question as you can see and i just want to do it i just wanted to point this out in this question so yeah if you're doing this in an interview you may not have to do all of this i promise you if you just do this one even though it's slower as long as you can explain how you'd optimize it by doing this that's totally fine again i think there are many more ways that you can validate a sudoku board this is just my way and yeah so if you like this type of content please consider subscribing to the channel comment down below if you have something to say share this video around the youtube community and smash the like button for the youtube algorithm and i'll see you in the next one bye you
Valid Sudoku
valid-sudoku
Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**: 1. Each row must contain the digits `1-9` without repetition. 2. Each column must contain the digits `1-9` without repetition. 3. Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition. **Note:** * A Sudoku board (partially filled) could be valid but is not necessarily solvable. * Only the filled cells need to be validated according to the mentioned rules. **Example 1:** **Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\] ,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\] ,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\] ,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\] ,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\] ,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\] ,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\] ,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\] ,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** true **Example 2:** **Input:** board = \[\[ "8 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\] ,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\] ,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\] ,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\] ,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\] ,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\] ,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\] ,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\] ,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** false **Explanation:** Same as Example 1, except with the **5** in the top left corner being modified to **8**. Since there are two 8's in the top left 3x3 sub-box, it is invalid. **Constraints:** * `board.length == 9` * `board[i].length == 9` * `board[i][j]` is a digit `1-9` or `'.'`.
null
Array,Hash Table,Matrix
Medium
37,2254
234
hi in this video I'm going to talk about Le 234 pandrum Ling list so what's a pandrum there's a definition here so a palindrome is a sequence that reads the same forward and backward for example for this one if you read it Forward you'll be two one right and if you read it backward it will also be one two one so this is a pum for this example if you read it Forward you'll be one two and if you read it backward you'll be 2 one so this is not a p androme in order to do this question you can basically have two pointers the first pointing to the first element and then the second pointing to the last element here and for the first iteration can check if they are the same so if they are the same can continue and check um move the left pointer here and then the right pointer here so if you checked it and if they also the same can continue move however if there's like two elements that are not the same can just return false however since this question is a link list and it's not in an array format so we can't directly access the elements like the last elements and we don't know how long the link list is so the approach for this one will be we have to add all the notes inside the link list so the value to a m Ray so basically converting a link list to an array after we convert it to an array we can find um perform the checking here so for example if this is the link list so this is the link list right and you will have one pointer at first have to convert it to an array so here the first one the value is one so just add it to an array to add to array and one so on so that's basically the approach of it and now we'll be moving to codes so at first have to create a pointer to look through the link list and put all the values inside the array right so we create a curve know you put be pointing to head and then we'll create an array so while curent is still pointing to a note you will add the value of the current note to the array and then you will move the current and after this we already have um L this converted to an array now we just have to create a left Po and the right point so zero and L result minus one well left is less than right mean they have to keep checking if result or left that's not equals to here so it means that it's not palr here we can just return false however if they're the same we can move left one and bright pointer in the end if this Loop breaks means that um all of the it means that this is a pelum right so we can just return true and when you run this it's accepted and that's it for this video thank you
Palindrome Linked List
palindrome-linked-list
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_. **Example 1:** **Input:** head = \[1,2,2,1\] **Output:** true **Example 2:** **Input:** head = \[1,2\] **Output:** false **Constraints:** * The number of nodes in the list is in the range `[1, 105]`. * `0 <= Node.val <= 9` **Follow up:** Could you do it in `O(n)` time and `O(1)` space?
null
Linked List,Two Pointers,Stack,Recursion
Easy
9,125,206,2236
1,822
hey guys myself Ankita so we shall send the problem so it's a very simple problem of what is daily challenge there is a function sine function of X that returns 1 if x is positive minus 1 is an X is negative and 0 of X is equal to zero so given a array we have to find the product of all the elements in Array and then we have to return minus 1 or 0 depending on whether the value product is positive negative or Z so if they are given an array called like something minus one two three and minus 4 will have a variable called Product that let that be initialize to first element in that will not initialize to zero we want to initialize to zero we will initialize to first element another y because uh when we run the follow we do product equal to product star and then product into numbers of I whatever I to Value right if we initialize it to zero then every bar will be zero itself that's why you initialize with the first element then run the follow from the second element so if you find the product so once if I in here it will be o minus 2 into 3 minus six minutes it will be 24. and next then you give the if connection if product whatever view you have got that is greater than zero then greater than one less than zero return minus 1 is greater zero one more thing which we need to look into this product can be very large value because you have finding the multiplication of elements of that and then that other elements would be large or it will be very long of length so that's why uh we will give the type as double not even log Mutual double I tried it long that didn't work few test cases didn't pass so we have to give the level so double rod I'll give him initially lit will check this so print product equal to sums of zero next four and I equal to 1 I lesser than product dot length and I plus product equals to product star in terms of I so once all uh sum is found now like if product is greater than 0 then return one else if product is less than zero then written minus 1 else Delta zero that this product is equal to zero so order I'll I enter equal to 1 I lesser than which will be num slot length sorry I will submit this and check whether all the disk is a passing no this is because we have given the value as in there let me give you long and check once still it's not taking it so will you double yes successfully submitted if you haven't else please drop it in the comment section you'll come up in another video in the next section and please subscribe to the channel and keep learning thank you
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
862
hey welcome back we just finished to talk about 239 sliding window maximum and we're going to continue our journey to lead code we're going to talk about the very similar problem with the 239 shortest sub array with the sub that is k and let's go ahead and read the question so we're going to return the length of the shortest non-empty the shortest non-empty the shortest non-empty uh contiguous sub array of a with the sum that is k and if there's an uh if there's no non-empty sub-arrow with the non-empty sub-arrow with the non-empty sub-arrow with the sum at least k and we're going to return negative one and i think the example is pretty short and let's find a slightly longer example so and we're just gonna fabricate some numbers right here so for example we have a whole bunch of numbers right here and we are trying to find a sum of the sub array and to make sure the summation of the sub array is greater than greater or equal to k and we want to have the shortest length of the short sub array so how should we do that and the tricky part of this problem is that uh we have some negative elements so let's assume that if all the elements within this sub array or within this array is all positive and to do that it's pretty straightforward so we're going to have a two leg two pointer and basically we just move forward and once we have uh the summation within this range is greater or equal to k and we can start like moving uh the left pointer and then once we move that and then uh once we have the summation is less than k again and then we start moving the right pointer and keep going forward by using o n square o n uh time complexity to solve the problem so that's the case is that when we only have the positive elements were positive or zero uh in elements within this array but now the case is that we have negative elements within this array so we cannot use that um so how do we do that i mean uh to think about this problem in the brute force way so we can use all the combinations between uh i and j we still have the two pointers and inj can be all the combinations between this array and we can just calculate the summation and then we just make sure the customization is graded or equal to k and then we just calculate the length of this that's doable and that's going to be n to the cube and there's one optimization we can make on top of the brush force is by using the presump so we can do the prefix summation and so we can easily use all one complexity to calculate the summation between each individual range and then we can also calculate that so that's going to bring down the complexity to n square and this is not going to pass because we have a really huge range right here so uh 10 to the uh what is that five times ten to the fourth power and square is going to be almost into uh 10 to the ninth power uh not gonna pass and how do we do that so uh how do we bring down the complexity and one way to bring down the complexity is by using steel heap or multiset or tree set to do that i mean so first we do the prefix summation so we do the prefix summation and let's assume that capitalize the x is gonna represent those numbers with uh the prefix summation and then and we fix one element so the right pointer j and each time within the of the sorted data structure for example tree side or multiset and we're gonna find a index that fits the needs and we can find the x that the between the comp and then to make sure that you know uh we want to find uh a index to form the summation of this range is greater or equal to k and then so we can calculate that as well so that's one solution and but that's not the optimal solution so the optimized solution we're going to talk about right here is going to be similar to problem 239 which we just discussed a few minutes ago um all right so the way we deal with the 239 is sliding window maximum and now we convert the entire array into something uh called prefix summation and based on the prefix summation and we can uh translate this problem to 239 uh how do we do that um the way we do that is so we want to maintain a dq as well and the dq is increasing order so why do we do the in increasing order so i'm just going to explain but before we dive into like we popping um from the right hand side let's go ahead and talk about the similar approach with the 239 which is popping from the left hand side and remember if you remember the 2 30 knight and we just talked about it a few minutes ago and basically if the new elements is adding from the right hand side when gonna pop the elements from the left hand side and very similar approach from this problem is that once we have the new elements it's being added into our sliding window right so for example we have three and now we're gonna incorporate the next elements and once we have the new elements it's been incorporated and add here on the left hand side we always want to popping out from the left hand side so just like the two pointer solutions right so if we have the three elements it already fits the needs and the summation of the three elements is already um greater than k and we actually want to start popping out from the left hand side because uh we want to find the minimized uh when i mean master length and we know that if we are adding one more elements in it and that's gonna make um the sub array longer so we don't want to make the sub array longer we're going to make it uh smaller so that's why we start popping uh out from the left hand side once we fix the knees that the summation of the subarray is greater or equal to k and we start popping the left hand side and so if the three elements from here with the new elements being added from the right hand side is still greater than okay and then we don't need this guy as well and we're checking these two elements if this atom is still greater than okay and we just keep going and but you got the idea basically we need a while loop to checking that um so that's from the left hand side and how do we do that from the right hand side the way we do it from the right hand side is we want to keep the q increase in the increasing order so why do we want to keep that the queue in the increasing order um so pretty much we know that this is the preset prism prefix uh it can pronounce uh the word right now uh prefix summation uh array so basically for example we have two three one four negative one and five and the prefix submission is going to be 2 5 and 6 and 10 and that next one is going to be 9 and 14 and um so pretty much like all of this is going to be increasing but once we see this guy we know this is a decreasing order so this decreasing order we're going to kick this guy out and just like the 239 so once we see the smaller number we're going to kick this guy out but why do we want to kick this guy out is because um 10 all the way to here so the reason we do that is because uh we have nine here and for example we have 10 here we know this is decreasing so it doesn't make sense that for example we start calculating from the right hand side right here and then like on the left hand side so you see a number that is greater than the u and you know that uh the summation from here is wasted so this guy is greater than this guy and then this is negative one and so it doesn't mean anything because we know that k is going to be positive number so that's why we're just going to remove this guy we're not even going to consider that guy uh and then we're just going to use this as the right hand side and once we subtract here for example when i subtract 4 5 it's going to be positive numbers so we don't waste our time to calculate uh a negative number in this range uh that's pretty much like uh the cases so we either pop from the left hand side or we also pop from the right hand side um so when we pop from the left hand side so basically we are uh shrinking the range of the length um so you know what let me i'm just gonna write the code and so let's understand that uh while we write the code uh so basically we still need adq and just like the last problem and uh in this case we are gonna store two things one is this uh prefix summation and another thing is gonna be uh the index so in instead i'm going to store it to both so that's why the initialization we are going to put in is going to be 0 and 0. and the first 0 is going to be index and the second also is going to be the summation so you see the differences later so now we have the prefix submission and we put uh for loop in it and we're gonna start doing the for loop and we are looking through the entire array so that's gonna be a and uh each time we're gonna accumulate the summation so sum is gonna plus or equal to the num and once we have that and we start popping out from the left so even though it's not really intuitive because we haven't started appending into the queue so in your mind it's probably empty but let's pretend that you know what uh let's do uh append first so let's append uh and everything because this is zero index right so we need to plus one um and some so some we which we calculated right here and now we can start like a popping from the left hand side so once the case is going to pop from the left hand side is when we fix the position we fix the need and the condition is going to be the zero and uh what is that the summation is the second element so we put one right here so if the difference is between the current summation and um the priest the prefix summation in the very beginning if the difference is greater or equal to k that means we fix the need and we fix the condition and then we're gonna start popping from the left so before we pop in from the left then we're gonna calculate uh store stronger results so we actually need to store the result as well and because we need the smallest elements right smallest uh the length so that's why i need a positive infinite number right here and we're gonna calculate the smallest number so we take the result and we take the i minus one minus the index so we'll stay index that's the first element uh of the first node in the queue and we minus that and we plus one the reason we pass one is that for example we have one here we have zero here and one minus zero and doesn't represent two atoms right so we have to plus one so that means we have the two atoms right there once we have that and then we start popping from the left hand side so just like the regular two pointers and you have the left point two left pointers and start accumulating to the right hand side um once we pop that and the first elements become the pointer actually moved to the right hand side so that's what we're doing uh somehow it's being removed okay um that's when we deal with the left-hand that's when we deal with the left-hand that's when we deal with the left-hand side and same thing we're gonna deal with the right-hand side and this deal with the right-hand side and this deal with the right-hand side and this is a slightly different with the 239 right 239 when we do with the left-hand side is that because with the left-hand side is that because with the left-hand side is that because we only add one element from the right hand side and we pop from the left hand side and we just use if condition but now we use a while loop so while loop the reason we use while loop is that the condition changed and it used to be index based in the 239 we actually just want to keep the windows sizes the same but right now we just want to keep the value the same so values might be varied right some numbers might be big and some numbers might be are very small and that's why we use the while loop to do to keep track of that and we're going to have the q and then we also want to maintain the increase in q so the way we deal with the increase in q is that if the news element the summation right so if you're incorporating a new number and if the new number is less or equal to the last elements from the cube that means the new number you're incorporating is the negative number so we don't need uh we don't need the previous numbers anymore so we're just popping those guys out and because we want to have maintain an increasing q and the way we do that is popping everything uh previously out and so once we have that and we start appending whatev what we have right um i think we're done so all we do is return the value so the way we turn that is if result is less than float infinite so that means that uh we did updates the value so then we just return result otherwise we're going to return negative one and let's try if that works or not okay works yeah so basically verse number two to 39 so all we do is tracking from the left hand side and from the right hand side and if you understand the logic so i think you got it um if you like the video please subscribe the channel i'll see you guys in the next video
Shortest Subarray with Sum at Least K
find-and-replace-in-string
Given an integer array `nums` and an integer `k`, return _the length of the shortest non-empty **subarray** of_ `nums` _with a sum of at least_ `k`. If there is no such **subarray**, return `-1`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[1\], k = 1 **Output:** 1 **Example 2:** **Input:** nums = \[1,2\], k = 4 **Output:** -1 **Example 3:** **Input:** nums = \[2,-1,2\], k = 3 **Output:** 3 **Constraints:** * `1 <= nums.length <= 105` * `-105 <= nums[i] <= 105` * `1 <= k <= 109`
null
Array,String,Sorting
Medium
null
86
hello everyone in today's video we are going to solve one more lead code question that is question number 86 partition list so in this question we are given a head of linked list and a value X and we have to partition this linked list and such a way that all the nodes less than x comes before the nodes greater than or equal to X and we should also we have to preserve the original order as well so let's see how we can solve this question using this example people where this is the given linked list and we have to partition this linked list using this x given x is equivalent to 3. so in our example our X is 3 and we have to partition this linked list on the basis of this value so all the values which are lesser than 3 are going to be on the left side and all the values which are greater than or equivalent to 3 are going to be on the right side so what we can do is we can create separate two lists for left and right partition so like I will create two dummy nodes like first one will be for left and second one will be for dry so these are my two dominoes and what I am saying now let's Traverse through this whole linked list and we will update are these two dummy nodes next pointers so firstly I will come up to this node and its value is 1. so what I will check if what I will check is 1 is less than 3 right and as 1 is less than 3 so what I will do I will simply point my left amino's next pointer towards this node with value 1 right and then what I will do I will go to next node that is 4 again I will check the same condition is 4 Less Than 3 no so if this is not true then what I will do I will update my right dummy notes next pointer and I will point that pointer towards this node with value 4 fine now again I will proceed and go to this pointer that is go to this node which is 3 and I can see that 3 is not less than 3 so it will go to this node it will go towards right portion right so I will again point my right part I will add this note in my the right partition I am not adding this node but I am pointing the next pointer of the previous node from right portion towards this node so this is what we are doing we are not creating any node now again what I will do I will update my pointer and we will proceed towards next node that is to again I will check 2 is less than 3 so that's true so what I will do I will update my left partition so now this Node 1 next pointer is going to point toward 2 this is 2. now again I will update my head and go to next node that is 5 and again I will check the same thing is 5 Less Than 3 no so if 5 is not less than 3 it will go to right side and I will point my Note 3's next pointer towards 5. so this is how we reached up till this node now again I will update my pointer and point towards this node last node again I will check the same thing is 2 Less Than 3 yes it is less than 3 so what I will do I will update my left party so now this next pointer is going to points towards 2. and this is how I Traverse the whole linked list now after traversing this whole linked list what I saw is both the partitions are now what I have to return is I have to return the partitioned link list so what I will do I will simply take the last node of this left partition and points its next pointer towards right notes next point I will take the next pointer from the left partition last node that is 2 and I will point it towards the next pointer of right partitions head so in this manner the end result will be 1 2 4 3 5 and we can see that this is the ANS light fever searching for right so in this manner we can create two partitions using two dummy nodes that is we have all already we have only created two nodes that is left node and right node and then what we did we simply updated the next pointers of all the nodes and at the end we join these two partitions and then we will return the left pointers left partitions head and this was the whole solution so what is the time complexity of this whole solution let me just clean this side so we can discuss the time complexity and space complexity of the solution is pretty straightforward the problem is pretty straightforward and I really like this question so what we did is we Traverse this whole link list only once we hadn't traversed this whole link list twice or twice to create these partitions so our time complexity is going to be big off n where n is the length of linked list and first base complexity we can say it is bigger of 1 why it is because of fun because we are creating only two dominoes that is left and right and rest we are using these same nodes from the given linked list we are simply updating the next pointer right so we only use two dominoes and that is going to be constant because we always because we are always going to create two partitions and for that we only need two dummy nodes so the space compound complexity will always be constant so this was the whole explanation now let's jump to the coding part so firstly let's define our two dummy nodes that is left comma right so this is how we initialized our left and right dummy node after that what we are going to do we are going to define the Tails of these Domino which we will be updating so this will be left and this will be right and after this what we have to do we have to run a while loop and we have to run this while loop to the point we had increased the end of our given linked list so what we are going to do if head dot val is less than x right so in that case we are going to update the left tail so left tail dot next is going to be equivalent to head and then left tail will be left tail dot next so this is the first condition and if this condition is not true what we are saying simply do the same thing over right tail dot next is going to be equivalent to head and right tail is going to be updated with it next right table dot next and up and at the end what we are doing we are updating the head pointer that is head equivalent to head dot next and after stepping out of this Loop what we have to do we have to join the two partitions right so what we have to do is firstly we have to end our linked list so right tail dot next will be equivalent to none this has to be out of loop after this left tail dot next is going to be equivalent to write dot next and we will be returning what I just wrote goodness returning left we have to return left dot next okay so this is working now let's submit this and you'll see it's working for all the test cases or not so yes it's working and we can see this whole solution is quite optimized and I hope this whole solution and this whole video was helpful for you all and if you find this video helpful then you can like this video subscribe my channel and I will soon come up with more such videos till then keep watching keep coding and thanks for watching
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
278
okay nothing high energy today so let's stop one simple question 278 first a bad version so the question is quite long basically the gist of it is that just imagine that we have a versioning of our code that's a linear sequencing versioning 1 to N and in some of the point in some version there is a bug that are introduced without anyone that noticed it's until that in the very latest version we noticed the bug so we want a retro is retro and find the first version that they introduced the back so for that purpose we developed a some kind of code method that we can call to check a version of the code and I guess this box check in error checking message can be expensive so we want to reduce the time that we use this thing to check now we're you know previous version of the code so we asked you to come up with heuristic to minimizing the number of API calls but still be able to find the first a bad version so there's a important property of this problem is that whereas all the versions after a bad version are also bad so if you can imagine that when we call this bad version 1 you might return false would call if version 2 in my return false if we call it's bad versions 3 when you if it comes as one true that everything every version after that then we call this is bad version there won't be one as well so we realized that the search space you know it's actually a sorted array so it's a zero enough you know in a it begins with zero zeros potentially zeros and then everything else is one afterwards so if we want to find the first two one the way we do that is to use binary search because a linear search we have to do redundant work a lot of redundant work but if we use binary search we can literally we can just cut the search space into half by utilizing that the property defined here so yeah so that's the question approach to this question so the time complexity will be log in and space is a constant let me move myself over and code this question up really quickly so we got a little binder which is starting with what the first version and we've got a hi pointer which is and the velocity version here while we haven't pin down exactly which version that introduces the bug we should check the middle one that's the low plus high and divided by 2 if we call this message here if it's the bad one then we look at the left the first half try to pin down exactly where this bug introduced otherwise we look at the haha you know the second half and for this case we can actually go to n plus 1 because if M is not a bad version then we don't need to check in the next generation so that's the that's basically the code and it looks good to me let's submit it okay it's working and quite fast so that's the question for today
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
265
foreign problem 265 paid house number two so this is my code for solving the pith house number one yeah because in pit house number one we only have three different colors the only difference is here for the problem 2 we have three different colors yes so the cost of paintings house with a certain color is represented by a n times K cost Matrix yeah n times K cost Matrix cost so this is the difference because inside this color it may have three colors for the first house yeah so the cost is one five and three and for this example inside it may be two colors one and three so basically it's the same yeah so for solving these problems it's also the bottom up yeah now let me copy The Matrix here to analyze it after that IO seems a little bit and to be used for other yeah paid House 2 problem now let me make an alignment of the houses so as you can see this is the first house it has three colors this is the second house here the second row it has a three colors yeah so for example this one and two it means the same color but you cannot beat house for the same color so from the bottom up if you choose this three it means you cannot choose this four anymore you have to choose two and nine yeah so this is basically my algorithm from the bottom up and when you choose a five it means you cannot choose this nine you can only choose two and four yeah so this means five and nine are the same color it means it has to be a different color and five two three and five to one is also the different color because this one five three means the cost for painting house one with different colors and 294 the cost of painting House 2 with the different colors yeah if you choose for example for this example I'm going but after that I have to choose the three so that is why I'm gonna return five if I choose this four after o I gonna choose one plus four is also five so the minimum is five yeah now I just need to change a little bit code to make it work for the penthouse two problems so because it is not three anymore it have to be okay and in this case equal to the length of the any one house and how many colors yeah for example the first house and it has three colors so k equal to the length of the cost is zero yeah now let me run it to meter to work as you can see it works and by the way the time complexity is n times K so n is the length of the cost array so let's check the length so the length is only equal to 100 and K is 20. so basically the time complexity is this n times this K now let me run into two tag if it can pass for all the testing places yeah let's start with for a few seconds to check if yeah as you can see it works and it's pretty fast thank you if you think this is helpful please like And subscribe I will prepare more lead called problems like this see you next time
Paint House II
paint-house-ii
There are a row of `n` houses, each house can be painted with one of the `k` colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. The cost of painting each house with a certain color is represented by an `n x k` cost matrix costs. * For example, `costs[0][0]` is the cost of painting house `0` with color `0`; `costs[1][2]` is the cost of painting house `1` with color `2`, and so on... Return _the minimum cost to paint all houses_. **Example 1:** **Input:** costs = \[\[1,5,3\],\[2,9,4\]\] **Output:** 5 **Explanation:** Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5; Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5. **Example 2:** **Input:** costs = \[\[1,3\],\[2,4\]\] **Output:** 5 **Constraints:** * `costs.length == n` * `costs[i].length == k` * `1 <= n <= 100` * `2 <= k <= 20` * `1 <= costs[i][j] <= 20` **Follow up:** Could you solve it in `O(nk)` runtime?
null
Array,Dynamic Programming
Hard
238,239,256,276
5
hi guys this is Vanina from I deserve today I am going to talk about longest palindromic substring so given a string like bananas we want to find out the longest palindromic substring here so you have a na n as palindromes here you also have a and a which is the longest palindrome we want to find this up so there is a brute force solution to this where we check all the sub strings of length 1 to N and then test each of the substring to be a palindrome or not so that amounts to order of n cube which is very inefficient there are three more efficient solutions to this problem of which I am going to discuss one based on dynamic programming before going there let's try to understand how to detect a parent row given a string like this first we would compare the first and the last characters if the first and the last characters match then we would go ahead and see if the remaining substring after stripping out the first and the last character this is a palindrome or not if the remaining substring is also a palindrome then the whole string is a palatal there are the two conditions that we want to leverage in the dynamic programming approach so in this approach we have a table like this where the string is represented as the rows and column both we also keep track of the current length of that we are looking at so we will be going from substring of length 1 to N and we'll keep track of what length that we are at using this variable current length we will also use another variable called maximum length which will keep track of the maximum length of the longest palindrome that we have at that point here and then we will also store the longest palindrome we have encountered along the way so let's start with sub strings of length 1 which are trivially palindrome those will update as true right let's go to lengths of 2 here B and a do not match right so it does not satisfy our first condition so it's not a palindrome a N is also not a poly a palindrome so we say false here and then na is not a palindrome again a n is not a palindrome and so on just go to length of 3 what we see is BNN do not match so Falls again but here a and a is a palindrome because a and a matches and if we step out a and a n is already a palindrome here so we update true here we also find na n as a palindrome sick palindrome similarly again a and a is open it up similarly right so let's go to the length four for length four we don't find any palindromes for length five we find a bigger palindrome where a and a matches na and we already know is a palindrome so both the conditions are true so we have did true here finally the length 6 for length 6 the first and the last characters do not match so we have dropped it false the longest palindrome that we found here is a na so let us look at the code this part is initialization where we keep track of the index where the longest palindrome begins we also keep track of length of the longest palindrome and we also have a boolean table to store the palindrome truth values so these are the palindrome truth values the first loop is to update all the single letter palindromes which is here and second loop is to update or to character palindromes which is basically this diagonal right baa and na and so on the third loop is to go from length 3 to n and save the longest palindrome that we find right so the two conditions that I mentioned are here the first one is to check if the first and the last characters match and the second is to see if the rest of the substring is a palindrome so if we are at here a and avian looking at a length 3 substring what we are going to do is see first and the last character if they match the first condition satisfies and then slip of the first and the last character which is basically I plus 1 J minus 1 we are looking at n right n is already a palaver so to both the condition satisfy so we'll be updating this particular cell of this table as true we go on till n length n and we find a n a similarly with this procedure and finally we can take the substring of the original string using both the variables that we keep track of the index where the palindrome starts and the maximum length of the by using here also the diamond space complexity of this particular algorithm is order of n square please go through the code which is below this video also look at the visualization please let me know if you have any questions and concerns thank you
Longest Palindromic Substring
longest-palindromic-substring
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`. **Example 1:** **Input:** s = "babad " **Output:** "bab " **Explanation:** "aba " is also a valid answer. **Example 2:** **Input:** s = "cbbd " **Output:** "bb " **Constraints:** * `1 <= s.length <= 1000` * `s` consist of only digits and English letters.
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
String,Dynamic Programming
Medium
214,266,336,516,647
55
Hello Hi Guys Welcome To Drama Video Desi Bf Coding And School JumpGames Surya Gives Energy After Negative Integers Comes And Bare Initially Setting On The First Indian Wisely Limit Naridra Maximum Complaint And The Question Return Of Rebel To The Last Intact So Let's Take Two Examples From To-Do List This Examples From To-Do List This Examples From To-Do List This Problem Gets Relief But Instead Of Trying To Reach It's A Question Is The Worst Position Problem Team The Worst Position And Subscribe University B.Com Questions No Now Scan Very Large Portion By Reminding Specific Loose Motion By Sending Another Life 2009 2013 International Let's Go to the Second Last Question Subscribe Someone from the Distance This is the Question No Real Life in This Mission 272 Plus Automatically Subscribe to the Channel Definitely Subscribe to the Channel Now 130 So Let's All the Selectors Please Call The System Index Want To Reach The Last To The Let's Go To The Next And Subscribe Now You Know That Is The President Of You Find Last Elections From Thel Asan Tax Credit The Second Last Point Extension Class Mix it is the president care of just care no difficulties and two possible means a waste returns through if the output is true love you to the number two but only one step subscribe our Channel and subscribe the Video then subscribe to the Page that Show Vigilant and Don't No Our Indicator They Want To Reach Vikram Equal To One From Wearable Tours And Number One Is The Means Of Birds Elastic Canalis Available To Send Number One From This Point To The First Indian Badminton League Twenty-20 Final Journey to the Number 210 Twenty-20 Final Journey to the Number 210 Twenty-20 Final Journey to the Number 210 Sudhir and Subscribe Now to the Number Five Years Will Reach Subscribe Now to Receive From the position of this is not needed not to take From this point to you will not be able to hear what the fish that you will Need to You Know Look Left Words Another Saini Mode Possible James David Khanduri Tennis Numbers Fiber Australia and India Cement Pipe Rates Meaning of Previous Example Visavadar Dance Class Next Was Helping Us to Reach Last Breath But Did n't at All Stories Last Next to the Last not mean that cold not but you love you to go for the next to the number of subscribe here to reach the water index want to know easy can jump to step what is means is that we can register Index Number Five Step Want To Reach From Here Rates Vitamin C The Tips You Make To Jump From Here You Will Reach The And 10 Inch Extra Security 2232 Possible For You To Reach The Number Three Lakh From Cash One To Three Idiots Number Toll Free Number Customer Care Contact to take Tanveer win over the phone on August 9, 2002 Ek aham yeh index hai sir a leaf one so what is means is updater from here you will be able to take only one step number 3 number three layer number one can you can only take Number One To The Spider In Positive Territory At Least For The Next To The Number One Day You Will Go For The Number Two And Number 01 That You Know What This Means Now They Can Take Three Steps Fiction Stories In December 31st Incident Preserve Review Birthday To You Will Reach In December 3rd Android Number Three To Increase The Last Not Want To Change Into The Road To The Giver Subscribe Another Example Subscribe To And You Have Another World Believe They Will First To The Doctor Away From Question But They Will Not Two Annie James Weir Were Sitting and Last in Acts Will Not Move to the Left Know It See the Story The Last Step Number One Plus subscribe to the Video then subscribe to A Lemon Forward to the Next Flight Most of These Alone Will Have Inactive Savings Value Of One Number Its Joe Hair Pack Check The Number One Plus One Should Not Be The Subscribe Now To Receive New Updates Reviews And All The Best Way To Subscribe Is And Weighted Se 0.5 Inch Bf2 Return Through Is And Weighted Se 0.5 Inch Bf2 Return Through Is And Weighted Se 0.5 Inch Bf2 Return Through Minute Example For Example Some Have Something Like For Example Delhi-110023 President Three To The Last Leaf From Various Sources Number Three Leg Race Vice Chancellor's Through It's Okay So Let's Move With Subscribe Number 90 Value Loot Tattoo Sudhir Plus Two Is Not To Be Given Equal This Again Use Lewis immediately move forward and will the value of Heading December Is Have A Leaf to the Video then subscribe to the Page if you liked The Video then subscribe to the Last Question on a Newly Married Paris End of the Year and Which Acid is Not Equal to Zero Rided Versus Written by Ex is Naughty Kids Will Return Of All Sindhis Censor English To Go To School Secret Supreme The Worst Thing Can Only Jump Maximum Of Two Step Sunao From Here 9.5 2G And Step Sunao From Here 9.5 2G And Step Sunao From Here 9.5 2G And Tourism Last Next So Let's Clean Up This Ki N Ki Related Co Dot S To Assembly Will Write Intent Right To Left Side Will Declare Is Good To Sight - One Who Will Declare Is Good To Sight - One Who Will Declare Is Good To Sight - One Who Will Change A Greater Than Equal To Zero Enabled By - - 9th District Level Check The By - - 9th District Level Check The By - - 9th District Level Check The Condition Is Name Clear I Plus I Is Great And Cold You Want To Change The D If Diet Set A Simple Total And Finally She Docent The First Indian Swiss Index Is Equal To Zero Daily In Return Proof Otherwise Wick In Return For Its Return True Value Return Forms A Ki Chudai Set And Lag Mixture Sit Working Fine Hua Hoon To I Think Is Hari Mirchi Mistake Lakshmi Conference Seat Sign Up That's Just Time Thank You for Being Patient and Listening Thank You
Jump Game
jump-game
You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position. Return `true` _if you can reach the last index, or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[2,3,1,1,4\] **Output:** true **Explanation:** Jump 1 step from index 0 to 1, then 3 steps to the last index. **Example 2:** **Input:** nums = \[3,2,1,0,4\] **Output:** false **Explanation:** You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 105`
null
Array,Dynamic Programming,Greedy
Medium
45,1428,2001
38
in this video we'll be going over count and say the count and say sequence is a sequence of digit strings defined by the recursive formula so in our base case we have count and say one which is a string one and then for countless a n is the way you would say the digits from count and say n minus one so we'll define the count and say n minus one and then convert it to a different digit string so determine how to use say a digit string split into a minimal number of groups so that each group is a contiguous section of the same character then for each group save the number of characters then say the character to convert the saying into the into a digit string replace the count of a number and concatenate everything so in this example we have two five one 3322251 we have two degrees three twos one five and one so we have two three two one five and one let's first go over the dark process we will implement a recursive approach so for each of the number n we will first want to find the count and say for n minus one then for each of the characters inside the previous string so we call this prev so count and save we say pre for n minus and for each of characters see inside brief we will want to keep track of the frequency or which is a consecutive frequency of c inside brief then if we are at the end of the string or the next character does not equal to c we will need to append count and c to our resulting string for our current count and say for n let's go do the code so we will implement a recursive approach and then what parameters do we need we will say n the current number we are processing and then what's the base case in the base case we have if n is go to one and we can just return the string one in each of the recursive call recursively find the previous string for n minus 1. and then create a string builder current to keep track of the count and say for n and then we'll create a variable counts to keep track of the frequency of the current character then we'll iterate through the it'll redo the previous string iterate through the indices of brief we say denoted as i increments will increment count basically increment the frequency of our current character and then if i is at the last index or the character at i plus 1 does not equal to the character to the current character i then we will want to append the count append count to current and then append the current character to also current and then reset count to zero for the next character and then we can return a string representation of current let's go over the time and space complexity what's the time and space complexity time complexity is equal to of n times k where n is the input value and k is the average length of each string there are up to n recursive calls and we iterate through k indices each and our space complexity is equal to suppose it's also of n plus n times k so of n is the recursive call stack memory and of k is each of the strings that's generated the generated strings in each recursive call now let's go through the code so if n is go to one then we can just return a string one and then we will first find the count and say for the previous for n minus one please go to count say n minus one and then create a string builder for the current count let's say and then create a variable to keep track of the count of each character then we iterate through the indices of previous increments count if i is at the last index or the next character does not equal to the current character i does not equal to prove that char that's i plus one then we'll append the current count append count and the current character append current character to our current account and say and then we'll reset count to zero and return a string representation of current let me know if you have any questions in the comment section below
Count and Say
count-and-say
The **count-and-say** sequence is a sequence of digit strings defined by the recursive formula: * `countAndSay(1) = "1 "` * `countAndSay(n)` is the way you would "say " the digit string from `countAndSay(n-1)`, which is then converted into a different digit string. To determine how you "say " a digit string, split it into the **minimal** number of substrings such that each substring contains exactly **one** unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit. For example, the saying and conversion for digit string `"3322251 "`: Given a positive integer `n`, return _the_ `nth` _term of the **count-and-say** sequence_. **Example 1:** **Input:** n = 1 **Output:** "1 " **Explanation:** This is the base case. **Example 2:** **Input:** n = 4 **Output:** "1211 " **Explanation:** countAndSay(1) = "1 " countAndSay(2) = say "1 " = one 1 = "11 " countAndSay(3) = say "11 " = two 1's = "21 " countAndSay(4) = say "21 " = one 2 + one 1 = "12 " + "11 " = "1211 " **Constraints:** * `1 <= n <= 30`
The following are the terms from n=1 to n=10 of the count-and-say sequence: 1. 1 2. 11 3. 21 4. 1211 5. 111221 6. 312211 7. 13112221 8. 1113213211 9. 31131211131221 10. 13211311123113112211 To generate the nth term, just count and say the n-1th term.
String
Medium
271,443
1,415
hello everyone welcome to clashing order so in this video we will see the question 140 1415 that is the kth lexus graphical string of all happy strings of length n so let's see what is a happy string first of all a happy string is a string that there are two rules you can see consists of only the letters of set a b c so that means the string the whole string should consist of only three types of characters that is a b and c from this set that we are given and the second condition is that s of i is not equal to s of i plus 1 so that means the two adjacent characters should not be equal so if like we are given a b then the next vector cannot be b because b is similar to b so it should be c it should be unique actually you can see for all the length of this thing you can see from i uh from one to length of the string so you can see for example the strings are given abc so this is a happy string because it consists of only three type of characters that means abc and all the adjacent characters are different from each other here you can see a c b so you can see in this string you can see all the adjacent characters are different than other you can see a b then c b a then b c and b if it would have been instead of c in it would have been b instead of this c so then it won't be a happy string so you can see here all the have all the happiest things but the strings a so here all the adjacent characters that is a and a are same so that means it is not a happy thing here you can see b e so here it if it would have been instead of a it would have been b or else c then this will this would be a happy string but this is not we can see the adjacent characters this second condition is false here you can see b a so a should not be same here you can see so the way given uh we given two integers that is n and k consider a list of all the happy strings of length n so here you can see this is of length three two one so we have to consider all the happy strings of length and the and sorted in lecture graphic order and they also should be sorted in lecture graphical order so i will explain you what is lecture graphical uh afterwards so let's see you can see the return the kth string of this list or return an empty string if there are less than the k happy strings of length n so that means we have to we will be given n and k you can see in this example we are given n and k n is 1 and k is 3 so we will have to generate all the possible happy strings of length 1 which will only consist of abc and will be of size one and we have to print the third string that is k you can see k is three so we have to print the third string from that list so this is what we have to do you can see here the c is the third string because uh of length one there are only three possible strings that is a b and c all other would be uh not of length one so you can see here from here this list we have to generate which is consisting of all the happy strings of the particular length that we are given and we have to our print the third or you can see the kth value from this okay is c so here you can see n is 1 and k is 4 here you can see this is the so this is actually the base case you can see n is equal to 1 and k is equal to 4 so n is equal to 1 has only three you can see possible happy string so k is 4 but k is not in the length that is k is greater than n so that will be simply we have to return the empty string because we don't have enough happy strings of that particular length and we cannot print that kth value for that particular vector which is of less size than k so this will be one case and let's see how we can solve this question actually you can see the size of n or the n will vary from one to ten that means you will be we will be have to generating we will have to generate the strings from length one to ten and the k will depend from one to it will change from one to hundred so let's see how we can solve this question actually and i will also explain you the example first of all so actually uh as it is written that we have to we are given n and k so we have to generate all the possible strings that are happy strings actually of length n so n is 3 here so to generate all the possible strings you can see it will be a b c and b it should only consist of three types of characters that is a b and c so here you can see for n is equal to three all the possible happy strings will be a b c a c b a c and you can see this b c a and all that so here you can see it was also written that they should be electro graphically sorted then only we should return the kth string so here the kth string in this is this you can see bca so we will have to output bc but how do we know that it is lecture graphically sort of lecture graphically sorted is actually if you are given like number one two and three okay so and you are given number one three and two so in out of these which numbers is greater you can see which number is greater actually so here if you see one is similar okay one is similar so we cannot differentiate on that but here if you see 2 and 3 so here 2 is less than 3 so that means this number is actually greater than this number you can see it is like so graphically greater than this 1 3 2 1 2 3 so in this example also where we are given the characters here you can see abc so abc is actually smaller than acb so if you will have to consider from left to right lexographically for uh considering left lexicographically you will have compare you have compared to from left to right so if you compare from left to right you can see a and a are equal but here b is smaller than c so that means this string is dexographically greater than the first string and you can see this third string is actually lexographically greater than the second thing because here the first characters differ and here it is b and here it is a so a is smaller so this is actually the lexographically or lexicographical order so what we have to do is we will be given n okay we have to generate all the possible happy strings so you know that conditions first condition is that they should be only consisting of a b and c the second condition is that or no adjacent characters that means these characters a b should not be equal if it is given like a and then b so here these adjacent characters a and a are same so this cannot be a happy string so we don't have to do this so we have to generate all the possible happy strings of size and that is n is three here so we have generated all the possible okay lexicographical strings and we have to sort them according to the lexographical order you can see they are sorted so they all are sorted then we have to find if the size this array that we have created which consists of all the possible strings of size n has length greater than k if it is greater than k then only we can output k so k is here you can see one two three and four so our output will be this bc a if it would have been uh asking like k is equal to 10 so here you can see we have only the strings possible as six okay six things possible of size n so how we can return uh and so n is greater than six so in this condition we will simply return empty sync here you can see in this question so we have returned empty sink in this you can see n is equal to 2 and k is equal to 7 here it is written return empty string if the there are less than k happy strings of length n so let's see how we can approach this question so actually you would have to go to know that uh first of all we have to generate all the possible things as i told you we will have to generate all the possible strings so first we will have to start with empty string so for this generating all the possible strings you know that permutation of saying so we use recursion so for this question this is the hint actually we will have to use recursion here you can see the constraints are also not the large and is and varies from 1 to 10 and k also varies from 1 to 100 so we simply you can see the we can use recursion because the constraints are also like uh optimal so that is why we will use recursion so let's see how we can approach this question now we know that we will have to generate all the possible strings so all the possible uh happy strings actually so to do that what we have to do is we will start with the empty sing then we will put a at first place and then we will try to put b after a and after a we will have to put c then we will keep adding we will have a set of three characters you can see a b c so we will run a loop and we will try to put all the characters after a particular character and to do that we will have to also check if it is a happiest thing or not to make it a happy sing we know that we are satisfied in the first condition because we are forming the strings only from this set of characters that is abc so first connection is satisfied but for the second condition that two adjacent characters should not be equal when you are doing this you can see abc here after a so first we have the empty string then you edit a in here to generate the sink okay then you add in b then added c so after this condition here you can know that there are no uh adjacent characters which are same but after this condition after this actually node you can see we have three options actually we can add a we can add b or we can add c here actually it is b actually you know that it is b so we can add only after c you can see we can add only a and b so when you are doing recursion you will call over you can recursion will call automatically for three options so it will be for b a c and it will call for all the three options you can see these three options will be called but here only two are happy strings this is not a happy string so we don't want our recursion call to go to this thing or to form this thing so to stop that what we will do is we will simply actually file calling for the recursive uh function uh by calling for the recursive function we will not uh we will check with before calling actually for the function we will check if the last character in the string so this is a string that we are given actually let me write it so we are given a string we are on the string abc okay abc and we uh we are we have to call the function recursively so before calling the function recursively i will also show the function and also the code so let's see first of all understand the uh actually the approach so before calling the function recursively before adding any character we will check if the last character that we are on that is c it is equal to the character that we are at trying to add so we will be trying to add a b and c so when we try to add a here you can see a is not equal to the last character so last character is c so that means they are not equal to adjacent uh characters are not equal so that means the second condition will satisfy for this string so we will add it over uh we will call this function recursively for that particular character now we come to b so b is also not equal to c so we can call this function again then we come to c so you can see b we come to c so c is actually the character we are trying to add c is equal to the last character of the string so that means we cannot add c here so it will not be happy string so we will simply not call this function so we will add a simple condition that the last character should not be equal to the character that we are trying to end so this will be our recursion direction you can see so uh simply we will form a function have the function actually which will try to uh perform the all possible strings of size n so when it will come it angles like if n is 3 so we will uh try to like recursively call the function so first it will add a then it will add a b after a and c after a then it will add a b c and a c b so when it reaches the size n that is n is 3 here so it reaches size of 3 that means we have formed a string of size 3 and which is also valid you know that it is happy string otherwise the recursive function will not call that particular string if it is not a hyper string so here abc is a happy string so we will form a vector which in which we will store all the possible happy strings of a size n so you can see we will add simply a b and c and uh when the size of the string is actually equal to n so n is c and the size of string is also c so we will simply add the string so when you come to this call actually so uh when you come to this uh you can see a c and b here you can see here we can add this also a b and e is also a valid string so i have not completed this question actually it says it is simply for the visualization actually you can see we will be also generating a b and a because a can be added after b a c can be added and a can be added because the adjacent characters in this ring are also not equal so we will simply add a b and a so we will simply make a function which will call for all the recursive strings and which will be happy seeing actually when the size of the string that we are forming this empty saying start this start with the empty string when its size becomes equal to n that is three here uh ns3 so we will simply add it to the result vector then at the last when we have generated all the possible strings and our recursion has ended the question t has ended then we will return we'll check if the size of the array that we that means all the possible strings are greater than k if the size of the array is or less than k so that means we have uh not k value is not possible so we will simply turn uh empty string in that case but if it is possible we will return we will have the vector which is all the strings we will return simply k minus 1 from that vector because it is a one based indexing actually k so we will have to subtract one minus from minus one from it so then it will simply turn over output so let's see the algorithm for this approach actually so you can see this is a simple algorithm for this so first we have to initialize the array of strings result as i told you we will have to store all the possible happy strings into a result array so we'll store into a happy uh this result happy strings then we will make a function call actually with the build function f built sing is a function that we are trying to call recursive function or we can say a helper function so this function will take three arguments first will be n and k because n is to check whether a string is becoming is equal to the size n or not if it is equal then we will relate to uh do the result and to optimize our calls further or optimize our recursion tree further what we can do is when we are given chaos okay we are giving k also when you are calling this function it will come here okay then it will add this thing so the size of the array will become one okay when it will add this thing the size of our array will become 2 so when it becomes equal to 2 another k is 2 we will check if the size of array becomes equal to the k then we can simply return our function because we know that we have formed the kth value or we have found the kth value we don't have to find the after the kth value so that means we'll simply turn from the function and we will return this value so you don't have to form all the recursion calls if you have already got the size of the array equal to k so we'll simply turn from that point so you can see here first of all this is a function that we will call okay this is a function call that we have made and this is a function so n is a length of the sim that we want so n is c here and k is two and string is empty first of all we'll call the empty single you can see empty string and we will at every point we'll check if the result size is equal to k as i told you to optimize the calls so we will check if the result vector that we are having has already k number of uh strings so we can simply turn from the function and we can uh return actually the result and uh result that we have at k minus 1 so it will be the answer our answer so then if it is not equal that means we have to make more function calls so we will check as if string dot size is equal to n so as i told you when the string size becomes equal to n so that means we have formed a string of size n so we can simply add edit to our result because it is the possible happy string so we will add it to the result you can see a result dot add and we will return from this function because these are already called so it will return to the parent function actually so for this recursion it actually uses stack so then you can as i told you we will have to use a for loop actually for this because we have to traverse over all the characters so all the possible characters are a b and c so this is actually a c is actually the last character that we are trying to add this is actually you can see capital c here so this is the last character that we are trying to add the new character if we have a okay if we have a string empty string okay so we can simply add any character so you can see we will have two conditions if the sync size is equal to zero so that means our string is empty so we can any character so we simply call this function again and you can see string so it will call n and k and then give me the remain same we don't have to subtract it then we will call the string so sing here is empty because this is the first function call and we will add it the a to it and it will also call for b and c because the string is empty so now when our sink is not empty so if we have a and the c comes to a so we will check if s dot back is not equal to c that is uh the c so c is here and the our string is also a so we cannot add a after a because the adjacent characters will become equal so our second condition will become false so that is why we are checking s dot back should not be equal to the character that we are trying to add so this would be the simple you can see algorithm for this approach so let's see the code so the time complexity for this will be actually uh and with this exponential time because you know that you will have to lessen it will be actually less than exponential because you have to generate all the possible strings that are happening so we are already like filtering our strings so we know that we cannot form a strings feature adjacent which have adjacent characters so already those things will be filtered out so our time complexity and we will reduce our function calls here you can see we were using this condition also so that is why our time complexity will be actually less than exponential time so let's see the code for this so i will written the i will also provide the code in the description so this coding is in c plus so actually as i told you we will be getting this function so we will be getting this function actually you can see string get strings so we will be getting the happy strings so you can see we have got n and uh and k so first of all we will have to make a helper function which will be calling so let's see so this is our helper function and we will pass the size of the string and the kth value that we are finding for and the string s so s is initially empty you can see here we are calling it the function with the empty string so we will check for the three conditions first condition will be actually if the size of that particular array that we are from you can see we have formed a global array of string which will be using for returning the strings we will check if at any point this array size is equal to k so that means we have formed all the possible strings still k so we have to return k only so we don't have to find the hyper strings after okay so we will simply turn from this function and this will optimize our solution and make it faster so you can see if it returns at this point that means we have formed we are searching for a uh strings of size n and hey we have got k so it will simply turn on from this function and it will check if the size is less than k so it will turn empty sync otherwise it will simply turn a result k minus 1 so the next call will be if the array size that we are we have to use is not equal to k so that means we have to make more function calls so that will be uh we will enter into this condition that is else if so as if we will check the size of the string is equal to n that means we have formed a string which is of size and which is also a valid possible happy string so we have to save it somewhere so we are using this global vector actually of string so we will add it or you can see push back to this particular vector and we will return from this function call that means we have found the particular happy string for this uh recursion so next we will go return and then it will call for the plane function so again this function you can see we will be iterating over all the possible characters so here the set is actually a b and c so this you can see auto where i use auto so it will iterate over all the e3 possible you can see characters so character to add is actually we are given a saying okay we are calling for the string if it is empty so it will add a so if it is not empty so it will check if the last character is not equal to a so if it is not equal so we will add a otherwise it will call for b or otherwise it will call for c so you can see if the string there are two conditions if the string dot size is equal to zero if it is empty we can add any character if it is not empty then we will check if the last character is not equal to the character that we are trying to add then only we will call for this function so afterwards when it with the recursion will end okay the all the conditions are not to this condition is not true so that means we have to find all the possible uh strings so then we will check if the result array size is less than k so that means there are no key there are less than key strings happy string so we will return the empty sing otherwise we will simply turn result k minus 1 because it is zero based indexing so we will have to subtract minus one and return the k minus one uh string so let's submit the solution and see if it works so it is meeting actually so this is not a back tracking approach actually so i tried also the backtracking approach but it took you can see the more time than this particular simple recursion call so this was the optimized website actually so you can see it got submitted and it was faster than 75.37 than 75.37 than 75.37 of the solution so thank you for watching guys i hope you like this video and do subscribe channel and like this video for more such videos thank you for watching guys
The k-th Lexicographical String of All Happy Strings of Length n
students-and-examinations
A **happy string** is a string that: * consists only of letters of the set `['a', 'b', 'c']`. * `s[i] != s[i + 1]` for all values of `i` from `1` to `s.length - 1` (string is 1-indexed). For example, strings **"abc ", "ac ", "b "** and **"abcbabcbcb "** are all happy strings and strings **"aa ", "baa "** and **"ababbc "** are not happy strings. Given two integers `n` and `k`, consider a list of all happy strings of length `n` sorted in lexicographical order. Return _the kth string_ of this list or return an **empty string** if there are less than `k` happy strings of length `n`. **Example 1:** **Input:** n = 1, k = 3 **Output:** "c " **Explanation:** The list \[ "a ", "b ", "c "\] contains all happy strings of length 1. The third string is "c ". **Example 2:** **Input:** n = 1, k = 4 **Output:** " " **Explanation:** There are only 3 happy strings of length 1. **Example 3:** **Input:** n = 3, k = 9 **Output:** "cab " **Explanation:** There are 12 different happy string of length 3 \[ "aba ", "abc ", "aca ", "acb ", "bab ", "bac ", "bca ", "bcb ", "cab ", "cac ", "cba ", "cbc "\]. You will find the 9th string = "cab " **Constraints:** * `1 <= n <= 10` * `1 <= k <= 100`
null
Database
Easy
null
123
welcome back guys hope you guys are having a great day today we're going to be doing something a little bit different we're going to be talking about a leeco question that I really like it's called best time to buy and sell stock three so there's actually three versions of this question and it progressively gets harder and I want to talk about the hardest one but if you guys do want to see a video of the first and second one let me know just a disclaimer there are many solutions to this is just my way of implementing it which I really like so the question is you're given an array prices where prices I it's a price of a given stock on the idea find the maximum profit you can achieve you may complete at most two transactions no you may not engage in multiple transactions simultaneously so you must sell a stock before you buy again now this may seem a little tricky if you haven't tried the first two I'm using the function I implemented for buy and sell stock one and I'm using it to solve this question so in the first version of the question we just find the biggest profit in one transaction so that's what I'm going to do first so yeah let me just write that as step one find the largest profit in one transaction and we have a helper function for this now we're gonna have three different cases for this so the first case is no profit this is when the biggest profit is zero so that means you know you can't actually make any profit off this and you have to return zero so this is my second scenario the next big profit is before or after the biggest profit transaction so once we get our biggest profit what we do is we look before that and then we look at the interval after that and then we try to find the biggest profit in those two so here's the example I'm going to use this is the array one two zero four and you know that the index represents the time and the value of that index represents the stock price so you can actually visualize this by drawing it into a graph so I just labeled them just to make it a little bit easier to understand so you can see that the biggest profit that you can get is zero to four so this entire area right here will give you the biggest profit of four now the next biggest profit is going to be from the interval 0 to 1 where you have the biggest profit of one so we know that the biggest profit is going to be four plus one is equal to five within two transactions so the way we could actually implement this is once we get that biggest profit we can find the interval that creates this biggest profit so in the helper function we could return the actual intervals that give us the biggest profit rather than just returning the biggest profit right so in this case we have two and three what we can do then is run that same profit helper function for the interval 0 and 2. and if you had more numbers here you can do three to here and then you just take the max of the left and the right finally this is a tricky one the biggest profit transaction can be broken down into two transactions now this might be confusing at first but let me draw it out so that you can actually understand it so this is the example input and let's draw this onto a graph so our example is zero three one four and you know that the biggest profit that you're going to get in one transaction is going to be when you get from zero all the way to four because this is going to give you a Max profit of four in one transaction now you're gonna see that either you can go left or you can't go right or you probably can but the biggest profit that you can get can be broken down into these two sub transactions so this one has a profit of three this one also has a profit of three so then you know three plus three is equal to six which is a much bigger profit now this is a little bit hard to implement efficiently how are we going to find those small sub transactions are you going to check every single one using Brute Force the trick is actually to find the biggest loss in that transaction so simply from here to here and you can see the biggest loss is two so the biggest profit you can get in at most two transactions is taking the biggest profit you can get in one transaction and then adding the loss inside that so four plus two is going to equal six also and this works because even though you're at 0.3 and then you even though you're at 0.3 and then you even though you're at 0.3 and then you go all the way down to point one since you know that you're in between the interval of the biggest profit you're gonna have to go back up to three eventually right so if you think about it you're gonna have this profit here so one in this case and you're gonna have the biggest profit here so three in this case and we get to add up that profit we made from coming back up from that loss which is gonna be two you can definitely have multiple losses but for two transactions what you're gonna need to do is just find that biggest loss so sometimes you're gonna have cases of all three you're gonna have the max admin here you're gonna have a big loss in between and you're gonna have profit to the right and you have profit to the left so what you do is you take the max of these three values you take the max loss the Max uh profit to the right take the max profit to the left and you're going to take the max of these three values and you're going to add into that initial profit of that big transaction and if you do that you would get the biggest profit that you can get into transactions so my solution was in Python and when I submit it the runtime was faster than 98 of the Python Solutions even though I explained my strategy there's multiple different ways of doing this but this is how I did it so we obviously have our base case here if the prices array is empty just return zero so what I did was I made a helper function called profit and what it does is it gives you the biggest profit that you can get in one transaction and uh it just Returns the max profit in the first item of that array and then the left and right indexes so I can actually extract that profit by getting first zero just like that this is where I look at that first case so what I do is if there's no profit inside that first two value right here is going to be negative one so it would just return zero here because there's no profit and what I do next is I use profit to find the biggest profit and one transaction of the left and right subarray of that big interval so I have another helpful function called loss and it's very similar to profit but it just finds the biggest loss in one transaction so I'm going to get the loss of that middle interval and I'm going to multiply by negative one since it's negative to make it positive again and I can extract the profit of the left and right by taking that first index of each array and I have that mid loss that we have so if I do profit plus a Max of these three values I should get the right answer if you want to take a look at the entire code implementation I'll have the link in the description below thank you guys again so much for watching if you do want to see me do more Lee code Solutions just let me know in the comments below and I'll have it all bye
Best Time to Buy and Sell Stock III
best-time-to-buy-and-sell-stock-iii
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete **at most two transactions**. **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** prices = \[3,3,5,0,0,3,1,4\] **Output:** 6 **Explanation:** Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. **Example 2:** **Input:** prices = \[1,2,3,4,5\] **Output:** 4 **Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. **Example 3:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** In this case, no transaction is done, i.e. max profit = 0. **Constraints:** * `1 <= prices.length <= 105` * `0 <= prices[i] <= 105`
null
Array,Dynamic Programming
Hard
121,122,188,689
902
hey everybody this is larry this is day 18 of the lego day challenge hit the like button hit the subscribe button join me on this card let me know what you think only two more weeks to the end of the year uh how did you do this year let me know in the comments below or comment this go just hang out chat about it whatever you want to do okay so this is a hard problem so it may take a while uh so yeah feel free to watch it on a faster speed or watch on 2x or i guess that is the fastest speed or just skip ahead whatever you like to do i'm just giving you options and if that doesn't work for you know i'm sure you could find another video that does it like people who keeps on telling me to switch to other languages well use other videos it's fine i'm going to keep doing it in python for you know as long as i want to anyway choice for me is given an array of digits which is sort of a non-decreasing order you can write uh i non-decreasing order you can write uh i non-decreasing order you can write uh i guess i didn't read the name yet which doesn't really matter but all right let's do it numbers at most n given digit set uh okay that's a really awkward sentence i guess anyway for example one three five we made one three five one two one okay so we can do that as many times as we want we turn the number of positive integers that can generate that are less than or you go to a given end okay uh let's see so um let's see right i mean the first thing i'm thinking of to be uh with these things to be honest it's gonna be brute force um and sing and that's why you saw me scroll down for a quick second see if um if that's possible um if this is nine then and n is ten to the ninth that means that there are uh i mean there are 10 digits but i guess like 1 billion exactly isn't it's fine um and there's no zeros anyway so there's gonna be nine digits each from one to nine so that's like nine to the nine uh 99 isn't as big as 10 to the nine but it is still pretty big it happens to be 387 million so that is not going to be great uh digits is sorted in non-decreasing uh digits is sorted in non-decreasing uh digits is sorted in non-decreasing order what does that mean can there be repeats or what does that mean like why is it not just increasing if it's unique okay i mean okay that's just like um that's a weird way of phrasing it if it is unique anyway so because increasing order is the same as not decreasing if it's unique right so anyway okay um so i think let me think about this right so the second thing that i might think about is um kind of actually i took a quick glance at this one and it gives a hint right of okay how many ways are there to have um a number of n digits right and then the next thing you're going to ask or i'm asking anyway right so let's say you know we only care about the number of digits then i think the math is pretty straightforward it is um for k digits k to the x or whatever right um because it's just all possibility so that means that we have a way to get the answer for n is equal to 1 n is equal to 10 and as you go to 100 and you know so forth right uh dot um and then the question is okay but then this obviously doesn't solve um the question of like let's say what if n is equal to like some random number right well then the question is gonna be you go to um the number of ways that n has a one prefix plus three digits right three random digits um or uh two to the plus three digits dot so you have a for loop here that's gonna be dot all the way to n is equal to five well okay let's actually not skip the dot because we're almost there um oops okay gadgets uh you know plus three digits and then n is equal to five it's not quite right because then now you could do five zero though technically the zero is not a possible thing so we'll skip that a little bit plus two digits right oops how do i keep on typing digits um and then oh there's no 5 2 because n is 5 51 so that's actually then this is not even true um okay let's can i'll get to the one in a little bit so let's ah let's swap the two and the one for a second um so then here five two well we know that you know this can this is not true anymore right not true so that means that we actually won 502 1 which is also not true you cannot do this plus one digit because the digit is constrained so then you do it from you know five one plus no digits um and then n is equal to five two one two and then n is equal to five two one three or so four right plus no digits um and then whether they're possible um i think that is going to be the way to do it and if i'm correct right um oh yeah and of course uh you know um you can kind of have an implicit n is equal to three digits um n is equal to two digits and so forth uh i was just think doing about four digits number right so that's kind of like the idea that i'm thinking playing with and of course um yeah i mean i think from here so the second dot which i kind of got distracted about that i was going to say is about the complexity right and you can kind of see from this complexity that even if n is equal to say 99999 we are going to do uh you know like we're just gonna have a for loop that goes from you know one and then two dot this time dot it uh and then nine and then one and then dot right uh n is equal to 9 2 dot n is equal to what we want to do is let's just say 9 8 and then and the next one is going to be 9 um 991 right for example right um so oh whoops i added an extra but okay but you get the idea um and of course in this case there's gonna be you're gonna move the first digit nine times second digit nine times third digit nine times dot and so um it is going to be only nine times the number of digits which is like we said before nine so it's going to be at most 81 up or 81 iterations of the loop depending how you how um what the cost of these things are so let's get started i think that's enough for um basis for how i would approach this problem uh i don't know if i've seen this one before probably i don't know well like i probably have seen it before but i don't remember it so hopefully this is helpful um but yeah so then here let's have at least for me you could have two as many functions as you like um but the way that i'm gonna do is maybe i have two functions at least uh one is n digits to kind of you know um oops and here that is just going to be these are i'm going to call this okay so then i could use n is equal to the number of digits maybe that's not reason okay never mind actually i'm going to make this k just n and then i'm going to write d is equal to the number of digits and then this is just d to the power of x right yeah um this is and of course let's document our code a little bit so we don't forget at least for me uh so number of possible numbers with x digits right okay and then now we can do a for loop with let's just say we have total is equal to zero um and then how do we say this um okay so we can do it in a number of ways uh let's just say digits is equal to one um and then how do we say i mean there are a couple ways you can do it so the way i'm iterating now is just this part um so yeah i mean you do for uh this is where like for loops in non-python languages because then i non-python languages because then i non-python languages because then i could just terminate um as soon as we care about but yeah um so then yeah it's okay um yeah let's just do this silly way uh let's convert to a string and then the number of digits uh so the length is the number of digits um and we want this um let's see so i'm just thinking about the edge cases of um let's say we have a hundred so that's three digits so we are only one up to two inclusive so i guess this is this should be good um so then now for i in range of this we can do that forget it okay total and digits of i right um and this is gonna work because um is it let's i'm just double checking whatever off by one um because for zero digits i guess silver they just don't really exist um so yeah it's okay let's start from one then um yeah okay i think we're good here though we'll double check later that's what testing is for um and then of course we'll return total at the very end and we don't have to worry about model overflow because well total can at most be n right so yeah um and also with timeout before it overflows so um okay maybe anyway okay so then now for the last digit we um we can construct it one at a time uh that's actually if for lacey let's say though you can't pass out the number from n to like have a digit by digit um but i'm going to be a little bit lazy uh oops digits is already um n digits maybe as you go to uh let's see uh weird brackets aside um okay and then now we can look at the fir oh i guess this is the length of this um and then now we can look at it one digit at a time right so here we can do four for current digit maybe uh i'm using inconsistent notation as well but uh i don't know because that's before i think so in python usually you do snag cases but when in lead code they have like weird things so it confuses me all right let's keep it consistent at least for current digit in um um how do we want to do it yeah uh well we want the enumeration version so let's do um uh let's just say for i and kern in numerate and digits um okay so then now the current we'll do a for loop for the current right um but only if um so here keep in mind that we're maybe another way of phrasing it though is that um this only has a two prefix if two is in the original digits right um for example um so in that because uh or i mean there are a couple ways you can do it to be honest i'm gonna do it with a for loop but you could actually do it with um and you can do it with a uh i want to say prefix some or you want to you could do it with prefix somewhere uh binary search on digits um and that's fine too but basically what you want to do is like okay let's say the first digit is five you want to count all the fours and all the before fours right so uh but the way that i like to write it this way because it generalizes a little bit for me in the future uh for other problems um in this case we can be more specific because it's a very straightforward formula but yeah for now for j we have is equal to the current digit uh we don't want this to be inclusive but then now we go if j is in digits which is kind of awkward i guess maybe we could have done like at least four loop until a for loop for j n digits okay fine let's do it this way digits we know that is sorted for j and digits if j is greater than or even equal to current we break because then now we hmm let me think about that if it's exactly in current what do we do oh so the way that i visualize this is thinking okay i have an example ready right if i have five what happens um well we go to the next loop but how do you handle this one exactly i guess we handled it pretty okay because we just do okay so i think if this is equal we can break um but i may have an off by one and this is something that uh we'll go hopefully i'll remember and not forget later if i when i do possible off by one let's say this one but usually i will keep it in my head and then if i see something wrong later on um i will go back to be like okay because this is sus right this is a little suspicious not quite sure it could still be right it's just that these are things that i think about when i'm writing that out right so okay but okay so before the break though we go okay so now um we know that there's a prefix with j so then we add the total two n digits of um in this case it will be length of and the other end digits well this is terrible but uh minus i minus one or minus two is it minus one or minus two but uh sorry yeah minus one minus two right for example here you have four digits um so this is gonna uh this is going to give us four if we have zero meaning this is the first index um then we are going to have three extra digits okay so i think this is right but again this is also such that we think about this right okay um and i think that should be good enough to be honest because if this is uh for the last digit it's going to only give us uh this will give us zero which gives us one so i think we're okay here let's uh return the answer though i think i have it below yeah uh and let's give it a spin and then we'll see how uh at least see if it's wrong then we can debug it right um oops i forgot that some of these are in string where is this uh and did you tonight convert it to a list j okay oh this is a string huh that's awkward actually let me convert that as well i mean we could also obviously just convert it every time but that's a little bit awkward maybe okay so that looks good um but uh so one thing that you have to think a little bit matter before you submit is that you know you look at the distribution of the test cases right and it's just and these are like really ideal situations that could easily be wrong so that's why we're gonna add uh more cases that we that's not included in the test case um yeah let's do this is hard to type but that's okay uh i think we had like some funky numbers here um and then maybe something like this should give us maybe the same number um and then just play around a little bit um yeah let's give it a spin we probably could come up more but um well but first thing first and we're really wrong uh not really even uh okay so there is an off by 1k so that's good oh okay i know why we have an off by one case is because this is good this if statement is good for everything except for the very last digit because then um because if or if i is equal to whatever because that means that the exact number this number n is a possible number but we break it off so there's that we have okay i'll buy one but that but it seems like from the other places we're a little bit more off by that um do i over count so one thing i'm thinking about is whether i'm overcounting or under counting because that helps and i think i figured it out when i um because in my mind i have a question and i said if this is if my hypothesis is true then i am over counting and then i took a quick look and i am overcounting and these two so that's good um and what happened is that i messed up um in that similar to this one is the inverse of okay basically what i was doing is that i cut this off and then i go to the next iteration right however we only go to the next digit if the number is already in it what i mean by that is that okay in this case we have like okay five one is a prefix that's why we did the loop this way however if i have six two one three and then no digits one two three four five meaning six is not in it makes no sense to have like a six thing right because we just go okay let's just say we do to do uh we have this thing in a three digit um and then n is equal to six well i mean yeah you can add stuff here but they cannot exist right because it doesn't matter because there's no six prefix um so that's why i'm wrong here um so that's okay so let's figure out both uh scenarios which is um okay so i mean these are two different one cases uh so let's think about this so okay so let's separate that out so if we break um okay so if j is equal to current we go uh maybe but let's add a statement right like um move on go on move on as you go to force maybe and then like something like this move on and then if not move on then we break so this should at least fake fix the over counting uh let's see if i'm lying and then we should only have to off by one right so okay so that does fix that and we have to off by one like we said we only have off by one when um yeah uh sorry my cut my sound got cut off for a second i think i was there's some weird thing that i was doing with my alexa i think uh but okay anyway so yeah so it is off by one so you know like we said it's just because the final number is in it so then we just there are a couple of ways you can think about this maybe uh okay let's say if maybe we can just do like if move on and i is equal to uh length of and digits minus one then we increment total right maybe that should be good enough i was thinking about doing it another way you can there are a couple of ways you can handle this is an edge case right at least in education how we construct our thing um but yeah so that looks good uh our test case is weird enough that this is confident um okay i think i'm okay um maybe i'll do one more just adding this one but with a six in it um though maybe that's the same as the other ones uh and maybe i just you know uh they have more digits uh maybe that's too many digits though okay i think this is good let's give it a spin okay so since that's good uh i'm more confident so let's give a submit i did it last time apparently about a year ago and this time nice i did get on the first try i was worried that i wouldn't um 627 days straight yay um so yeah so what's the complex i kind of alluded to this right we do it one digit at a time um and for each digit at first we go for the um all the possible digits so this is going to be at most n times d where d is the number of digit or and n is the number of digits in n right so in that sense it is linear um because that is no actually no psi this is quadratic i suppose um because the size of the input is the number of bytes which is the number of digits and the number of uh things in n but uh but yeah uh that's all i have for space i guess we reconstruct this away but you could have you know just cast an int but that's a little bit awkward if you ask me um again i don't know there are a couple of weird things here that you can optimize if you really care about space um but maybe that's a little bit awkward so i don't know do use your only discretion um okay let's take a quick look to see what i did last year um probably did the same i don't okay i did do a sword because i guess i missed it um but i did the same idea here but i did it recursively um okay i guess because the recursion works too um that's a good idea as well um so yeah uh i mean okay uh cool that's all i really have for this one uh i probably have a video if you wanna the recursive uh explanation so check that out and that's pretty much all i have um hit the like button in the subscriber and join me on discord hope y'all have a great weekend have a great friday great saturday wherever you are whenever you're watching it um stay good stay healthy to good mental health i'll see you later and goodbye
Numbers At Most N Given Digit Set
minimum-number-of-refueling-stops
Given an array of `digits` which is sorted in **non-decreasing** order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`. Return _the number of positive integers that can be generated_ that are less than or equal to a given integer `n`. **Example 1:** **Input:** digits = \[ "1 ", "3 ", "5 ", "7 "\], n = 100 **Output:** 20 **Explanation:** The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. **Example 2:** **Input:** digits = \[ "1 ", "4 ", "9 "\], n = 1000000000 **Output:** 29523 **Explanation:** We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array. **Example 3:** **Input:** digits = \[ "7 "\], n = 8 **Output:** 1 **Constraints:** * `1 <= digits.length <= 9` * `digits[i].length == 1` * `digits[i]` is a digit from `'1'` to `'9'`. * All the values in `digits` are **unique**. * `digits` is sorted in **non-decreasing** order. * `1 <= n <= 109`
null
Array,Dynamic Programming,Greedy,Heap (Priority Queue)
Hard
null
144
hello and welcome today we are doing a question from Li code called binary tree preorder traversal it is a medium let's get started given a binary tree return the preorder traversal of its nodes as values example given the tree one with no left child 2 for its fried child and then 3 none we output 1 2 3 and why do we do this it's because it is a pre-order traversal so because it is a pre-order traversal so because it is a pre-order traversal so what that means is that usually we read left root and then right but in this case the root comes before the left and the right so over here we print out root so 1 then there is nothing in the left so we move on to the right then again we do root left and right so we get 1 2 3 but let's look at a little bit bigger example to get a better idea we want to do a pre-order traversal and a quick way do a pre-order traversal and a quick way do a pre-order traversal and a quick way to remember this in case we ever forget we can draw flags to the left before the number for pre-order and take our pencil number for pre-order and take our pencil number for pre-order and take our pencil go left to right without moving it to connect all the numbers so 1 2 4 5 3 6 7 and that's going to be the order for pre-order traversal now that's just like pre-order traversal now that's just like pre-order traversal now that's just like a quick little tip so for this what we want to do is have root than left than right so root would be 1 then we do left before we go into right so again for the left we do root left right so now we do 4 2 and then we go left before we go into right so for the left again we do root which is 4 there is no left or right so we go back up to twos right which is a 5 so now we've done root left right and then 4 here we've done root left right so we're done with the left of 1 we want to go into it's right now so again we do the same thing root left then right so we do 3 6 and then 7 so this is the answer that we would be acting for this kind of tree with one being its root to three being its left-right children and four five six left-right children and four five six left-right children and four five six seven being their left and right children and my video is kind of blocking this but it said the recursive solution was trivial and can we do this iteratively so before we do it directively let's make sure we understand the recursive solution so we're gonna go ahead and do both solutions for recursion there are two things that we want to keep track of first is the base case and the second is the recursive case so for the base case we want to see when we will exit the function at what point do we return and stop computing well that would be if there is no root right so if root is none we want to return so what do we return here well we see that we want to output a list of the values so at this point we would just return the empty list and if root is not none what do we return well here's where our logic comes in this is the new recursive case we always want to do route left right for pre-order so here what I'm right for pre-order so here what I'm right for pre-order so here what I'm gonna do is return root so whatever the value at the root is labelled plus and this is in list form because we want to output a list of values then I'm going to call this function again on its left tree so soft pre-order traversal on left plus order on rooftop right so what is this doing it continuously builds up a list and returns that so let's see with our routing one we have root is not none we return root L the value is simply one plus whatever is it is in its left and right so for this we have two so we call this function again and we call it with two and then we add that result with whatever is in theory but before we can go into three we have to solve for two because as soon as we have that we do plus and then we call this function again with its left child so for this two right here we have root being equal to - it's not none we add being equal to - it's not none we add being equal to - it's not none we add root bail so what eval is going to be appended plus its own left and right children so now we're doing two plus four plus five but before we can go into five we again have to do root out left so we go back in here root is not none we return the value of B node so that is four plus what is it in left and right so that is none plus none so when we call it with the left again we just keep going left to first right when we call it again with its left we return the empty list and that is it so when we call it with none all we do is we return the empty list so once that is done we know what to append to fours left so we've gotten four but now we can append this empty list to it right here now we move on to fours right which is also the empty list since it is none so over all concatenated four with two empty list is just four so the result for four is just the list of four now I can add this back into what was calling it was being called by twos left so this is just to concatenate it before now I go to twos right since we're done with to the left and five does it have a left to right child so that would just be a list of five so overall when two is the root we add to its value then it's left with the same function then it's right again with that same function so we get two plus four plus five and that just becomes two for five and this is the left child for one so this then goes back up into what called with two so we have one it's root value then left for one is two for five and now that we're done with its left we move on to self dot pre-order traversal move on to self dot pre-order traversal move on to self dot pre-order traversal with its right so now for three we do the same exact thing over again we do fruit left right so for that again it would just be 3 6 7 and once that returns we concatenate all of that together to form what we were originally expecting so this is the recursive solution let's run code it is accepted let's submit and it is accepted as well so now that we know how to solve it recursive Lee let's see if we can do it iteratively now how will we do this when we had the curtain we could call this function again and we could use the recursive call stack to return to the original node that was calling it so when we wanted to solve for one we would add this value to left then right but before we went into writing would solve for left and then for its left right so we had these other branches that we could always return to once we're done solving for their children but here we can't do that so we're actually going to have to make instead of a recursive call stack we're just gonna have to keep track of a stack so what a stack does is it is last in first out so whatever we add into it last is whatever we're going to operate on first so we're gonna have a stack and we're going to keep track of a resulting list because with recursion you could always build the list as we called each function but here we're gonna have to store it somewhere so let's think about this how are we going to do this using a stack well with recursion we knew what the pattern was it was always root left and then right with the side what do we want to add the value of the root and then perform calculations on the left than the right but since that is last in first out if I had a stack right here if I do left and then right I'm going to be solving on my right branch before I go on to my left so for stack what I want to do is actually want to reverse this order I want to add the right child then the left child so when I go back to the stack to solve it when I pop off the very last element I go left so what I'm gonna do is I'm going to have root in my stack resulting emptied my old stack is not empty I'm going to pop off whatever's on top so it equals stack top and what this does is it takes the value of stack stores interview and it actually removes it from sack so this value I'm going to then append to results so result dot append the value of the room and if a right child exists I'm going to add that first to the side so stack so sorry check first if root dot right is not none stacked on a pen roots top right once I have added the right then I go on to the left so if you top left is not none that root dot left once that is done I have appended right then left so each time I pop I always get left and then right once that is done all I have to do is return results so what is happening here let's run through this we have our stack and we have our result hang in and do this and stack starts off with root so we start with root while a stack is not empty we pop off whatever's in there and this root is actually equal to one so I take this off add that value to result and then to sack I added right child then its left child so I add on three then I add on two so when I go back into the sack I pop off whatever's on top which is two so I go into its left again and take off that tune add the result to result and then add its own right and left children so I first add right which is five and then I add left which is for exiting out going back in sin stack is not empty take off the top of stack add that in value to result and it's a right and left children are both none so we have nothing to add on go back in here stack is not empty take off the top which is that too result again it has no right left children just go back pop off whatever is on top and the value to result and add it's right and left children but three does have right and left so then I add to stack seven and then six going back in here take off the top take off six add that to my result nothing to add again no children go back into my while loop I have that last element in there take that off add that to result right and left Arnon go back in here but this time my stack is empty which means I am done and then I return my result which again if you see matches up with what we are expecting so let's go ahead and run this accepted let's submit one type object has no attribute Val so we're adding a none type that means we need a check here so if the initial route that we pass in is none what do we do so if root is fenomena we just return the empty list submit and it is accepted so run time and space time complexity since we go through all the nodes run time is o of n and space time we have a result where we keep adding all of our nodes that is also OFN so this is o of n run time and space time if you have any questions at all let me know down below otherwise I'll see you next time
Binary Tree Preorder Traversal
binary-tree-preorder-traversal
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
94,255,775
123
hello everyone welcome to tic this is khushal and today we will be looking at the third question of the series best time to buy and sell stock so how is this question different than the previous two questions in the first question we were allowed to do only one transaction and get the maximum profit and the second question we were allowed to do as many transactions as we want in this question we are allowed to do only two transactions let's quickly look at the question so we will be given an array of stock values and we need to get the maximum profit as we discussed we are allowed to do two transactions uh so they have also given a note that you may not engage in multiple transactions at the same time i mean uh you must sell the stock before you buy it again right okay let's see what we need to do let's look at a few examples first so for these values if you buy the stock add 0 and sell it at 3 and again buy it at 1 and sell it at 4 the profit will be 3 plus 3 6. if you try any other combination the profit will not exceed 6. so we saw these values in previous problems as well 1 2 3 4 5 so for these values if we buy the stock at one and sell it at five we will get the maximum profit for so for this example we do not even need a second transaction only one transaction will give us the maximum profit and for these values 76431 no matter how many transactions that we do we cannot get any profit as this forms a decreasing sequence all right coming to the solution so uh we are going to try to follow the pattern that we followed in the first question if you haven't watched that video i insist you watch it first all right so we'll be having an integer array in which we will be storing profit and we'll also be having two variables called minimum price and maximum profit so in the beginning we will be starting at our zero index value three so at that point the minimum price will be 3 now let's look at the profit if our value is 3 and the minimum price is also 3 the profit at that point will be 3 minus 3 0 and we'll also be putting this value as our maximum profit now we come at our first index the value still remains three so we do not need to update our minimum price also the profit will be three minus the minimum price three zero at index two we do have five as 5 is greater than the minimum price 3 the minimum price doesn't get updated now the profit will be 5 minus the minimum price 2. so we need to put 2 over here and also our maximum profit will be updated as two now we come at our next index where the value is zero as zero is lesser than our minimum price the minimum price will be updated with zero what about profit are we going to put zero minus zero over here no so what we need to do is we need to take the maximum of this value and this minus this value so here we are going to put the maximum profit value 2. as the price remains same at the next index we will put the maximum profit over here as well at our next index we do have value three so the profit will be three minus the minimum price zero which is equal to three now the profit is three which is greater than our maximum profit so first we will be updating our maximum profit to 3 and then we will put maximum profit here all right at next point uh 1 minus 0 so the profit is 1 which is not greater than our maximum profit so we will be putting this value over here as well last index the value is 4 so 4 minus 0 the profit is 4 this time which is greater than our maximum profit so first we need to update our maximum profit to 4 and then put value 4 over here all right so we were able to form an array by going left side to right side now we will be forming another array in which we will be going from right side to left side also one of the variable has changed min price has become a max price now all right so as we'll be starting from our last index we will put our max price as four and this time we will be calculating our profit as the max price minus the current price so for minus four we'll be putting zero over here now we move to our next index where the value is one as one is lesser than the max price do not need to get updated what about profit so for calculating the profit we can do four minus the current price one which is three so in the beginning we will be updating our maximum profit to three and then putting the maximum profit value over here all right so coming to our next iteration we are at value three now as three is lesser than our maximum price will not get updated what about profit so the profit will be four minus three which is lesser than our maximum profit so what we're gonna do is we're gonna take this maximum profit and put it over here following the same pattern we'll be filling the whole table so after we are done with both of these arrays what we need to do is sum the values of the same index so 0 plus 4 2 plus 4 so the value which is the maximum is our answer let's pick one of the six this one so what this means is if we do our first transaction within this range and second transaction within this range the value will be the profit will be 2 plus 4 6. i hope the logic and approach was clear to you if you still have any doubts that will be resolved while we code this all right so in the beginning we're going to check for some edge cases if my price is array is equal to null or prices dot length is lesser than 2 if that's the case we're just going to return zero okay let's quickly initialize the two iii that we discussed integer array of left profit is equal to new integer the size will be the length of prices right okay just like that write profit array let's go to new integer prices dot length okay uh we also needed two variables right integer minimum price let's initialize to integer dot max value in the beginning and integer max profit that will be integer dot min value in the beginning okay now we can start iterating through the array for integer i is equal to zero i is less than price is length i plus uh the first thing that we're going to do is update the minimum price uh main price is equal to math dot min the current minimum price and uh the value at index i okay after that we will be updating our maximum profit is equal to math.max current maximum profit and the value at i prices at i minus the minimum price okay so whatever the maximum profit that we get we will be putting that to the left profit value left profit of i is equal to max profit okay so now we will be starting to fill our right array all right so for the right array we gonna need a maximum price right so let's quickly initialize maximum price in the beginning it will have the value and these are dot min value okay we also need to reinitialize our maximum profit because that will have some previous value from the previous iterations okay now this time our for loop will start from the last index so integer i is equal to uh prices dot length minus 1 which is the last index it will go up to zero with index i minus okay uh so in the beginning we're gonna check max price into the max price is equal to math dot max the current max price and prices of i okay after max price will be checking for maximum profit match.max maximum profit match.max maximum profit match.max the current maximum profit and here the formula for max bet will be different max price minus current price all right so whatever the value we get for the max profit we're gonna put it into right profit of i is equal to max profit all right so now we're gonna get a value called maximum and we're gonna initialize it to zero what we need to do is we're going to have to sum all the indexes and get the maximum value right so for integer i is equal to 0 i is equal less than prices dot length i plus max is equal to math dot maximum of current maximum and left profit i plus write profit of i and in the end what we need to do is return the maximum all right so this seems to be all right let's try to run this code okay uh integer oh okay we have already defined this variable so double run prices sorry about that okay let's quickly submit it awesome so our code is faster than 99 percent of the solution let's quickly discuss the time and space complexity as we're iterating through the error twice two for making the other arrays and one for you know getting the sum uh the time complexity will be 3n so of n what about space complexity as we are storing n values in two arrays left and right the space complexity will also be of n so i guess that is all for this video uh thank you everyone for watching please like share and subscribe thank you
Best Time to Buy and Sell Stock III
best-time-to-buy-and-sell-stock-iii
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete **at most two transactions**. **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** prices = \[3,3,5,0,0,3,1,4\] **Output:** 6 **Explanation:** Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. **Example 2:** **Input:** prices = \[1,2,3,4,5\] **Output:** 4 **Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. **Example 3:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** In this case, no transaction is done, i.e. max profit = 0. **Constraints:** * `1 <= prices.length <= 105` * `0 <= prices[i] <= 105`
null
Array,Dynamic Programming
Hard
121,122,188,689
1,491
hey how you doing guys it's illa bella here i recorded stuff on youtube chat description for all my information i do all legal problems uh make sure you subscribe to this channel give me big thumbs up to support it and this is called average salary excluding the minimum and maximum salary get an array of unique integers salary where salary at i is the salary of the employee i and return the average salary of employees excluding the minimum and maximum salary for example we got these salaries right here and we return this output which is uh an average salary right minimum salary and maximum salary are 1000 and 4000 respectively average salary excluding minimum and maximum salary is uh 2000 plus 3000 divided by 2 is equal to uh 2500 here that's the same um the length of that salary is greater than or equal to three and is less than or equal to one hundred the value at the position of i into that salary is greater than or equal to the base 10 raised to the power of 3 and is less than or is greater than or equal and is less than or equal to the base 10 raised to the power of 6 salary at i is unique answers within uh the base 10 raised to the power of minus 5 of the actual value will be accepted as correct okay all you need is this uh double yeah double uh sum which is 0d then you create a variable which is the maximum is equal to integer minimum volume minimum which is uh integer dot maximum value then you are looking through that salaries s which is background salary and right here at each duration uh you check whether the value the current salary is greater than uh maximum salary if it's so then you update the maximum to the current salary otherwise you just ignore that and you check whether the current salary is less than the minimum salary and if it's sold then you update the minimum salary to the current salary and s plus equal and i mean sum plus equal and s you add the current salary to the sum at each duration finally return this the sum minus the maximum salary minus the minimum one divided by uh the length salary of that salary and -2 salary and -2 salary and -2 because we subtract you know maximum and minimum and that's it let's run this code accept it let's submit okay success so let's look at this example we got you know salary this array which is four thousand three thousand one thousand and two thousand uh sum is equal to zero right zero d then uh 0.0 right zero d then uh 0.0 right zero d then uh 0.0 maximum is equal to the minimum value uh minimum is equal to the maximum value we start looking through that salaries where here we got 4 thousand right so we update maximum to uh 4 000 right uh maximum yeah we update to four thousands then minimum we update to uh four thousand as well then uh sum is equal to zero plus uh i mean you know plus this four thousand is equal to four thousand then we uh are here then update maximum uh to you know maximum which is four thousand or three thousand we uh ignored that then minimum we got four and three thousand we got three thousand then uh four plus three thousand is equal to seven thousands then um you know yeah like seven thousand then um we are here and maximum we ignore that because 4 000 is greater than uh that's greater than one thousand we update minimum to one thousand then uh sum plus you know seven plus one is equal to eight and we are here we uh ignore maximum and ignore minimum and r to um eight uh two which is ten then ten minus uh you know we out of that loop and ten minus maximum which is four we got uh six and six minus minimum which is one uh thousand we got five so five divided by uh is equal to four minus two we got two right two uh five right five sum ten 4 1 yeah 5 divided by 2 is equal to 2 thousand and 500 and we return this uh double you know result that's it that's the whole problem thank you guys for watching leave your comments below i want to know what you think follow me on social medias uh follow me on instagram add me on snapchat i do all legal problems um i'll see you next time bye
Average Salary Excluding the Minimum and Maximum Salary
number-of-times-binary-string-is-prefix-aligned
You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee. Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** salary = \[4000,3000,1000,2000\] **Output:** 2500.00000 **Explanation:** Minimum salary and maximum salary are 1000 and 4000 respectively. Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500 **Example 2:** **Input:** salary = \[1000,2000,3000\] **Output:** 2000.00000 **Explanation:** Minimum salary and maximum salary are 1000 and 3000 respectively. Average salary excluding minimum and maximum salary is (2000) / 1 = 2000 **Constraints:** * `3 <= salary.length <= 100` * `1000 <= salary[i] <= 106` * All the integers of `salary` are **unique**.
If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too.
Array
Medium
319,672
1,647
Hello everyone welcome to my channel, we are going to do video number 17 of our greedy playlist, lead code number is 1647, there is not much to do, it is very simple, this question is going to be minimum delicious, you make character frequency equal, do you understand, question what to say, it is six. He has given you this string S. He is telling you that a string will be called good only if the frequency of all the characters in the string should be different. The frequency of the different characters in this string should be different. Only if he takes this string as good then life will be saved. String S gave you the extreme return D minimum number of characters you need you delete you make S good Okay now look at this example here there is only one frequency two and the frequency of B also becomes two this is not good right now Meaning, the frequency of different characters should be different, so delete one of them and make it two. I deleted A and made it one. Now see, the frequency of both is different. Okay, so the answer is how delicious we made one. So the answer will be one. That we had to delete one character. Let's come here, look at A. B. What is the frequency of A? The frequency of B is one. The frequency of different characters is different. So now this is an already good string. Okay, so delete something. There was no need to do this, now look here, pay attention to this is a little important example, now look, it is an obvious thing, first one has the frequency of all, now if I delete one, then it becomes one. I delete this also. If both of these happened, then I delete this also. What did I do? The answer is five. Now this is a good string. In this, C has come once and D has come twice. So first its brooch band. Let's see, look at the approach band, friend, pay full attention to the process, how it reduces my thought process, then you definitely understood this thing in the example, you need the frequency as possible, right, so you will have to store the frequency, without that you will If I can't do anything then what will I do? It is given in the question that from this English letter of all the lower ones, I will take one of size 26. And you know that the frequency can be stored here, zero one you and so on 25. What is the tension between us that if this frequency guy is sitting here then I don't want any more frequency guy from this right? We have the same tension, neither do we store the story nor buy a set here. But let's make a noise about which frequency he has already met, okay then let's start, I came here, I saw that you are the frequency, so are you the frequency, have we ever seen anyone before, if we have not seen any person, then it is good. It is not necessary to make it delicious, but here I write that yes, you are a person with frequency, we have it, okay, now when I came here, I saw, okay, his frequency is two, is he a person with two frequencies? Already, we have it, yes. If you can't keep two then I will try You are visible to me here, you are a person of frequency, I have you already It's okay here, it's zero, friends, will you put this on the set, it's zero, that means it's been deleted, now that character has been deleted, [ __ ] him, now that character has been deleted, [ __ ] him, now that character has been deleted, [ __ ] him, now it has come here, then show it to me, it's already on the set, okay, so I have Tried to reduce it, made it one is also already on the set, if it becomes zero, then you must do something, it is not necessary to do, what does it mean that this character itself is finished now, okay, in the future, all are zeros, so those with zeros. Ignore, we have to kill like this, our story will end, we will kill the entire travels, when I am out of bound, then okay, see how much was the total delicious, then it became five delicious, this is our answer, we will read by deleting so many characters, okay, it was quite simple, so see. So, what we have done here is that we have taken a vector named frequency whose size will always be 26 because in the question we have given that the lower English status is there, the space complexity will always be one, which is fine here, but we have also taken set. Okay, let's do this one quickly. After that, we will do approach, you will come up, so let's finish coding approach one. After that, approach, you will come up. Okay. First of all I had said that the frequency will have to be stored, it is of size 26 because it has been given in the question that all the lowercase English letters will be ok. Answer on OK, I have done plus in the result, I will keep storing how many delicious items we have to do and remember, we take the take from those orders so that we can store which frequency we have already seen, ok, Ville. Frequency of I, it should be greater than zero, right, if it is equal to zero, we will not do anything to it, okay, it should be &gt; 0 and if this frequency is should be &gt; 0 and if this frequency is should be &gt; 0 and if this frequency is frequency of I, it is okay, already we have seen, I will notify you on the set, reduce this frequency. I will try to do frequency of -=1, which means I frequency of -=1, which means I frequency of -=1, which means I will keep decreasing by one and if I am going on decreasing means I am deleting, then I will keep changing the result to plus, okay then as soon as it comes out, I will insert it in the set. The result is okay, it was quite simple. We have done exactly what was told. We have definitely passed how using power first approach. Repeat here again. Look, first of all, it should be greater than zero. Second, if we have already seen that frequency on the set, what does it mean? I have seen that I am trying to reduce it, first there was 'T' then 'one' was added to it and the result was ' was 'T' then 'one' was added to it and the result was ' was 'T' then 'one' was added to it and the result was ' delicious', if 'one' was also present then delicious', if 'one' was also present then delicious', if 'one' was also present then see 1 - 1, it becomes zero, okay see 1 - 1, it becomes zero, okay see 1 - 1, it becomes zero, okay then let's solve the result in a separate set. I had to take the right, I want to see if we can make it even without a set, let's try it. So friend, this is an example, the frequency of 'S' is also two, it is frequency of 'S' is also two, it is frequency of 'S' is also two, it is clear, now see, after this, we have to do it, okay? Now what will I do, I will first sort it, what is the benefit of straightening it, I will also tell you, look mother, I have shortened it, okay so hero one, three and so on, okay now see sort. Let me show you what will be the benefit for me by doing this, here let's race it first, yes then indexing is done with zero, here 25 26 24 23 and so on, okay now see, everyone has been sorted in ascending order, so 2 Here rest all were 00, right, they will be left behind here, it is clear here and it is given in the question that you can never add an extractor, you can always delete it, right, we start from the biggest one, right here. Let's start from here, we have sorted in ascending order, then the bigger values ​​will be at the last place here. Okay, so we will then the bigger values ​​will be at the last place here. Okay, so we will then the bigger values ​​will be at the last place here. Okay, so we will start from here. Right till now, it is clear, we have done the sorting and here we will think but, what is its size? If it is 26, then 26 people are 6. It would seem that this has also happened constantly, if seen, then look friend, I know the benefit of sorting, why did I find the zero just now, leave it now, look at these carefully, I will write them down once separately and show them to you here separately, just because. I am writing this so that you can visualize it better. If you are zero then I will ignore it anyway. I am trying to understand you by writing this separately. Okay, see what is the benefit of sorting me by all the frequencies. Look, all the ladies will be side by side, won't they? All the ladies are side by side because you are next to you and so on, it's okay if you take mother, I am here, if you take mother, then I am here and I + I if you take mother, then I am here and I + I if you take mother, then I am here and I + I can compare in 1 that ok i and i+1 are can compare in 1 that ok i and i+1 are can compare in 1 that ok i and i+1 are equal. Okay, so those with equal frequency will be side by side. If one i is pe, then one i+ one i is pe, then one i+ one i is pe, then one i+ will be consecutive. So I have seen the benefit of sorting. I should start with the egg. That is right, so there is something in India's adjustment, otherwise, no problem, we will start from here, this is 25, Thane 24, 23, so we will start from A = 24, okay, let's start from A = 24, okay, let's start from A = 24, okay, let's take it here and here I am a result. I am late in which what will I store and how many characters have to be deleted? Okay, so see, it must be very simple. Now you have seen I have compared I, rectangle character and I plus one eight character, see if it is equal or not, then I. What will I do in this rectangle character, will I add a ghat in it, what will happen if I add a ghat in it, one will go, this is ok, so what do I do, I will just write one in the cat's place, how many times will I have to delete it, sorry here. But let's go back to this, pay attention where did we go wrong, when I came here, I became happy here, I did not do three, maybe four, okay, we will not be able to do it like this, okay, so pay attention to one thing. How should we approach this? How should we fix this? Look carefully at this mistake of ours. When did the trouble happen last Sunday? When I was here, the trouble happened here. We were happy here that I came and I + 1. Whatever that I came and I + 1. Whatever that I came and I + 1. Whatever this is you and this is one, so we were happy here but here it is like this, it does not have to be handled, look, we know what we will check here, if the frequency of I is okay, if greater than or equal, you become the frequency. Off I plus one is okay which is look at how in this we have a frequency of vice is two and this is one ideally this should not happen because ascending order is right meaning or plus one should always be bigger but here it is smaller. It means something must have gone wrong, so how do we have to catch it in the same way, we have to catch it in the Greater Dane Equal Tu too, okay, we have to catch it in the Greater Dane too and the Equal Tu also have to catch it, okay so the Greater Dane Equal If the frequency is I + 1, then think like this, If the frequency is I + 1, then think like this, If the frequency is I + 1, then think like this, I cannot simply subtract one from 2, then one will go to A, then again it will be equal to it, then do you know what I will do, whatever is there in I plus one, what is one? Right, I will subtract -1 from it and put it here. Okay, Right, I will subtract -1 from it and put it here. Okay, Right, I will subtract -1 from it and put it here. Okay, I mean, what I am saying is that the frequency of I knows what I am going to do. I will do this by adding minus one to whatever is there in the frequency of I plus one. What is the benefit of subtracting one from what is there in i plus one? What is the benefit of subtraction that i will no longer be equal to i + 1 because if this i no longer be equal to i + 1 because if this i no longer be equal to i + 1 because if this i is one then if you subtract one from it then now it is the same thing. And it will be right, it will not be equal to i + 1/3 minute. Look, not be equal to i + 1/3 minute. Look, we are not making the frequency of A plus one equal to one. We are writing it by doing minus one, so it will not be equal in frequency. Okay, and what will happen to us is one more thing. Ascending order will be maintained, Saturday will be maintained because look, I am putting an element smaller than this here, then if necessary, I will put an element smaller than this here, then I will put it here, that means I am saying that ascending order has to be maintained because why should there be a last time problem. Had gone because look, it was you, then there was one, then again you became you, it is visible a little, I am not maintaining ascending order, this is what was going wrong with us, so what am I doing now, not frequency of I to frequency of I What I am doing is that whatever value is there, I will put -1 in it, whatever value is there, I will put -1 in it, whatever value is there, I will put -1 in it, then I will put zero here, okay, earlier the value was 2, so I have written the previous one, it is okay and now what I have done is that the frequency is 5+. There was also value frequency is 5+. There was also value frequency is 5+. There was also value in it, after dividing it by mincing one, what was the benefit of that? Here the order is maintained. Sending order. If the order is maintained then it means that the elements will not be equal. It is definitely okay. So how delicious we have done. Let us see the result plus it is equal. What was your value earlier? What happened now? Take the frequency of both. Take both of them and you will know how delicious it is. The frequency of I is ok till now, so let's reduce it. Do you understand this? Will you understand that this was important? Okay, I am making a big bulb here, so that you can understand that it was very important. I will make a flower diagram in myself, taking the logic from the very beginning, also see 5 + 1. Will this condition be passed? Yes, also see 5 + 1. Will this condition be passed? Yes, also see 5 + 1. Will this condition be passed? Yes, there is vacancy. What will be added in the result? Frequency will come first. What was the value? What was two? Was it two? Now what has become of one? How delicious it is. Had to do a presentation, so I added one in my result. Okay, now see how it will reduce like magic, okay? Why did I do this by comparing it with I Plus One, why did I write Greater Give Equal, because Greater Give Equal, you were here, remember the last time, don't see, just now, I am here, look, you are here, this one is gone, it is messed up here only. Is the sending order finished? Okay, now see it has come. Is the frequency of I greater than the frequency of I plus one? Give it equal to you. Yes, this time look, the greater one has been placed. Okay, so what is the previous value? So the frequency is two. What is the frequency, see what is there in I plus one, okay, it will become zero is important here, okay here, it is very important, pay attention, what is the frequency of I plus one, brother, if it is zero, then see, greater den equal you. The following condition will be true, give it greater, it will become true because look at the frequency of i is two, i plus one is zero, give greater, tu is equal, ok, frequency of is ≥, then let's see frequency of is ≥, then let's see frequency of is ≥, then let's see what is the value of frequency of i, ok, given two pulses. Given two pulses in the previous, what will I do with the frequency of I? Whatever frequency it is, if you add minus one to it, then what will be zero minus one? It will become -1, so do -1, so do -1, so do not add minus one here. Now you are concerned with this, how much is the max? You can reduce it to zero, you can reduce any frequency, it is okay, so do n't directly write minus one here because negative can also go, like right now we are going negative, so I don't know what to do here. Look, pay attention, if it goes to zero then let it remain zero, if not then it is okay. Whatever value was there in five plus one, put -1 in it. If -1 in it. If -1 in it. If it goes negative then the answer will be zero sign, hence max has been put here. But okay, then look, pay attention, what is the value of five plus in pregnancy, it is zero, do minus one in it, minus one, no, minus one, if it is negative, then do not put negative, add zero, it is okay, till now it is clear, it is good, so is the previous one. What was the number of rectangles? What did it become now? What has become of zero? How delicious is it? Had to do a presentation? Plus you got the answer, five came, now it will come here, the story ends here, I am fine, this is a very good technique, it will work fine and every one of you. You should know the meaning of each and every thing, right? Why did this one happen? Why did Greater Dane come here? You should have understood that too, that's why I have done complete driving. Are you okay with this? So Almora, we have almost written the complete code. This code is important. Okay, let's do it quickly and finish it with the approach itself, so let's do it with our approach too, the frequency will have to be stored, otherwise in that code today I will write it here, store the frequency here. Okay, after this, remember what I said that we are going to sort the rays with frequency, we will short them only if the result is greater than zero. If you sort, what will happen is zero comes last, you are here. If I get any zero for free, then all the zeros on its left side will be either less than that or not and it is not necessary to know the left hand, why do I have to see the zero and its left side too? If you go then you will get only 0, hence the frequency is off, if not ≥ 0 then frequency is off, if not ≥ 0 then frequency is off, if not ≥ 0 then break it with foreloop which is fine and the frequency of I should be greater than zero. Okay, now how do we write the same here, frequency five if greater. Give equal, let the frequency of i plus one become greater. Why is it written? I told you that too. Right, first let's check that whatever value is there, first store it and let it go. Okay, we will make it -1 and we will keep its value only. Till now it is okay, the frequency of I has been updated, okay what to do in the last, return result, okay after submitting, let us see, hopefully, they should be able to pass which date cases using and approach you also India's way how to solve this question. Wizard using hashtags. Okay, here we have done the sorting. Here, we have maintained the frequency. Okay, look at the frequency too. It is one of one, because there is a constant size of 26 sizes, so it is a fan space. If you look at it, then it is also in the sorting. O Off one felt because it is of constant size, it is ours, it is okay, so I hope I was able to help, there is no doubt, there is comment area in radium, ultra C U gas video, thank you.
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
230
what's going on guys today we're doing leak code problem 230 K smallest element in a BST this is a medium problem given the root of a binary search tree and an integer K return the K smallest value one index of all the values of the nodes in the tree okay so first things first um we got to make sure we understand the problem so we have the root of a binary search tree and we have some integer K so we need to return the K small value so if they give me uh one that is I need to return the first smallest value in the tree so in this case that's one if they give me three I need to return the third smallest value so one is the most small then two then three so three is the third smallest value so the output is three so when first when you first see this problem um I think one natural um intuition you might have is okay well if I can find some way to iterate through all the nodes in the tree as I hit each node I can store its value in an array um and then once I have my array um I can separately just sort the array um and then once it's sorted in ascending order I can easily find the K the smallest value and that's not a bad strategy um that can definitely work but um sorting is takes uh time complexity of n log n because that's what merge sword is n log n and we can actually do it um a little bit faster than that if we utilize a property of binary search trees so um the trick to this problem is knowing like knowing how binary search trees are structured and the way that a proper binary search tree is structured is that we have a root node and then every node in the left sub tree of that root has to be smaller than this root node similarly every node in the right sub tree of the uh every node in the right sub tree has to be greater than the root node and this is consistent not just with this initial root but when three is the root the same thing applies so this two and this one have to be their values have to be smaller than the three and then of course this four has to be greater than the three Okay so if you know this um if you know this to be the case then you can sort of intuitively I think understand that okay well the very smallest value is going to be all the way to the bottom left um so it's that one and then the next thing you can realize is that if we Traverse through this tree um just going gradually basically moving to the right through the tree um we're just going to be going in order well and so what you find is that you want to do an in order traversal of the tree um so there's for doing a depth first search you can do um a pre-order an in order and a post do um a pre-order an in order and a post do um a pre-order an in order and a post order to go through the tree and um really quick just want to iterate or explain what those are so um if you already know then you can fast forward a little bit but I'm going to explain pre-order um we have the root followed pre-order um we have the root followed pre-order um we have the root followed by the left sub tree followed by the right sub tree okay in order um is left sub tree root and right sub tree and then post order is left sub tree left I'll just say Left Right subt tree and then root is last so noticed how root is the only thing that's really changing here it's always left then right um but root can either be at the start the middle or at the end and if root is in the middle then that's in order meaning we're going to go from the smallest all the way through the highest values um so it's worth knowing these three things um if you don't and I would encourage you if you're not comfortable with this there's um there's actually a really great video that I found that explains intuitively how these make sense um I'll link it in the description but yeah with that said we would like to do an in order traversal so let's get started with that um and so actually something else I want to do is um I want to make a separate um method for the in order traversal and as I go I'll try to explain why I'm doing that um but for right now just Just go with it I guess okay and we're going to be doing an a recursive in order traversal because I find the recursive for depth first search the recursive Solutions are really pretty straightforward and simple well not straightforward but they're clean at least um they can be a little mindboggling okay so for the in order traversal um what do we want to do uh well first of all we don't really want to we don't need to return anything here um we still need the root we don't actually need k for this in order traversal either um oh okay I remember exactly why I made a separate function here it's because uh I want to make the separate function because it in this I basically just want to return um let's like whatever the answer is it's not going to be this but I just want to have a simple function that Returns the answer so inside my function I want to call the function that finds the answer and then I just want to return it I don't want to have to deal with returning the answer inside of the recursion because it'll be a little bit messy in my opinion um so with that said uh what are we going to do we're gonna well basically we want to do this recurs recursive in order traversal and we want to store um the array as we go through the inorder traversal so I'm going to make a an empty array here and then I'm going to call um self.in order traversal um and that's going to be on root and I'm also going to pass in the array which means I'm going to have to add it as an argument here um so list of ins awesome okay so now how do we do the in order traversal um well first things first is we want to establish a it's recursive and we need a base case so I'll say if not root um then return just exit out of our function so I want to call um in order traversal on um root. left oh I knew I messed something up here I can't just say this I have to actually give it a name um so I'll just call it um I'll label it clearly I'll be very verose about it so it's clear what's happening so in order array um which is this array um just for abundant Clarity we'll rename all these two in order array so what do we want to do what well we want to um we want to add items to this array in order so let's actually let's just break down what's going to happen when we call inorder traversal on root. left so we're start um first of all we're starting with just the root okay so that's right here look at this five um we say if not rout return but spoiler alert we're not hitting that so then we call in order traversal route. left so now we're on to the three and then same thing we're not hitting the if not root so we're down here and now what happens when we hit um the child of this well we hit this if not root so we return so now we're back at this quote unquote level of the recursion right here for this one so what do we want to do now that we're actually inside of that well now we want to append that number to the array so we want to say in order array do append um root which is the root that were're on root. V so the last thing that we're missing is the traversal for the root. left or the root. right um so we're starting at the five we're going here we're checking the left child there is no left child so we're returning and now we've appended this one and now after we've appended this one we call in order traversal on the root. right but that's also none that doesn't exist so we just return so now the recursion the recursive stack quote unquote is going back up to the two and so we're calling this line aend the two and then again in order traversal on the root. right but that's just not an existent so we just return okay so now we're at now we're the recursive stack is tracing back to the three and we're appending the three to our array and then see now that we've appended this one we're doing we're looking for anything that could be you know slightly greater than it and this is the thing it's going to be slightly greater but it's not going to be greater than this because that's how binary trees are structured this entire sub tree has to be smaller than this five so that's why the four is the next highest value so uh that so we're doing in order to on root. right which is the four that means we're going back through this function we're not hitting this we're calling it on root. left but that's just going to return then we're appending the four and then we're calling it on root. right which returns and now the recursive stack just finished doing what it needed to do for this three so now it's going to this five okay and so and actually on that five we just finished our entire traversal for root. left which was the three so now we're hitting in order array. append and we're appending the five and then finally we're calling in order traversal on root. right which is this we're appending this six and then or but I'm shouldn't say we append it yet so we call in order traversal on the six it's not the root we call in order traversal on the left child of the six which is non-existent so it returns six which is non-existent so it returns six which is non-existent so it returns so then we call append the six value and we call in order traversal on root. life root. right which is non-existent so it root. right which is non-existent so it root. right which is non-existent so it returns and so now we've just gone through our entire binary search tree and we have made a list of all the elements of it in order and it's O of n because we just went through it um we just went through each node and we only iterated once yeah so that's our in order traversal so um so the cool thing is that we call the in order traversal and we're actually we're literally passing in this in order array so all the changes that we're making to the in order array are actually affecting this in order array it's not like different if that makes sense you're actually changing the values in this so what do we need to do now we have our array in order and we need to return uh in order array and we want to return well we know the first element is the smallest right and then the last element is the largest so the K smallest element is just the K element except for the fact that we have to remember that it's one indexed it wants me return the K the smallest value and let's say k is one so it wants the first smallest value if I return in order array of one then I'm actually returning um you know the second smallest value because arrays start with an index of zero but if I do K minus one 1 minus one then I'm returning in order array of index zero which is the actual smallest element and so as you can see this is what we want to return um so with that said let's run it and see how it goes runtime error classic so very important got to put self um I could copy and paste but I think it's faster just to type it real quick all right let's run it again runtime error oh and another thing in order traversal requires this in order array as an argument so foolish me thinking that I don't need to pass it in every time um be better than me don't make these mistakes or do and learn from them which is what I should do um just make sure your parameters match the functions you call and use self let's run it again and it's a runtime error oh because this is just a this oops this one doesn't need it this is just root. Val this is just a pending to the array so let's run it again uh it's good to be able to figure out your errors solution object has no attribute in order array oh again it's not self because it's a parameter sorry we only need self when we're calling the function which I knew I just didn't notice yay accepted on the test cases let's submit it and cool now you'll see it beats 39% it and cool now you'll see it beats 39% it and cool now you'll see it beats 39% which might not seem good but if I submit it again it should be different because it's pretty random now beat 70% because it's pretty random now beat 70% because it's pretty random now beat 70% we are killing it we're crushing it so that's a lot of nonsense but hopefully this explanation made sense thank you so much for watching
Kth Smallest Element in a BST
kth-smallest-element-in-a-bst
Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_. **Example 1:** **Input:** root = \[3,1,4,null,2\], k = 1 **Output:** 1 **Example 2:** **Input:** root = \[5,3,6,2,4,null,null,1\], k = 3 **Output:** 3 **Constraints:** * The number of nodes in the tree is `n`. * `1 <= k <= n <= 104` * `0 <= Node.val <= 104` **Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST).
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
94,671
767
because 767 reorganized string um asked by many companies tops like fang companies especially um question is given a string s check if letters can be arranged that so that two characters are adjacent that are adjacent to each other are not the same if possible i'll put any possible result if not possible return to empty string so example a b um i'll plus a b a because we do not want the a's to be adjacent to each other example two aav cannot have a valid output so the output industry and this is because no matter how you organize it and a will be adjacent to another a and so this might seem like kind of a confusing problem but actually once you notice the pattern it becomes very simple basically in order to optimize your result you want to get rid of the letters that appear the most first right so for example in the first example a appears most so you get rid of an a first right and then you get rid of the next most appearing letter which is b so b and then you get rid of the next most appearing letter which is a again because there's only a left and if you think about it this makes sense because if you have like a lot of the same letters you want to get rid of it first in order to maximize the potential that you won't have an adjacent letter that is hitting each other later on in the string and whenever you hear the word frequent in coding immediately in your mind should be heaps like anything with top k frequency like problems can almost for sure if you solve the heat so that's one programming tip i have given you or like i'll give you um so how to do this problem then well we need to find the frequency of all the letters first and then like we said before we take the most frequent letter put it in our result string right we pop that most frequent letter out of our maxi and then next letter should be the next most frequently letter that's the next most frequent letter so we look at that one put it that in the string and then while we do that we push the most previous frequent letter back in so why did we pop that out in the first place because after you use a letter you don't want to consider again consider it again for the next possible character in our result string because we don't want the same letter to be adjacent and appearing twice together got it so we have a letter that is most frequently appearing which we have just popped off the heat we put out the front then we put the next most frequent letter next to it and when we do that we push the previous letter back onto the heat because now that we have two non-adjacent characters two non-adjacent characters two non-adjacent characters we want to re-consider we want to re-consider we want to re-consider that first previous character that we have just popped off so we want to continuously consider it still um okay so let's get right into the code and i'll be programming python by the way it's um okay honestly i don't know why that was red right there but i'll try to make my code very readable and then you guys as programming amazing programmers can try to you know simplify it or like decrease it later if you want while you're practicing but for now i'll try to make it as readable as possible to for anyone to understand so first i want to build a frequency dictionary which keeps track of how many occurrences of each character occur in our input stream so we have our frequency dict and we just count the letters that appear in our original string and as always if it's already appeared we just press one otherwise we initialize the two on okay so now that's done our next step is a max heap so we initialized by here oh don't forget to import i already did cool okay yeah so don't forget to import that though um not really important for whiteboard interviews to import but honestly with covid and remote interviews i've noticed a lot like a lot of my interviewers have been asking me to run my code so if it's breaking randomly it just might be that you have forgot to import something so we want to add everything to the max heat so here we'll be looping through the frequency dictionary and pushing the frequency and letter onto the backseat and remember all heaps are inherently min heaps so the easy way to fix that and make it a max heap is simply to negate whatever value you're putting in so that is why i'm entering and pushing in negative frequency so now we want to initialize our result and remember in our discussion we wanted to keep track of the previous letter and previous count because we always want to push it back into the heap after we have considered the next one so we have previously equals nine priests account equals zero and while there's items in our max heat we can extract the frequency and letter from like the most frequently appearing like we can extract the most frequently appearing letter and its frequency from the max heat and we just want to append it to the result okay and after we repent it don't forget to decrease the frequency because we have gotten rid of an occurrence of it and because it's a maxi we plus one because of our whole opposite negation thing and then if previous count is not equal to zero so if there is such a previous character that we have considered earlier and it still has like it still exists and has a frequency of above or equal to one we want to be able to put it back into our heat and reconsider it right so um oh yeah okay so then we want to push it back into the heat basically okay and then we want to set our current one to be the previous is wait okay yeah and then at the end because of our results array we just join it and make it a string and then at the end remember there's like cases where there's no valid arrangement so if the length of a result is not equal to the length of our input we can just return an empty string otherwise we can return that result so let's hope our code compiles oh of course it never does in the beginning okay for letter ms um wait return oh return nice so at least that test case worked and then when you submit it's accepted and honestly yeah it works and i believe the runtime of this is o of n log n where n is the number of characters in the input stream so yeah good luck to everybody and you know give this video a like subscribe if you want to um also if anyone actually does watch my video which i know i'm not like a programming youtuber or anything like literally it's my second programming video um i kind of want to know how everyone's recruiting is going so you know leave a comment about your recruiting journey during covet 19 down below um yeah okay thank you so much and i'll see you the next time i'm bored at night
Reorganize String
prime-number-of-set-bits-in-binary-representation
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
Math,Bit Manipulation
Easy
191
1,601
hey everyone today we are going to start with a little question maximum number of achievable transformities so you are given RI request and this is a transfer request from like a building from to building I so index 0 is uh from building and the index I is a two building so all building are full so a list of requests is achievable only if for each building the net change in employee transfer is zero so that means so let's focus on the first two requests so first request is like a person want to move from building zero to building one right in that case um reduce the number of people from building zero so minus one and uh increase the number of people in after building one so plus one right in the next request is person wants to move from building one to building zero so in that case reduce the number of people at building one so zero and increase um number of people at the building zero and zero so in this case we can keep the number current number of people at all buildings right so this question asks you about how many liquids you can accept to keep the current number of people at all buildings okay so let me explain with this example and N is a number of buildings so in this case five so first of all we try to accept or decrease six requests so before we check I try to create a unique subset with length of 6 from 6 requests so that means um all requests right and uh um the value of subset is a index number so that means zero one oops one two three four and a five okay so let's see the result um if we accept all requests so we accept from 0 to 5 so if we accept zero so people want to move from zero building to one building and I create a list with ranks of five in this case so number of building so and the initialized to be zero and each number is like a number of people at each building and when we accept zero request so people wants to move zero building to one building so that means so zero in at index 0 should be -1 and so zero in at index 0 should be -1 and so zero in at index 0 should be -1 and the one building is a plus one and the next request is one so one zero so person wants to move from building one to building zero so that means so index one will be zero and then index 0 will be zero right and the next request is two so from zero to one so zero minus one and the so you know building one e0 and everything beginning being two is one and the next three case is 4 and the two zero so building two is zero and uh building zero will be zero and the next three case is five and three four and uh in Building C minus one and everything four is one and then we finish iteration and we accept all requests so look at the result so fast three buildings looks good because a number of people's so we keep the number of people with zero right but I look at everything three and the buildings whole so minus one and one so we can't keep the number of people right so in this case we cannot all request like a six requests so that means six is not answer so let's try uh to accept like a five request so in this case so everything a reset oops and zero here so before we check the result so we try to create a subset with links of five from six requests so there are many right so one possible unique subset should be zero one two three four and another possible unique subset should be zero one two three five and then another is zero one two for Y and something like that and so we create uh all possible unique subset with ranks of five from six requests and then we take one by one so if we take this subset we accept so request zero request one this two decrease three degrees four and the next um subset is zero one two three five and next is zero one two four five something like that and I think uh this is a answer subset so let's check quickly so zero one so minus one and the next because this one so zero one zero and Z1 so minus one and the one and uh one two so one e zero two is one and the next is equals four zero one two c four this one so two zero so zero and uh zero and then finish so um after we accept all requests from zero to four so we can keep the number of people at all buildings right zero so that means we can accept these five degrees so that's why output should be fine in this case yeah so that is a basic idea to solve discussion so with that being said let's get into the code okay so let's go first of all inside this list and the combinations in size with list and we try to accept all requests not fast so that's why we start from recordings or public list until zero and reduce one by one and the first of all create a subset so generate subset and start from zero index and the anti so how many or decrease so passing the client request and let's create a generate subset and a start and let's say the name so if remaining equals zero so append current subset to combinations so append and the subset in the column so I don't explain detail of like a creating subset so I put the Link in the description below so actually I solve the subset question before and so return for I in range and start to ranks of requests so subset append and the index current index number so generate subset and the I plus 1 and remain in minus one so plus one minus one and then after that subset dot pop and then uh I think we can create a unique subset and then so after that so this combination has a unique subset so because here and then so for um so for combination in combination and then let's create like a beer pin and initialized to be zero multiply 10 so ranks or number of buildings and then for index number in C and then we do things and then requests so current request and zero is from building right from building so people move out so minus equal one right and then two building should be one right so we have to press one so that's y plus one and then after we finish all movement and check um number of people at all buildings so if not any buildings so in that case so that means if all we keep or of TV keep or a number of people at all buildings in that case we should return request and if not the case we should return yeah so let me submit it yeah looks good and the time complexity of this solution should be order of n plus M multiply 2 to the power of M multiply M so where N is a length of number of buildings and the m is a number of requests and the space complexity is order of M or order of n so yeah m is a number of requests and M is a number of buildings yeah and uh this is a little bit slow and I think I can improve the time complexity but I use a building function in Python so I think I use in your interview you need to ask um if you can use the building function or not if interview are set you cannot use a building function use this solution but uh interviewer said you can so I think a next solution is a better than this solution okay so let's raise a call first of all for request in range and the ranks of the twists and from latest to zero and reduce minus one and then I use one more four for combination in so I use a building function it did I don't know how to say how to call this function and the combinations and there ends in the rings of requests and a request so after that building equal and zero multiply n and therefore index number in C combination so we will be building is so current index and the zero so from building R minus 1 and the building requests current index and the two building so one should be plus equal one and then if not any building in the case with um request if not the case just return zero yeah so let me submit it sorry this is yeah so let me submit again yeah much better right beat 74 percent so yeah I'm not sure you can use this splitting function in their interview so you need to ask before use this function yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
Maximum Number of Achievable Transfer Requests
maximum-number-of-achievable-transfer-requests
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`. **All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`. Return _the maximum number of achievable requests_. **Example 1:** **Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\] **Output:** 5 **Explantion:** Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. **Example 2:** **Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\] **Output:** 3 **Explantion:** Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. **Example 3:** **Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\] **Output:** 4 **Constraints:** * `1 <= n <= 20` * `1 <= requests.length <= 16` * `requests[i].length == 2` * `0 <= fromi, toi < n`
null
null
Hard
null
890
Loot Hello Guys Welcome Garden Kashmir They Will Discuss Please Like This Question More Thursday Subscribe This Video Please subscribe And subscribe The Amazing spider-man And Subscribe Health And See What Is The Question Have A Doubt That 92 Pattern Women And Will Be Checking Apps for every vote counts but subscribe now to subscribe button more parts after any point presentation of but will have to subscribe unnecessary chapter notes BRC in this world look into different subscribe The Channel Please subscribe And subscribe The Amazing and subscribe Midning Middling Property Question President Dr Budha 121 Relationship But Widow Pension Properties Loot Meaning Attractive World Channel Subscribe Button To Subscribe And subscribe The Amazing The Current President Thursday Loot And They Are All Sorts Time Till That Particular Road Near Resultantly subscribe The Video then subscribe to the Page Isn't it a minute later Operation Every Word Expensive Twitter Patan Su Distic Listen to my voice messages Famous poet Neetu Data Structures These robbers did ok on Thursday Mahesh Chand left the shop Second World Will Continue To Work S Letter Verification 826 Length Of Non Electronic Clever to do take care of defense subscribe appointed subscribe to hua tha tension will check f-35 printer not hua tha tension will check f-35 printer not hua tha tension will check f-35 printer not present 128 206 hai aise mili android 2.1 a kyon na ek dam aap and pattern to but did not match with vote and ping in water In the Yash half not mid returning return must subscribe 108 successful knowledge Sameer and set alarm successfully addressed time complexity in this question in half subscribe to Ajay
Find and Replace Pattern
lemonade-change
Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**. A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word. Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter. **Example 1:** **Input:** words = \[ "abc ", "deq ", "mee ", "aqq ", "dkd ", "ccc "\], pattern = "abb " **Output:** \[ "mee ", "aqq "\] **Explanation:** "mee " matches the pattern because there is a permutation {a -> m, b -> e, ...}. "ccc " does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter. **Example 2:** **Input:** words = \[ "a ", "b ", "c "\], pattern = "a " **Output:** \[ "a ", "b ", "c "\] **Constraints:** * `1 <= pattern.length <= 20` * `1 <= words.length <= 50` * `words[i].length == pattern.length` * `pattern` and `words[i]` are lowercase English letters.
null
Array,Greedy
Easy
null
213
welcome to october's leeco challenge today's problem is house robert two you are a robber planning to rob houses along the street each house has a certain amount of money stashed all houses at this place are arranged in a circle so that's going to be the difference between house robber one and two so that means the first house is the neighbor of the last one so there's a security system where it will contact the police if two adjacent houses are broken into on the same night we want to try to find the maximum amount of money we can rob without alerting the police right so normally when you solve this problem it's a dp solution basically what we'll do is have a array or that's going gonna store the amount of profit that we could have made the two previous houses before the total amount of profit so here it starts off with zero right now at one we're going to ask ourselves should we rob this house and take the profit and the profit from two houses before or skip this house and take the profit that we made from robbing the house uh previous so here they're both zero so it doesn't matter we're just going to rob this house and at two this is where we ask ourselves should we rob this house and take whatever we had two houses before or take what we had one house before so here we can see clearly we want to take two now what about three should we rob this house and take this house profit here that's gonna be four or should we take this profit and that's two so obviously we'll take four and here we'll say okay should we take the profit from here and get this profit or should we take that profit from the house previous and four is larger than three right so uh we'll take four and we just return that's going to be the total amount now that's the solution to regular house robber but how would we do this if there was a circular house houses involved well the basic idea is since then we're not going to be able to rob the first house and the last house right so all we really need to do is go through our list twice with the first one starting from the first house and skipping that last house and the second pass starting from the second house and going all the way to the last house and that way we'll take care of that weird edge case where we can't rob these two end houses before so let's start off by just initializing our first solution what we'll do is first take care of some edge cases we'll say if not nums we return zero and if the length of nums equals one then we should just return whatever is in nums now we'll we could use an array but i'm just going to use two variables because we only care about the last two positions and we're going to shift it inside of our iteration so for n in nums we will first store our dp one because dp1 is the house previous and dp2 is going to be two houses previous and we want to shift that as we go along so we have to store this dp1 in case it gets updated so dp1 now get the max between dp2 plus profit here or should we keep dp1 and the reason i stored dp1 as a temp here is because it could get updated right we don't want that to happen because what we're going to do is update dp2 to become dp1 so we need to store that information from before okay so once we finish that we can just return vp1 and this here this year we get four right but this isn't right because what this is the first run thought was well we should rob this first house and last house but we can't do that remember this would work in the first house robber but second house however this doesn't work so again what we'll do is go through it twice we'll just have the same algorithm here what we'll do is call these something else dpp and we turn the max between these two but for this one we will only go to the second last house and for this one we'll start off with the second house and that way we can take care of that weird situation where we don't we can't rob the first and second house so this should return three it does it's going to submit that and accept it yeah so once you um i mean at least the hint is in here basically if we can take care of this problem where uh house we can't we need to figure out uh should could we rob either house one and um this second to last house or should we rob house two and the last house after that the pro problem gets degenerated to the regular house robber so if you know the solution to the house robber you should be able to come up with some way to do that there are some other ways but this i think i found the most intuitive and constant space and oven time complexity alright so thanks for watching my channel remember do not trust me i know nothing
House Robber II
house-robber-ii
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are **arranged in a circle.** That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and **it will automatically contact the police if two adjacent houses were broken into on the same night**. Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_. **Example 1:** **Input:** nums = \[2,3,2\] **Output:** 3 **Explanation:** You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. **Example 2:** **Input:** nums = \[1,2,3,1\] **Output:** 4 **Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** 3 **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 1000`
Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the House Robber, which is already been solved.
Array,Dynamic Programming
Medium
198,256,276,337,600,656
162
hello everyone and welcome back to another video so today we're going to be following the leeco question find peak element all right so in this question a peak element is an element that is strictly greater than its neighbors so we're going to be given an integer area called nums and our goal is to find a peak element and return its index if the area contains multiple peaks we return the index to any of the piece so the question itself is really simple but where it gets complicated is the fact that they want us to find a solution in big o log and time so let's first come up with a solution in linear time or big o n time and then we can come up with the other solution so by itself um there's three possible ways that we can have a peak so let's look at the first condition so we can we're going to kind of have two edge cases so the first one is going to be when we have an array which is in ascending order so let's take an example of one comma two comma three four five so it doesn't have to be an arithmetic sequence what i mean by that it doesn't have to have common differences but in this case it is an ascending value so what is the peak in this go to be so the peak over here is going to be whatever is at the very last index which in this case is five and that's at the index four so we would return the index four and the reason for that is let's look at the neighbors of five there's only one neighbor which is four and obviously five is greater than four so this is kind of one edge case that we have and uh let's just kind of draw it like this so you can kind of think of all the values increasing and they might increase at different rates but they are increasing and finally we have a large value on top over here which we end up returning okay so this is for ascending so now we have another edge case is when uh that's when we have descending values so let's take the same example but the opposite so let's say we have five four three two and one all right so in this case the peak is going to be five right and this is going to be at the index zero so we return zero and the reason for that is the neighbors of five are four there's only one neighbor and five is greater than four obviously so that's what we end up returning five is the only cheat that exists in this case so in this case uh we have a value over here and then keeps going down at whatever rate right so this case is the only peak which is the first value and ascending the only peak is over here now we have a case in between right so you can kind of think of this uh think of this as the more common case and this is where we have a local uh maximum okay so in this case as you can see these are the global maximums in both of these cases so a local maximum is only when the immediate neighbors for example are actually smaller than the actual number so uh how that would look like is something like this right so to the left of it's decreasing to the right if it's decreasing but the value itself is greater than what's on the left and greater than what's on the right so we might have several local maximums but let's just take a look at one example so let's say we have one comma two comma five comma three comma four right so in this case we actually have two possible answers to our solution now the first one is going to be five so let's look at the neighbors of five so we have a value of two and five is greater than two so that's one thing that's correct and now let's look at the right which is three so in this case five is greater than three as well so this means that five is a possible p and we're gonna return its index which in this case is two so we return the index two and another possible peak is going to be four so in this case uh four is at the index of zero one two three four so four is at the index four and we're gonna return four in this case since compared to its neighbors it only has one neighbor which is three four is greater so these are kind of the three conditions that we have and we can kind of just look for this in a simple loop so let's just see what that looks like so this over here is going to be our big o of n solution and we're gonna have a for loop so let's just do for x in range length of numbers where we're iterating through all of the numbers and remember over here we take care of all the cases right and there's and the two extreme cases which is we might have a peak at the zero index or the last index okay so now keeping that in mind we're going to have a condition it's going to be a long one so the first thing we need to make sure is when you check whether it is a neighbor or whether it's larger than both of its neighbors so let's just assume that so to do that we first order nums we're going to go to the index x and check if this index over here is greater than whatever is to the left of it so to do that we're going to do nums x minus one okay so that's one condition and the other condition we check is so we know it's greater than something to the left of it we also need to check if it's greater than whatever is on the right of it so to do that we're going to do nums x is greater than nums x plus one okay so this over here tells us that it's greater than what's in the left and what's on the right and if this is true or sorry and if this is true over here we can just directly return this index which is x but there's a few conditions that we didn't actually account for what about the condition where x is at the index zero so when x is at the zero index we can actually check for something to the left of it so that we're gonna have an exception so if x is equal to zero or this condition over here now the same way when we're at the very ending or at the last index we can't check for whatever is at the right of it so the condition we have there is if x is equal to length of nums minus 1 or the condition that we defined over here so this is true we directly return x since that is a valid p so this over here is pretty simple but again we want a log and solution so let's see how we can kind of optimize this to get a login solution and the way we're actually going to do that is by using a binary search so let's try to understand how exactly we can even use a binary search for this so it might be a little bit hard to understand why or how we can actually use a binary search because normally we use a binary search for areas which are already sorted but in this case that's not necessarily the case right so what exactly are we searching for so in this case it's pretty simple we're searching for a neighbor and this is exactly how we're going to do it so let's just kind of go through an example let's use this as an example and i'll kind of explain it as we're going through it so as with every binary search we're going to have to define our search space so the search space is going to be the entire area so we're going to have l or the left part starting at the index 0 and we're going to have our index or we're gonna have a pointer r starting at the very last index okay and let me just also label the indices first so that's zero one two three four okay perfect so now in this case what exactly is our goal going to be so what we're going to do is we're going to find out go to our mid index and the way we do that is going to be by l plus r divided by 2 okay so in this case we have 4 plus 0 divided by 2 and that tells us that the mid value is at the second index so in this case what we do is we keep going to the mid value and we check if mid over here is a neighbor so if sorry if mid is a peak not a neighbor sorry and the way we actually check if mid is a peak is by the same condition we have over here so this is the exact same condition that we're going to use so over here we're going to check is the 5 ap so five is bigger than two and five is greater than three so in this case five is ap and we're good to go okay and in that case we just directly return mix so that's pretty simple so now let's just change it up a little bit so we have another condition to work with so let me just change the area all right so now let's say we have this as our area one two three four and zero so in this case we can obviously tell that this over here is the peak but how do we actually get to it so over here we have this as the mid value okay so this over here is mid and now what exactly do we do how do we know which direction do we move do we look at the left of mid or to the right and the way we actually figure that out is by looking at its neighbors one by one so first the first step is checking if mid is a p so in this case three is greater than two so that's one condition but three is less than four so that means that mid is not ap so now we move on so we have two options right and the two options are pretty simple we can either move to the left or we can move to the right now what is the condition to move to either the left or the right and in this case that condition is going to be based upon which value is greater okay and what exactly i mean by that is over here what we're going to do is we're first going to look at the left okay so let's look at the left of mid so this is the value at the first index and we're going to check if whatever is at the first index so if in this case we have two so if two is greater than three and obviously this is not true 2 is not greater than 3 so what that tells us is that if we move to the left we are not going to find ap and the reason for that is because in this case so let's say we do end up moving to two we don't care what's on the left because we already know that it's right neighbor is greater than it so the other way to find a peak is now we look at the right so we know the left that was not a valid option so now we go to the right so we go to the third index here and we check if its value is greater than three so in this case is four greater than three the answer is yes so what that tells us is that this value here can be a possible peak and we do search in that area and the reason we know that is because this 4 is greater than one of its neighbors already and now we just need to check if it's greater than the other neighbor as well okay so now let's actually uh continue with the steps so let's actually move l so now our search space is going to be over here so it's going to be mid plus one so l is going to be here now we find the new mid value so that's going to be three plus four seven divided by two is three point five but we rounded down so we take three so mid is over here and in this case over here mid is a p four is greater than three and a four is greater than zero that's perfect now let's actually move back a step and let's look at another option okay so let's say at this exact place instead of four being the peak let's just change it up and let's say we have five over here and then six okay so in this case what exactly would happen so this would be r and let's do the same thing we again we would not move to the left but we would move to the right and again our reasoning for that is because the immediate neighbor for 3 which is 4 over here is actually greater than the mid value itself so that means there could possibly be a peak value in this search space to the right of it and in the worst case condition we might have something an ascending value where the last value is going to be the p so let's just keep doing that so over here we have mid and we're going to move the left pointer so it's going to be mid plus one and it's going to be over here now we look for the new mid so this is the new middle value and we check if this mid over here is a p so 5 is greater than 4 but 5 is less than 6. so it is not a peak as well and now we look to the left of it okay so we look to the left of five and in this case the left value is not greater than five so that means there could not be a possible peak over there okay so keeping that in mind now we look to the right of five so the right of 5 is 6 and since we have 6 over here that tells us that 6 could possibly be a 3. so that means that we need to move our search space to the right of it since 6 is greater than 5. so now we're going to move l to mid plus one so in this case um l and r are in the same place so the mid value is also going to be exactly over here so if you just want to see it um this would be the fifth index so five plus five ten divided by two is five so mid is also at the same index and now six over here is ap so now we look at the neighbors of six and this case is only one neighbor which is five and six is greater than five so that means that it is a peak and we're going to return the index file so hopefully you do understand what we're doing and this applies the same way to when we're moving to the left so first we find the mid value then we check if it's a p and if it is a peak we're going to return that a mid value directly but if it is not a peak then we're going to move our left or right pointer and we're going to move the left pointer if the value to the left of mid so if mid minus one's value is greater than mid and if that's not the case then we're going to move our right pointer and the condition for that is if mid plus one is greater than mid okay so let's see this in code and i think it should be easier to understand uh with the code all right so over here i'm just going to leave this if condition over here since we're going to reuse it so now let's just get rid of this and we're going to define our two pointers so we're going to have l and r so l is going to be the left pointer starting at 0 and r is going to be at the very last index so that's just going to be nums minus 1. okay the length of knocks minus five sorry so now we're going to go in a while loop and what we're going to keep going into it as long as left is less than or equal to r so now in this case the first thing we need to do is we need to find what is mid so we do that by doing left plus r and then into uh integer division divided by two so it's supposed to be r okay so now that we have the mid value we need to check if mid is a neighbor so if mid is no sorry not neighbor if mid is a peak and we do that by using this condition over here the exact same condition i'm not changing anything except that wherever we have x it's now going to be mid okay so this is the condition we have here and if this is true this means that a mid is ap so we return that okay so in this case we're directly going to return mid now what if this is not the case so if mid is not a peak we have two options okay and the two options are look to the left or the right okay those are the two options that we have so now let's see um about looking to the left okay so searching the left and the condition for that so we're going to have else if it's if the left value to it so that's going to be nums and then it's going to be mid minus 1 is greater than num smith so if this condition over here is true then our search space is going to be everything to the left of mid so in this case we're going to move r to min minus one okay so i forgot to add one small thing so we actually might have a condition where we are at the zero with index so when we are at the zero index we can't look for anything on the left of it right we're gonna get an index error so to actually account for that we're gonna have a condition that mid has to be greater than zero and this condition over here has to be true so that just makes sure that when we're at the zero index we're not looking to anything at the left of it and one more thing uh just to add on to this is when we are at the zeroth index there's only one neighbor that you look at which is what is to the right of it okay so yeah that should be it for this and now let's see what is the condition for when you search to the right okay so in this case else if and over here we're gonna go to nums and then mid plus one the right value has to be greater than number and the same way how we had mid is greater than zero over here we need to check that we're not at the last index so if we are at the last index there's nothing to the right of it so to ensure we don't get an error for that we need to check if mid is less than the length of nums minus one and the reason we're doing minus one the length of num starts counting at one while indexing starts at zero okay so that and this condition has to be true and if that is messed then that means we need to look at the right surface space and to do that we're going to move the left pointer to mid plus one so we'll submit this and as you can see our submission was accepted so this over here is going to be a big hole of lock and uh time complexity and it's going to have constant space so hopefully yeah this video did help and thanks a lot for watching 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
1,930
hello guys today we are going to see another daily lead code problem 1930 which is unique lead unit length three palindromic subsequence problem right so let's understand the problem first so what it is saying over here is like we are given a string yes right and we have to return the number of unique paling Drums of Len three uh that are subsequence appears right and also so uh we all know what is a ping drum right and we also know what is a subsequence so if you don't know what is a subsequence so let's understand what is a subsequence so uh let's uh so let's take this example itself and let's come back to our notebook to see how uh we understand subsequence so suppose uh in our example it was given like a b c d e right so what we can say is like B b d e is a subsequence of the string a b c d e uh also uh there is one thing known as substring so substring can be something like the you know consecutive occence like CD is a substring but a c and d a c d is not a substring it is a subsequence is generally in a sequence but uh within from within that string itself so I hope you have understood what is a subsequence so anyways let's see uh what we are trying to do so uh give let's see what the example here we have given a b c a and the output is three so what uh we are doing is like we are calculating the paling drum subsequence of Len three so here if you see the subsequence a b a which is like a and then this B and then this a is a subsequent similarly this a uh this a and this uh the next a and then again this a is also subsequence of L three and they are paling drum right because from back side also if you see it's a on itself similarly this a and then this C and then this a this is also this can also form a paling drum so uh let's understand the intution of solving this problem so let's take a kind up a little bit complex example and understand how do we solve this so our example can be something like b c b a so if you see uh what is the number of paling DRS of Len three so someone can see says like B this B and uh this B can be one paling of course similarly this B can be another paling drum but again see both are same so we have to count only one that is given in the question read it carefully so we cannot consider this part again uh what we can consider is like b c b can be one pingr right so this B this C and this B can be one again this B this C this B cannot be because again it's same and repeating again another can be b a b right and then we have a b a so I think that's all we can only form this four paling drums right and not this one yeah so to do this we can do something like we can create a you know what we call we can create something known as uh the position like uh so suppose uh we do something like this we uh iterate through each and every character and we see left of it and right of it and if we have uh the same character that can form one paling right so for example if we see this C let's say this C we are at this point and uh suppose if we see at the left we have a b right at the right we also have B yeah then this C can contribute to form one such filing DM which we are looking for if you see this B this can contribute to form because in its left there is a b in its right there is a b right but if you see something like this a so this for this a there is this B and this B yeah this can help to form one palum but uh not any other thing can help over here if you see for this B this a and this a can help to form paling drum right so a A can be one sequence so uh in this uh sequence we have to see how to form the valr so what we generally what we'll do is like we'll calculate the uh we'll calculate the first occurrence of a character so uh we have 26 characters right and in the question we are given that we can only use small case alphabets so data 20 six from a small a to small G right so let's say we U like we will basically create a vector so given a string yes we have we are given with a string yes right what we do is like we will create a vector integer right and we say is like first occurrence uh of occurrence first occurrence uh of certain characters let's say like we'll create a vector where we store the first occurrence of the character like there are 26 characters right so for the all the 26 character we will initialize uh this with say int Max similarly we'll create another Vector which will store the last occurrence right for 26 last occurrence and we'll say uh it contains minus one yeah like it does not uh contain any character right so what we do is like we will Traverse through this string which a b c b a right we will Traverse through this string and we will store uh the first occurrence and last occurrence first and last so see uh the first occurrence of B is at position zero right uh like we are traving it starts occurrence as of now is z Z because we have not seen uh this these parts we have just seen b now we come to this B its first urren is already we have we already have so what we can do in this case is like we will see the minimum of already stored right stored and the current position whichever is minimum we will store in the first and for the last we will store the maximum of the store and the current position so we'll update this last position by one now we again iterate we go to C right so first C uh the First Position will be so this is for B like okay how do yeah let's create a ARR kind of thing yeah so this is for example for a for B for c for D do everything this is the first one similarly for last one we'll create another Vector where a b c d all are the indexes right and this is the last occurrence where we are storing so for B basically we have stored first Occurrence at zero and for B the last occurrence was one as of now right so now we are at C and when we see look at C for C the first occurrence is 0 1 2 3 4 5 6 so for C the first occurrence is C and last occurrence is c as well right again we'll see B and the last occurrence will change from 1 to three right again a the first occurrence will be at four last occurrence will be still at four for B last occurrence will change to five right again we'll see for a first occurrence is two it like four itself but the last occurrence is at position six C right now we have the first occurrence and last occurrence of each and every character so we iterate through all these 26 characters and whichever characters which are present in our you know this first occurrence and last occurrence Vector what we do is now finally so we'll uh like uh for a the first occurrence is four and last occurrence is six so there how many unique characters are in between four and six so from four and six in this uh string we'll see how many unique characters are there and we'll find that okay there's only one unique character so this a will cont like this part will contribute for one uh like uh one paling subsequence of size three similarly we'll go to B the first occurrence is at zero and the last occurrence is at five so between Zer and five how many characters are there which are unique so see B is not unique right so like B is unique as of now c a three are unique right b c and a between this and this right so we'll store we'll add three for this we'll go to C first C uh first and last is two and two itself right so there's no any character so it's zero C is contributing zero similarly for D there's no D zero e f everything will do so till z if we do we'll get 3 + 1 4 which is our answer so we'll get 3 + 1 4 which is our answer so we'll get 3 + 1 4 which is our answer so now let's see the code yeah so over here uh you can see this is the count pic subsequence string right uh length we have calculat length and then we have initialized the vector where we have the first position occurrence and the last position occurrence and then what we are doing is like let me zoom out for you yeah so we'll Traverse the string to find the proper position that is the first occurrence and last occurrence right so we'll Traverse through the string s like from I Zer to the length and then what we are doing is like we extracting that character position right and then we are uh in the uh first occurrence position uh of that characters let's say for B we are storing the minimum of the value and the current position whichever is minimum we are stoling and again for last position we are so in using this Loop we are creating our uh positions first and last positions right and then we'll create a variable let's say answer to initialize our answer to zero as of now so that we'll update the answer later and then what we are doing is like we are traversing from each and every character like from A to Z right a zero represents a and 25 represents Z right and what we are checking is like if the first position of certain character let's say a is length or it's minus one the last character is minus one it means that we have not seen that character right so we'll just continue we'll not this because this is not going to contribute anything in our answer right we'll do that and we create an unordered set of characters to store the unique characters right to store unique characters in between the first and last so now uh we have that character uh we have suppose we have air as of now and what we are seeing is like the first occurrence of a that position and then uh till the last occurrence of B we are adding all the characters into the set right and we at the end we'll have unique count right unique there will be unique uh characters inside the set at the end so we are adding the size of the set and then again Loop will run and then we'll again initialize this set and we'll check for character and from A to Z we'll increase the count and we'll store in this and let's submit this code yes so yeah it is working per perfectly and uh for you uh I'll just minimize so that you can see the entire code at once for your references uh I hope you will be able to see the entire code let me do so yeah and then Zoom it a little bit for you yeah I hope uh you can understand this thank you
Unique Length-3 Palindromic Subsequences
maximum-number-of-consecutive-values-you-can-make
Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**. A **palindrome** is a string that reads the same forwards and backwards. A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. * For example, `"ace "` is a subsequence of `"abcde "`. **Example 1:** **Input:** s = "aabca " **Output:** 3 **Explanation:** The 3 palindromic subsequences of length 3 are: - "aba " (subsequence of "aabca ") - "aaa " (subsequence of "aabca ") - "aca " (subsequence of "aabca ") **Example 2:** **Input:** s = "adc " **Output:** 0 **Explanation:** There are no palindromic subsequences of length 3 in "adc ". **Example 3:** **Input:** s = "bbcbaba " **Output:** 4 **Explanation:** The 4 palindromic subsequences of length 3 are: - "bbb " (subsequence of "bbcbaba ") - "bcb " (subsequence of "bbcbaba ") - "bab " (subsequence of "bbcbaba ") - "aba " (subsequence of "bbcbaba ") **Constraints:** * `3 <= s.length <= 105` * `s` consists of only lowercase English letters.
If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.
Array,Greedy
Medium
330
132
hello everyone in this video we will be solving palindrome partitioning number two problem it is a hard problem number 132 let's look at the problem statement given a string s partition s in such a way that each substring of the partition is a palindrome if you look at the example here a b if you partition it at the interval between a second a and b you will get two sub strings a and b and each of the substring is a parent row if the whole string is already a palindrome like in the case example two we can we have to return 0. like any other problem there are several ways of solving it one simplest way is the brute force where you can loop through each and every combination and try to check if it is a palindrome or not and if it is try to save it in an extra space in a variable and at the end compare the minimum number of cuts or partitioning that you will have to do to get your answer but the problem with that is the runtime complexity if you go with a brute force approach and try to loop through each and every combination and sub strings you will end up with a runtime complexity of o of n cube let's try to solve this problem with o of n square using dynamic programming we will break this problem into two sets one is to identify the all the possible combinations of palindrome that we can build from the string and the other would be how to partition it optimally to get the best result so the first one can be solved using dynamic programming let's use banana as our example so if i build a dynamic programming array a two dimensional array it would look something like this so in this dp the vertical side is i and the horizontal side is j as we already discussed a single character is always a palindrome so in this table where i is equals to j we can directly put a t or true value if we look at a combination of two characters we can easily check if it is a palindrome or not if we compare the two characters by themselves if i compare the character at position 0 which is b and position 1 which is a they are not equal so it is going to be false similarly if i keep on going down to all the combination none of the adjacent characters are the same to compare the remaining combination where the character string length is greater than 2 we can use a simple formula where the first and the last character in the string must be equal and the remaining substring after removing the first and the last character is a palindrome two as an example the j is equals to two and i is equals to zero with that combination our substring will be b a n the formula that we discussed earlier can be written as s of i is equals to s of j and dp of i plus 1 and j minus 1. if this condition is satisfied we can say that the string is a palindrome if we use this formula on our substring ban the first condition is not satisfied as the end character the h characters b and n are not the same it means it is not a palindrome and hence we can put false in the table so our next combination is i is equals to 1 and j is equals to 3. for this combination our string will be a n a if we run this string by our formula the first and the last character are equal and the remaining character is a parent row using the same formula and approach we can fill out the remaining boxes in this two dimensional array now that we have the dynamic programming table ready we need to now check how many cuts are needed to get a palindromic substrings here on the right hand side i have written our string and added few boxes just below them we will be writing the number of cuts that are needed to pass the string from the zeroth index to that particular index we will try to loop through each and every combination of cuts that we can make and verify if after making the cut air are all the sub strings palindrome or not we will be using the dp table to verify if a substring is palindrome or not let's start with the first combination with two variables length and i where l will be the length of the substring that we will be using and i will be the pointer we'll start with l is equals to 1 and i is equals to 0. with this combination i'm looking at the character b by itself is always going to be a palindrome so i don't have to do any partition so my result will be zero okay now if i increment my length by one now i zero length is two so my string is ba by itself is not a palindrome for sure so i will have to break it and the only combination that i can do is break it from the between so after breaking it both the substrings are a palindrome the number of partitions can be calculated by the cuts that i have made for b plus one so for b made zero partitions so for a will it will become one now we will increase our length to three with that combination my stop string will be b a n and going by the same formula that we tried earlier is the whole string a palindrome no now we will have to break it and we can do a couple of combination we can break it from here or we can break it from here so let's try the first one if i break it from here b is a palindrome yes but a n is not so i cannot do this combination the next combination is i will have to break it from here which will bake my substring as ba or a n does that work no so i will have to do two partitions to make it work between b and a and between a and n so with that being said so my number of partition will be the one that i've used before a plus one so result would be two so with two partitions i can make b a n proper palindromic substrings the reason we are starting this calculation from the first character all the way to the end is because we have to break all the characters in the whole string and find out the palindromic combinations the next combination is crucial so now the length is going to be 4 and i is equals to 0 so our substring is bana by itself b-a-n-a is not a bana by itself b-a-n-a is not a bana by itself b-a-n-a is not a palindrome so we cannot do a zero partition let's start with partitioning it from the first place so if i place a partition here b is a palindrome yes a and a is a palindrome again yes if i make a partition here automatically i get two palindromic substrings so my result would be the pal the total or number of cuts that i made at b plus 1 which is going to be 1. so i will have my result in the a column i can continue digging into deeper where i am making up trying to do a partition here to see if i get an optimized result so my two substring would be b a and n a both of them are not a palindrome so that wouldn't work i will try to do it at the end so b a n and then a separate which is again not two palindromic strings so those combination will not work because we are looking for the best optimal result the first cut is the best combination that we can bring out so far okay so i will erase this and try a different combination with length five and i is equals to zero yes substring going by the same approach the whole substring is not a palindrome so we cannot do zero partition we'll start with the first one b a and a not the combination that we are looking for or they are not the palindrome by itself now trying a different one ba so ba is not a palindrome but n a n is although n a n is a palindrome ba is not so we cannot go with this approach or we will have to try something else we can try this combination we are cutting it b and a and then a and n which will give us the best combination b a and then n a n so we have to make two comm two cuts here because we are making us cut at in between a and n we will have to look at what was the last value saved at n and incremented by 1 so 2 plus 1. three so after making three cuts we can make the best possible case here with the same approach if you go with the last combination it is the whole string banana if we try the whole text it is not a palindrome if we cut it from the first b is a palindrome and the rest of the thing is also a palindrome so this is the best thing so we will take the value that we obtained at b increment it by 1 and save it under the last column 0 plus 1 is 1 and we will return the last value that we saved in this array as our result i hope you were able to understand this approach on the whiteboard now let's look at the c sharp implementation of this here is the c sharp implementation for that problem i have tried to simplify it as much as possible for i start with having some sort of a validation to make sure that the input is valid then i initialize a dynamic programming two dimensional array and then so for each individual characters i'm setting it to the true on the dp array because it's always going to be true a single character is always a palindrome that's why the second loop is to compare adjacent to adjacent characters and confirm if they are equal or not if they are which makes them a palindrome and i'm setting the value accordingly after that is done the next is the important loop where i'm looking at are all the length greater than two so starting with length three if the characters the end the first and the last characters are the same and the dp of i plus 1 and j minus 1 is also a palindrome this makes the combination of the substring palindrome and i'm setting it to true after doing that the next set is to loop through all the characters in our string and then do a substring compare it with our d using the dp verify if those are palindrome or not and then save the result so for example start with the index i is equals to 0 verify if dp of 0 and i is already true if it is then we don't need to make any cuts so cuts is equal to zero if they come if the condition fails then we loop through the characters in that substring and try to cut it at each possible combination and verify if that individual sub strings is a palindrome or not so we use the dp that we have built in the previous step and compare it and only save the result if it is better than the previously calculated cuts and we use this temporary variable to save that and at the end we take the last value in our cuts array and return that because that would have the best possible solution or the best possible combination saved this is how you can solve the problem this is just one approach there are definitely several approaches i think like this is one of the cleanest approach that i've seen so far i hope you were able to understand the approach and the code i will be adding the link to my code on the github in the description below feel free to check that out if you have any comments or concerns please feel free to reach out to me and i would be happy to talk about it if you have any better answers or any suggestions for me in terms of the approach that i have taken in solving this problem i would be happy to talk about that as well again thank you for watching and i will see you in the next one
Palindrome Partitioning II
palindrome-partitioning-ii
Given a string `s`, partition `s` such that every substring of the partition is a palindrome. Return _the **minimum** cuts needed for a palindrome partitioning of_ `s`. **Example 1:** **Input:** s = "aab " **Output:** 1 **Explanation:** The palindrome partitioning \[ "aa ", "b "\] could be produced using 1 cut. **Example 2:** **Input:** s = "a " **Output:** 0 **Example 3:** **Input:** s = "ab " **Output:** 1 **Constraints:** * `1 <= s.length <= 2000` * `s` consists of lowercase English letters only.
null
String,Dynamic Programming
Hard
131,1871
683
hello friends now let's of the KMT slots problem there is a garden with unloads in each slot there is a flower the unplowed will bloom one by one in ten days in each day there will be exactly one flower blooming and even will be in the stators of blooming since then given array flowers consists of number from 1 to n each number in the array represents the place where the flower we open that day for example flowers I equal to X means the unique flower that bloom at the day I will be at the position X let's see this example the flower is 1 3 2 which means there on the day 0 the flower add to place position 1 opens and enter day 1 the flower at position 3 opens in edit day on the date to the flower at a position to opens and then we are given an integer K you need to open in which they there exist two flowers in the status of blooming and also the number of flowers between them is K and these flowers are not blooming so what does this mean well basically our task is to find a window and the size should be k plus 2 and those are 2 elements in the cider which is the I and I plus K plus 1 should opens earlier there are all the K elements between them so you can see with the better happen ray there's a value equal to the days these flowers opens and what about the index how to unique how to indicate representative flowers uniquely it should have in a position because one position only have one flowers so in this case we can just construct another array which name the position and this arena position 1 the flower and position 1 opens in the day 0 and the flower at the position to open them day 2 and the flower and the positions to reopen at day one so basically this is another version with the flowers basically they are the same but the sides should be n plus 1 as the position start the stern index is 1 not 0 so we just simply plus 1 and the way then we just iterate the position arrange to find a value in the window so it's a changer to a sliding window problem ok so let's do it but you should pay attention to that and as finally we return the second thing not to that they want take this example this is the very the window and we need a true return 1 right but actually we return 7 8 so we should have canceled a maximum of these two side States and plus 1 that's the one point and another point is that according to their tests if there are many very today so we should return their dates as smaller and Kosovo ok let's do it we first get it is equal to the flowers doll ends and we need a position array position around the sides to defeat some plus 1 and the way should be no initialize the position rate so we iterate to the flower right now less than an I plus the position should be the index repeat of flowers I and there are very we caught you on which means the flower at the position flowers I opens at the day eyes ok and we need a result so we initialize the integer max value because if in the NXT you go to max very which means we have to find a very the window is there we hurry to the position right because it's the sliding window problem so in there two pointers and the ones in the low start from one because the position start from one and the high will be equal to the 1 plus though 1 plus K as 1 because there should be an positions between the low and high so basically need her just equal to 2 plus K and we iterated I start from 1 and the condition is that high less oil coriander and I plus so if the position is greater than the starting end is greater than the law and the position I is greater than transition high which means it'll still valid so I just continue it's not the case well one condition is that the I go to the height which means a we find the earth very the window which are updated result or minima result and I as I said we should have pick the maximum of these two sides which is a position low and position hi and the we should have last one because I started it start from one mmm ok and every time we opted a low to the I you know the highway you caught you I cross K plus 1 we always maintain a size K finally if the result equal to the integer Max value we have the final return x1 if we find it we'll just return this ruins out so a time complexity you should be linear thank you for watching see you next time
K Empty Slots
k-empty-slots
You have `n` bulbs in a row numbered from `1` to `n`. Initially, all the bulbs are turned off. We turn on **exactly one** bulb every day until all bulbs are on after `n` days. You are given an array `bulbs` of length `n` where `bulbs[i] = x` means that on the `(i+1)th` day, we will turn on the bulb at position `x` where `i` is **0-indexed** and `x` is **1-indexed.** Given an integer `k`, return _the **minimum day number** such that there exists two **turned on** bulbs that have **exactly** `k` bulbs between them that are **all turned off**. If there isn't such day, return `-1`._ **Example 1:** **Input:** bulbs = \[1,3,2\], k = 1 **Output:** 2 **Explanation:** On the first day: bulbs\[0\] = 1, first bulb is turned on: \[1,0,0\] On the second day: bulbs\[1\] = 3, third bulb is turned on: \[1,0,1\] On the third day: bulbs\[2\] = 2, second bulb is turned on: \[1,1,1\] We return 2 because on the second day, there were two on bulbs with one off bulb between them. **Example 2:** **Input:** bulbs = \[1,2,3\], k = 1 **Output:** -1 **Constraints:** * `n == bulbs.length` * `1 <= n <= 2 * 104` * `1 <= bulbs[i] <= n` * `bulbs` is a permutation of numbers from `1` to `n`. * `0 <= k <= 2 * 104`
null
Array,Binary Indexed Tree,Sliding Window,Ordered Set
Hard
null
1,220
Ajay Ko Hello Everyone Welcome To Date 4th July List Ko 409 Plus Question Account Top Formation In This Question Wear Dresses And The Art Artist Account Home Ministry Of Length In This Form Using The Given Rules Under Rule Clear In That Used Cars Industry Flood China More Me To The Volume To Do Subscribe To Hai Account Bill Sperm Donation List Code 120 Question Is The Question Liquid But Vi0 Question Is The Past And Avoid Giving Plays For This Question Electronic In The Mid Length Virudha Tarzan Full Form E Agree Vid Ooo think she is the current president and you should not like this till date reservation has been given I hope you understand this rule sir inverted the rule for this is not fair on Thursday for you I am Anil Gautam technique and will use this question Is Backstreet In Amlon In July It's Alliance With Plenty Of Questions And Producer Ball Seam Technique Anandhi Use Vidron In Dab Skin More Subscribe Do The Time Will Come When Will Help In Decreasing Total Time Subscribe To The Page But Let's Dimple Laddu Internal Memory Chip 800 Without Do Let's Look At Recording Part And Listen What Exactly On I First Explain The Map Leader On Middle East Opinion To Do Logic Is Defined Often Set The Best All Possible Directors Patience Default String And Start Generating Account Settings For Each Activity Subscribe Account Of The Meaning of the word meaning - - one of the current president meaning - - one of the current president meaning - - one of the current president that this Dilip Admi Pavana every person who will reply you will be passed and electronic and displaced from the court passed away on that this mind meaning director account tone suvvar subscribe possible in the midst of Video Subscribe I Will Invoke Pahal Par Use Meaning of Subscribe To Hain Smile Previous Program Year On This Day Half Liquid And I Will Be Minus Plus Channel Subscribe School To Must Subscribe And Subscribe To That Contracted Hubrs To Tell You Will Simply Return But Now Consider Map to Interest Litigation in To-Do List Litigation in To-Do List Litigation in To-Do List Subscribe to Reduce Competition of the World Channel and Inside 3 Inch Right to You for Small Kids for the Meaning of Account subscribe and subscribe the Computer Vidmate App A Free State Forest Hai I Hope You India Today Session Id Please Don't Forget To Like Share And Subscribe Our Channel Thanks For Viewing Needs A Hua Hai
Count Vowels Permutation
smallest-sufficient-team
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * Each vowel `'i'` **may not** be followed by another `'i'`. * Each vowel `'o'` may only be followed by an `'i'` or a `'u'`. * Each vowel `'u'` may only be followed by an `'a'.` Since the answer may be too large, return it modulo `10^9 + 7.` **Example 1:** **Input:** n = 1 **Output:** 5 **Explanation:** All possible strings are: "a ", "e ", "i " , "o " and "u ". **Example 2:** **Input:** n = 2 **Output:** 10 **Explanation:** All possible strings are: "ae ", "ea ", "ei ", "ia ", "ie ", "io ", "iu ", "oi ", "ou " and "ua ". **Example 3:** **Input:** n = 5 **Output:** 68 **Constraints:** * `1 <= n <= 2 * 10^4`
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
Array,Dynamic Programming,Bit Manipulation,Bitmask
Hard
2105,2114
1,470
Hello everyone, Evgeniy Sulima nov is with you and today we will look at the solutions to the problem years code number 1470 shuffling arrays and so we are given an array of integers consisting of 2 multiplied by n elements and having the following form x1 x2 and so on dxn and y1 and y2 and so on long y en that is, we have within our array 2 a subset x and subset, a subset x and a subset y which each includes the same number of elements, we need to return an array having the form x1 y1 x2 y2 and so long x and y en that is, insert elements from the first one by one and the second subset, consider an example, we are given an array of integers from elements 25 1347 and nr and inside this means that the size of the array will be six elements 2 multiplied by 3 that is, the subset x includes three elements the first because the next three elements and the output we get 2354 17 because here is our subset x that is 251 and Igor in 3 4 7 and we get 2354 17 at the output and we are also given two more examples we have the following constraint and array length from 1 to 500 correction number of elements of the 1st to 500 length of the array is equal to 2 multiplied by n and each element of the array n can directly have a value from 1 to 10 to the third power. How can we approach solving this problem, I’ll allow myself to depict a little problem, I’ll allow myself to depict a little problem, I’ll allow myself to depict a little artistically, a possible solution is our input array at ms-1 122 and the is our input array at ms-1 122 and the is our input array at ms-1 122 and the resulting array is the result in which we will go in steps of two elements, we will have two pointers and this is l that is, the OSCE forest inter which will first point to the beginning of the subset x and p recipe pointer which will show the beginning to the beginning under the set y we go by obviously by elements and we say that the result is that the first element of our array is equal to the first from the subset x 2 the first from the set y switched to the next two elements and we say that this element is equal to the second element from the set x and 2 the next one is equal to the second element from because 9 and so on until our entire array will end, let 's try to depict this in code, what it 's try to depict this in code, what it 's try to depict this in code, what it might look like is that we have the resulting array cut to length for us. links we have two on the inter, that is, this is the left neighbor on the inter which is equal to zero and the right up set pointer which is equal at the beginning n now we go through a loop which looks like int i is equal to 1 until the array on mts and step y ends we will be in two elements, now we write for the next ones, we say that the result and -1 that is, the zero element cut the -1 that is, the zero element cut the -1 that is, the zero element cut the raven she is mts lion neighbor under more precisely pointer and the result is both that and the next element is equal to mts right sap setpoint now we need to increase each of pointers that is, we can do it either here or right here put comprehended dreams increments the same for printers for the right subset and at the end we return our isolt bar let's double-check our solution that let's double-check our solution that let's double-check our solution that is, the resulting array has two inters for the left and right subsets we go in a loop from 1 to the end with step 2, fill the elements first with lfc then the recipe and return our array, run our solution front run to for the first set of data, everything worked out, run sore to run everything the test version, seeing that everything is beautiful, the time complexity of this solution is aten because we need to go through the entire length of our array on nts and the memory complexity is from n since we allocate a new data structure of length equal to n for our result, I don’t equal to n for our result, I don’t equal to n for our result, I don’t say goodbye to you all the best until we meet again
Shuffle the Array
tweet-counts-per-frequency
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\]. **Example 2:** **Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4 **Output:** \[1,4,2,3,3,2,4,1\] **Example 3:** **Input:** nums = \[1,1,2,2\], n = 2 **Output:** \[1,2,1,2\] **Constraints:** * `1 <= n <= 500` * `nums.length == 2n` * `1 <= nums[i] <= 10^3`
null
Hash Table,Binary Search,Design,Sorting,Ordered Set
Medium
null
155
hi everyone so today we're going to solve lead code problem number 155 minimum stack so uh in this problem we have to basically complete these few functions first one being the init function for minstack class where we'll initialize the stack objects second one being the push where we'll push our element onto the Star Pop where we'll remove the element from the top of the stack then the top function which gets us the top element from the start uh and getment which retrieves the minimum element in stack and they have given a constraint where uh will have to implement a solution such that it operates in over one time complexity for each function okay so uh and there is an uh example but it's a really easy problem we need not to go through the example it's a self explanatory that what we have to do and what I'm going to do is I'm going to use two stacks first one like first one will be the main stack and which uh we'll be doing all the operations and everything and second one will be the main stack which I'll keep so what I'm going to do I'm Gonna Keep A Min stack to store the minimum element which we have encountered for every new push okay so what I'll be doing is I'll like whenever I'll get a new number I will be checking if that number was uh lesser than the top of the Min stack which will be which we will keep if yes uh then we'll you know uh we'll update our minimum value to the new value otherwise I'm gonna use the same like the top value of the minimum stack and I'll be pushing the same value to the minister okay so yeah let's start the solution and I'll explain uh the code okay so these are the few functions so first like uh I'll have to initialize my main stack which will be second one will be the Min stack okay so we have initialized uh these two stacks in the code first one is push in this we will be pushing all the values which we'll get right so in the main uh stack it's very simple I'm just gonna pin that value into this task okay but for the minimum stack what I'll be doing is I will or let's say mineral let's click the name manual foreign it will be the minimum of the current value or minimum amount or sorry the top of the Min stack if it is like if this stack has any value at all or not okay if not obviously it will initialize it with the current value if self dot main stack has any value oops value itself okay and I will again append that into the bin stack okay next one is the pop operation so I'll be just popping out the elements from both the feed from both the stacks next one is the top in which we have to get the top of the element so we need not to pop that but we can just simply uh peek into the stack and check what is the element so this is it this is the interesting one get win uh which will be very simple as for our implementation so similar to what we have done in the top function will be just checking what is at the top of the stack let's check out the test cases yeah so the test case is got clear let's submit for further evaluation now um yeah so the solution got accepted and I think we performed decent we have outperformed 65.24 of the submitted Solutions 65.24 of the submitted Solutions 65.24 of the submitted Solutions so yeah thanks and guys for watching the video and stay tuned for the upcoming ones and this will be uh this video will be a part of our playlist called stack so please do check that out thank you bye
Min Stack
min-stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the `MinStack` class: * `MinStack()` initializes the stack object. * `void push(int val)` pushes the element `val` onto the stack. * `void pop()` removes the element on the top of the stack. * `int top()` gets the top element of the stack. * `int getMin()` retrieves the minimum element in the stack. You must implement a solution with `O(1)` time complexity for each function. **Example 1:** **Input** \[ "MinStack ", "push ", "push ", "push ", "getMin ", "pop ", "top ", "getMin "\] \[\[\],\[-2\],\[0\],\[-3\],\[\],\[\],\[\],\[\]\] **Output** \[null,null,null,null,-3,null,0,-2\] **Explanation** MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2 **Constraints:** * `-231 <= val <= 231 - 1` * Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks. * At most `3 * 104` calls will be made to `push`, `pop`, `top`, and `getMin`.
Consider each node in the stack having a minimum value. (Credits to @aakarshmadhavan)
Stack,Design
Easy
239,716
1,020
hello everyone so today let us look at the problem called number of enclaves so we have been given an M into n binary Matrix grid where 0 represents a C cell and one represents a land cell a move consists of walking from one land cell to another adjacent four directionally land cell or walking off the boundary of the grid return the number of land cells in grid for which we cannot walk off the boundary of the Grid in any number of moves okay so in this example we have this Matrix okay what is the number of land cells from which we can walk out of the Grid in any number of moves that is this one this particular grid if you take one move to the left we can walk out of the grid isn't it but if we look at these three land cells in any number of moves we can't walk out of the grid isn't it if you go up it's water if you go left it's water if you go right it's water we come down it's a Lancel but if we go down again it's water right we can go in only four directions top bottom left and right isn't it this is diagonally connected we can't move diagonally so these are the three land cells from which we can't walk out of the Grid in any number of moves so three is our answer if we look at this example we have four land cells connected to the boundary okay so if we go up and up we can easily walk out of the grid isn't it so there is no such land cell if we stand on that Lancer we can't move out of the grid there is no such Lancer so the answer is zero okay now let's see this example okay what is the number of land cells if we stand on that land cell we can't walk out of the grid it would be this one this and this why because if you see if we move in any direction there is no way we can walk out of the cell okay I mean the grid okay but if we look at these blue lenses okay we take a step to the left then again left we can easily walk out isn't it similarly for these ones we can go to the left go up go right go up you can walk out easily isn't it so these land cells are not going to count similarly these ones also okay so one two three four five six seven eight nine is going to be our answer nine is the number of land cells in our given grid from where there is no way we can walk out of the grid okay so how are we going to solve this problem we need to count the number of cells from where we can't walk out of the grid rate so if we count the number of land cells okay that is the cells which has a value one right so this cell has a value one all these yellow cells are one right but similarly these blue cells are also one value isn't it so we need to make sure that we don't count them okay so how do we make sure that we don't count them what we are going to do we are going to sync all those land cells okay which are connected to the boundary okay if they are connected to the boundary in any one of the four directions top bottom left and right okay that means from any of the those cells we can walk out of the grid isn't it so we will sing this then we will sing this connected Lancer then we will sing disconnected lime cell then using this connected lenser similarly we will sync this one then this one we will start from the boundary and spread out similarly we come here it's a one here right from here we spread out and spread out by doing what by syncing it that this land cell is useless okay so we will sync it and after syncing all these land cells finally the land cell from which we can't walk out of the grid will be remaining okay so this will remain all these yellow cells would remain and we will simply Traverse this grid and we will count the number of ones okay so this thing that we did okay syncing this land cell how are we going to achieve it if you watched the video that I posted yesterday I did something like this what I had said that let us assume we are on a helicopter okay and in our helicopter we have a lot of people whose task is to sync the land cells which are connected to the boundary so our helicopter will as usual Traverse okay fly around okay as soon as it sees that it's a land cell it will drop all the people on that land cell and what we the people will do is it will sync this land cell then all the people would will spread out okay spread out in all four directions and sync all the connected land cells okay sync all the connected lenses so what did we do we did a DFS okay so what are we going to do we are going to Traverse on this grid okay and if we see that there is a land cell on the perimeter okay or let's say extreme rows and columns 0th row zeroth column last row that is R minus 1 and last column that is C minus one okay if there is any land cell in this particular row and column we will start syncing that land cell from here okay we will sing that one and we'll sing all the adjacent connected land cells okay so ultimately the land cell which are not connected to the uh boundary okay they will be remaining and we will count them and return it as our answer okay so let's see the code this is a very easy problem okay so this is the solution okay it's very easy we count the number of rows and columns and we start iterating okay if you are standing at the first row or the last row or if you are standing at the First Column or the last column okay and if it's a one okay that means if it's a land cell okay then what we will do we will call our DFS on it that is I have named the method as sync land we'll sync the all connected lenses okay all connected land cells we will turn all of them to zero okay we'll make them useless because they are isn't it after that all the land cells which are connected to the boundary would be turned into a C cell okay then we will easily count the number of remaining lenses okay they are the ones which are not connect connected to the boundary okay so this is uh that for Loop okay number of enclaves in enclaves we simply iterate over the grid and if it's a Lancel we increment it and we return it okay now this is the DFS method okay if you have moved out of bounds then return okay if it's a C cell then also return it's no use to move into that cell isn't it otherwise sink the land cell okay and after sinking that land cell move in all four directions left right up and down okay so it will move recursively in our Matrix okay and turn all the connected seek boundary connected land cells to a C cell okay make them useless because we don't want to count them when we want to count the number of land cells which are not connected to the boundary okay I hope you don't have any confusion okay so this is the simple DFS method and this is the method to check if you are standing at the zeroth row or zeroth column or the last row and column okay so this is nothing okay so this is The Simple Solution it's very easy there is this is just traversal okay DFS traversal so I hope it's clear okay if we talk about the time complexity as usual it's going to be a bigger of M into n okay or R into C okay and the space complexity is also going to be a bigger of M into n okay so this is the solution okay I hope it's clear if you have any doubt you can ask me in the comment section and other than that if you like this video do hit the like button share this video And subscribe to my channel and I will see you in the next one also make sure you watch my yesterday's video that is number of close Islands okay so that problem is very similar DFS on a matrix okay so yeah that's all bye
Number of Enclaves
longest-turbulent-subarray
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell. A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`. Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_. **Example 1:** **Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\] **Output:** 3 **Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary. **Example 2:** **Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\] **Output:** 0 **Explanation:** All 1s are either on the boundary or can reach the boundary. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 500` * `grid[i][j]` is either `0` or `1`. For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd.
null
Array,Dynamic Programming,Sliding Window
Medium
53
572
in this video we'll go over Le code question number 572 sub tree of another tree now if you haven't already I'd highly recommend you first watch my video on lead code number 100 same tree this is because we actually use the solution in same tree to solve this sub tree problem with just a little bit of extra logic so you'll have to be familiar with that solution first the link is in the description so please go ahead and watch that and make sure you understand how it works okay now moving on to this problem given the roots of two binary trees root and sub root we need to return true if there is a sub tree of root with the same structure and node values of sub root and return false otherwise for example if these were the two trees given then in this case we would return true since root has a sube that is identical to sub root on the other hand if these were the two trees given then we would return false because even though it looks like sub root appears here the node with a value of two is missing the child nodes so sub root would not be considered a subtree of root so you can see that this problem is very similar to lead code number 100 same tree but the only difference is that instead of trying to figure out if the two trees are the same we want to figure out if the sub root tree is the same tree as any of the sub trees of root so now let's look at the code and solve this in Python let's say the root node of the top tree is root and the root node of the bottom tree is sub root like I mentioned we're going to be using the same solution from the same tree problem but with just a little bit of extra logic so over here I've brought over the exact same function used to solve that problem where p and Q are the two nodes passed in now since this function uses recursion and the outer function will use recursion too it gets a little messy trying to visualize both at the same time so what I'll do instead is I'll assume you already know how to implement this function since you should have solved the same tree problem first and I'll treat this function as a black box where all you need to know is that this function returns true if p and Q are the same tree and returns false otherwise this will make it easier to focus on the logic that's happening in the main function so now let's move on our first base case will be if the root node is equal to none in this problem both the root and sub root are guaranteed to contain at least one node so if the root is none then that means we've gone all the way down to the end of a branch without finding a matching subtree you'll see an example of this later but for now just keep in mind that we return false in that case right now root is not none so we'll move on now it's time to check if root and sub root are the same tree so let's call our helper function is same tree which will return true if root and sub root are the same tree you can see that the two nodes right now have different values so they are clearly not the same tree and so this function call will return false at this point we'll now have to check if any of the sub trees of root are the same tree as sub root so we'll end up returning true if the left sub tree of root contains a sub tree that is the same as sub root or if the right sub tree of root contains a sub tree that is the same as sub root let's enter the first recursive call first as usual I'll leave a Green Dot here as a reminder of where we left off in the function where the green node is the root so let's enter the recursive function call and now root is the node in Orange it's the left subtree of our original root notice that sub root is still the same node and doesn't change now let's try again root is not equal to none so now we'll check if root and sub root are the same tree again you can see that they are not the same tree so we'll return false now we have to go down another level and let's start with the first recursive call again I'll add an orange dot here since we're in the function where the orange dot is the root and now let's enter that recursive call but now notice that root is equal to none that means we've reached the end of a branch without any success so we can return false we'll now exit this function call and return back to the function where the orange node is the root and remember this function called return false we still need to try the right sub tree though so let's pass in root. right and enter this function this time Root is the none value on the right side so this condition is true again and we'll return false now we're back in the orange function and this returned false so now we're ready to go back up to the function where the green node is the root and we'll return false or false which just evaluates to false so now we've returned to the green node and this function call return false so now we know that sub root is not a sub tree of any of the sub trees on the left side of root but we still have to check the right side so let's pass in root. right and now root is the node in blue root is not none and now when we check if root and sub root are the same tree we can see that this is actually true so the is same tree function will Traverse both trees and verify that they have the same structure and values so because they are the same tree this function call will now return true and since this condition is true we'll enter the if block and return true now we can go back up to our original function and this call returned true so finally when we evaluate this statement this becomes false or true which evaluates to true so we'll return true as our answer since sub root is a subtree of root and we're done
Subtree of Another Tree
subtree-of-another-tree
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. **Example 1:** **Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\] **Output:** true **Example 2:** **Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\] **Output:** false **Constraints:** * The number of nodes in the `root` tree is in the range `[1, 2000]`. * The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. * `-104 <= root.val <= 104` * `-104 <= subRoot.val <= 104`
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
Tree,Depth-First Search,String Matching,Binary Tree,Hash Function
Easy
250,508
1,626
In only WhatsApp everyone welcome back injury coding in the video cassette recorder problem back team which you can check the problem treatment is Ayodhya I found possible team problem in 1231 research team MLA Saurabh car 's dacoits' fastest off course for 's dacoits' fastest off course for 's dacoits' fastest off course for declaration team Vaibhav by pressing positive- thoughths conflict positive- thoughths conflict positive- thoughths conflict a confident if player till high school channel player record war that finches sink of a boat lips courses very courses updates player in vitamin B6 and code of all possible team that ninth chand solution ko whatsapp khol hit audio player according to the ganges To take of world needs pe and in points and demonic toys player song seeds stand that even today chorus hands free 11058 9 tags page 10 and forests on and budding player one that finance were judge and decorative 120 player david 145 that new year's warden spotting Time According To 23 This Problem Vikram Another Version Of Dynamic Programming Problem Old And Is Long Thin Griffin House Of Credit Brightness Increase In All Sequence Vacancy Sujit Example A Demon Made According To Be Rich Hai Veer Voltage Winters Please Remove This Post That And Anyone Want To Calculate The Answer A Particular Intact Aaye The Antibody Is Allowed Answer All This Injustice Is To Given Only And Difficult And Asked Why Will Method Maximum To This Position That And To Fold This Point Aaye Knowledge Deal Me Solid Calculated On 151 Everything Going To Inch And Intact Behind If You Say Know The Falls In Taxes Which Arise Spirit And Avid Traveler The Players Were Behind Aaye It Is Great Dane And It Is Equal To The Co Refer Current Affair Effective Than They Can Be Updated On So That BJP Going To in opposition to the one who wants too fast for bestowing to the player the don't calculator for every good player also the person who situation greed and one suggested answers for every possible answer this position will be good care of in the given this possibility to increase dandruff Trees Relative Abs Created In The Eyes Of Shame A Visit To Industries Solitaire Receipt Voucher 120 Days Will Be A Good Profession Devi Andher Possible Options For Happy Life Problem For All The Independent And Will Be Finding Vikram Award Winners Of A Non Stop Dame According To Damages Ajay Devgan Se Ne B TV Main To Abhi Hai Apne Phir Students Ko Four Din Kam Player With It's Two Again In These Questions On Hai To Wah Tak Hai Among Dars Mein Ladte Is Earrings The Places To That Videsh Kumar Player With Students Ko Four Dandruff Plate to ki with requested and fear ki Noida Backwards ki Bigg Boss 26 ki Bigg Boss B grade one and difficult to the current affair birthday song in this is not greatest leaders will not come into account ki Michelle's buses Answer Security is always active Declare method against court for damini player in the image on me knowledge cheat code of this student picm update murti don't know water has been provided link description to longest river in subsequent a person or pet is an integral part of yadav culture that and price of Theories that advertisers Buddhist philosophy I felt for dip and that PM to activate at that time Navjeevan trust him according to this software floating touch and my tab reporting done call 100 as e want some time in decreasing order Witch Addiction Hair Solid Waste Water In Decreasing And That My Flight Function On Kar Do Hua Hai Chance Of Dr That I Late And On DP That BJP Will Contain 0 Active Alarm Set A Particular Date Trap Is Video Titanic Lower Is This With Me Call do a very happy Navratri Sir call do no ki aisi aur discussed hai ki then DTP related tips ki encounter Calculate the answer for different 15th Already know what festival hai beech-beech mein kids these days of yours beech-beech mein kids these days of yours beech-beech mein kids these days of yours hai to a Condition [ __ ] defeats hai to a Condition [ __ ] defeats hai to a Condition [ __ ] defeats digested and modified and will consider the referee's decision in a clutch sequence. This of Clans dirty politics and cheap a record of eyes wide expressway will win this possibility of if center year now another and the can hoo is this is It is enter condition has us emphasis of this particular and used in this form of Delhi has another possible date plus wide and this will keep track of all possibilities in this will be answer 1411 text New Delhi will move ahead and similarly calculate disaster for BJP in this award to remain active is absolutely the answer so fielding is absolutely good to draw a small boys after that and skimming going from inch and juju aaye yes greater than 10 - - yes greater than 10 - - yes greater than 10 - - that this speaker now I want to see Chinese course but ab to decorate the native will be adding and its significance of be turned off by the current player that this morgan and this chur diku fidget player om ne Bigg Boss ad BJP this sequence ap and now hi hindi me gym of divine coma ki Bi job will tell which is intact a minor vanadium of batuk decorative selected for severe and minor that and finally the answer is equal to maximum of the answer comedy beef and that and finally twitter hello how are you a solid banned a little bigger correct answer laddu karne If I am going to a wedding then I gave a meeting and on this 20-8-2016 I got a girl 169 Instinct of why did the phone and Abhijan Sandesh I got polytechnic result a cigarette at a and not talking about Deepesh complexity during and after this place of n till we Practice being after and Biwi Singh Deputy are a time complexity 3400 idiot and drop earring 2.25 sandwich is earring 2.25 sandwich is earring 2.25 sandwich is this problem itself is the longest increasing sequence first time in the order of this set the solution in this video please subscribe my channel and you can check The place which was spotted according to the complaints and appointed as well
Best Team With No Conflicts
can-make-arithmetic-progression-from-sequence
You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the **sum** of scores of all the players in the team. However, the basketball team is not allowed to have **conflicts**. A **conflict** exists if a younger player has a **strictly higher** score than an older player. A conflict does **not** occur between players of the same age. Given two lists, `scores` and `ages`, where each `scores[i]` and `ages[i]` represents the score and age of the `ith` player, respectively, return _the highest overall score of all possible basketball teams_. **Example 1:** **Input:** scores = \[1,3,5,10,15\], ages = \[1,2,3,4,5\] **Output:** 34 **Explanation:** You can choose all the players. **Example 2:** **Input:** scores = \[4,5,6,5\], ages = \[2,1,2,1\] **Output:** 16 **Explanation:** It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age. **Example 3:** **Input:** scores = \[1,2,3,5\], ages = \[8,9,10,1\] **Output:** 6 **Explanation:** It is best to choose the first 3 players. **Constraints:** * `1 <= scores.length, ages.length <= 1000` * `scores.length == ages.length` * `1 <= scores[i] <= 106` * `1 <= ages[i] <= 1000`
Consider that any valid arithmetic progression will be in sorted order. Sort the array, then check if the differences of all consecutive elements are equal.
Array,Sorting
Easy
1752
70
hello everyone and welcome to python programming practice in this episode we're going to be covering elite code number 70 climbing stairs this is classified as an easy problem so we'll start by reading the problem set up here you are climbing a staircase it takes n steps to reach the top each time you can either climb one or two steps and how many distinct ways can you climb to the top so basically we're given a staircase of unknown length and there's two ways we can go about climbing it by one stair at a time or by two stairs at a time and how many different ways can we get to the top given that we have those two options for how many steps we take and they have a couple examples here if an input value of two so a staircase that's too tall how many different ways can we get to the top well the output is two so i guess there's two different ways and these are the ways we can take one step then one step or two steps one so the only two ways to do it and then the other example is an input of three so a staircase of three stairs and the output is three so that means there must be only three ways to do that i guess we can do one step so that's going to work for any length of staircase and then the other two a's are one step then two are two steps than one and we're also given this extra constraint here the number of stairs is between 1 and 45 inclusive so we're not going to have to deal with super long staircases so that is helpful to know now let's pull over to the code editor to start working on this problem but before we actually start coding anything i'm going to pull up a whiteboard here so that we can think through how we should even approach this problem so let's see if i can get that to come up here so let's start by writing down some of the values we already know a staircase of length one we were given that only has one way of ascending it a staircase of two we were given by the problem there's only two ways of doing that in a staircase of three there's three ways so those are some initial values that we already know now let's think about a staircase we don't know the next most simple one which would be a staircase of four so let's draw that out here's a staircase with four stairs and now we can just walk through the different ways we can even do this so we can do one that's one way to get to the top we could also do two that's two ways to get to the top and then we have various combinations of one and two steps so we could do one two one that's three ways we could do one big step first and then two little ones that's four ways or we could do the two little steps first and the one big step at the end that's five ways and i believe for four that's the those are the only options we did all small steps all big steps and then each combination of three different possibilities where we take one big step in the other little step so that seems for four then the output should be five so what are different ways we could think about trying to code this up well we could try to do something where we actually generate every single possible sequence that gets us to the top we could have generated those five different possibilities just like we did by hand here we could try to do that in code and then after we've generated every possible sequence we could just say how many sequences have we generated and that would be the answer the problem there is that could be a pretty slow running algorithm depending on how fast this sequence grows with the input size n if it was only growing at the size of n well maybe we could do that but already four but already five is bigger than four so this is going to be something that's going to grow faster than the input size which means if we're starting to get long staircases there's going to be many more possibilities than the length of the staircase and that means that if we write something that tries to generate all possibilities like a brute force solution that's probably going to be too slow to solve this problem so we need some deeper insight into the structure of the problem to solve it in a better way and the key insight to have here is that for any size staircase in this case the four size staircase to get to the top there's only two ways that we can get to this fourth stair we can either get there from here the third stair and take one step or we can get there from the second stair and then take the two-step jump those are the take the two-step jump those are the take the two-step jump those are the only two ways that we can end on this final stair so basically that provides a way to break down this four-stair problem to break down this four-stair problem to break down this four-stair problem into two smaller sub-problems basically the number of sub-problems basically the number of sub-problems basically the number of steps it takes to get to stair four should be the combination of the possibilities that lead to it so the only way to get there is either from here or here so that means the number of possibilities to get to four should just be the sum of the number of possibilities to get to two plus the number of possibilities that lead to three and those two things together should result in the amount of possibilities to get to four because those are the only things that lead directly to four and we can see in our little tree of values we've been writing out here that we can see that is the case in the results we have so far for instance three the value for three was just equal to the two previous values added together and the value for four here was just equal to the value of the two previous ones added together so the next one here we could do a calculation five should just be equal to the two previous one so three plus five so that should have eight possibilities and six would then have 13 possibilities seven would have 21 and etc all we have to do is add up the two previous steps so when we know that we can generate up to any number staircase n just by starting from the beginning ones that we know and calculating forward so now that we have a handle on how the problem works better we should be able to code up a relatively simple solution to do this all we need to do is make a loop that goes up to our target value calculate all of these intermediate values by adding the two previous ones and then once we reach the final value return it so let's pull back to the code now so that we can implement our solution so all we need to do is start off with a dictionary containing these solutions we already know so we'll say path equals a dictionary it's going to contain all the sequences we already know so we know one stair is one two stairs is two and three stairs is three and then we need to make a for loop up to what our target value of stairs n is so say for x in range 4 to n plus 1 because we need to get all the way up to n so basically we're starting at 4 because if it's less than 4 then we know it's something we already know the answer to this for loop will just be skipped and it will return the answer anyway so we're going if we see a staircase that's 4 or longer we'll go take steps all the way up to the length of the step staircase and for each of those steps we'll calculate how many possibilities there are to get to the top of it based on the values of the two previous ones that will be stored in our dictionary and then we will store our new value in the dictionary so that we'll have it there to calculate the next one so we have to store here path x so this new stair value is going to be set equal to the previous two stair values which would just be x minus 1 and x minus 2. so for the case of four a four stair staircase here this is saying how many ways are there to get to that well we saw before that it's the number of ways to get to three plus the number of ways to get to two because those are the only two positions that you can directly get to four from so this for loop should do the necessary logic to calculate the number of possibilities to get up each staircase length all the way up to n so all we have to do at the end then is return the path or the number of steps it took to get up to the staircase of length n we did end up calculating and storing every intermediary length staircase as well so if this was something where we were having to do repeated calculations we could perhaps try to make use of that already stored dictionary to spit out an answer even faster and not have to redo some of this work but for this problem we wouldn't have to do that we just have to return path n so i'm going to go ahead and click submit on this one hopefully we did not make any mistakes so let's pull over and check the result here as long as we didn't make any mistakes our code ran in 32 milliseconds was faster than 64 percent of other python 3 submissions so a reasonably decent solution with the other ones that have been accepted here now if you know a lot about other sorts of programming problems you might have noticed when we were on the white board calculating these different values that the sequence here that we're working with is actually what's called the fibonacci sequence it's the sum of the two previous things in the chain so if you notice that this is actually just a fibonacci sequence progression is what's fault is what fell out of this stair counting problem you could probably find some algorithm for efficiently calculating the fibonacci sequence based on the actual math instead of doing this kind of more algorithmic way of doing it so if you knew something like that you might be able to even code up a solution that was faster computationally than this one because our solution was an o of n solution which means the amount of time it takes to run scales up linearly with the input size but if you knew the underlying math and formulas for the fibonacci sequence you might even be able to come up with something that is faster than linear so i hope you found this explanation useful thanks for watching and keep coding
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
1,197
okay we are live today is the 15 days of may and we yeah because this is the first day of the third week three so again we have two questions and again because of today's weekend so unfortunately we have one median question and one hard question so um well anyways for the hard question i probably won't be able to finish it myself so i will probably decide to read the solution and then try to learn how to do it but for the medium one i will try to do it myself and yeah so the other thing is that for the medium one we actually have three hint but for the hard question we don't have any yeah so today let's try to solve the median question by ourselves first and then let's see if we are able to also solve the hard question but of course i by solving it i mean maybe read the solution and then try to implement the that solution myself okay so let's cut the cheese and start doing the first one which is the medium one okay so minimum night moves uh in an infinite sheet a chess board coordinates from negative infinity to positive infinity you have a knight s square zero okay so a knight has eight possible moves it can make as illustrated below each move okay is two square in a cardinal direction then one square in your orthogonal direction okay well anyways ah my alexa is trying to talk with me okay so by the way the direction the eighth direction is already shown on the board so return the minimum number of steps needed to move the knight to the square xy it is guaranteed the answer exists okay we start off 0 and then we have input of x and y and then we are trying to get the minimum number of steps to move there i would think it would be probably bfs or dfs right since this is a e well not easy this is a medium question so let's see the first hint you can simulate the movement since the limit are low oh okay so constraint is both x and y will be less than 300 so the constraint is low although it looks like it's large but it's actually low so yeah that's what we are trying to planning to do right doing a dfs or bfs and is there a search algorithm applicable to this problem i don't know a star since we want the minimum number of moves we can use breadth refer search okay so yeah i guess we can use either right but if you are doing dfs it's better you are like using something like a star so that you won't like go too far to a different direction because the board actually is infinite right yeah i'm curious maybe we can yeah i don't know so yeah but for the minimum distance it's probably better that we do dfs bfs okay so let's try it let's try to do the bfs so we start off zero so then for the basic df bfs we will need a q right so let's declare a q u e like integer so this integer will be no integer i probably need a integer array right because we have two dimension so we have a q and then okay so from 0 to 2 0 the step is 1 so anyways we can put start with the zero so i mean q the o for uh nu and t like zero right and uh because we have eight directions so yeah so that's our neighbor right and then we also probably need to memorize the place that we have visited right so in order to do that i don't know let's have a set okay i just i don't know i think i like i always like to use a set of string i don't know if that's a good idea or not but that's what i always do so new a hash set of string and then i want to put the set dot at like zero anyway let me just put 0.0 yeah i don't know i just like to use string i don't know if that's a good idea but i do think we need a set otherwise how what if we like come back to the same point right is there any possibility that we can implement this without that i don't know but for now let's try a set yep okay so um i mean currently it's level zero right so and the leave level is probably something that we want to return so uh yeah probably okay so then um let's start doing it so while because it's it is guaranteed so since it is guaranteed we need to like i want to compare i want to see if set contains the x y but it's probably not needed so i can probably just first for now use true in here hey are you blocking my screen my cat okay so we can probably okay are you going to sleep okay sleep here no you don't okay then don't block my screen thank you so i can probably use a shoe in here and then i need to know the length of the q right q-u-e the size okay and then we try verse through uh for int i equals to zero i is less r let's increment the level how about that first right so uh i less than len i plus and let's get one from the queue so int cur equals to q u e dot pool and then so we have a direction what are those a direction let's choose to do two steps first so two step two and yep so it's is there a better way to code this without well anyway i don't know if so oh i can probably have a uh integer step two would that be easier for me to code like i don't need to make it global let's just put it somewhere in like here okay so i will be like plus two and okay well let me think about it i have two one and then one two and then let me just do well i'm stuck with those kind of design though a step i don't want to call all eight but is there a better way to not code eight of them okay i just don't know if there's a better way so okay anyway we have a car we need to do like for and t x equals to zero yeah it's only two step x less than equal to 2 x plus and then 4 20 y equals zero y is more or less than 2 y plus and then we check if n t next equals to like cur zero oh i don't know it's okay and next equals to the curve so the first one will be this plus let's say step okay so i have step two and i have step one so plus step so let's do stop one first x zero and then cur one plus step two why so i want to make sure is that cover all the i suddenly got stuck with the design of this so i have zero and pair with so it's two pair with and then yeah maybe right so if like so i want to cover convert it to a string so like string key equals to next uh zero plus this plus next the one and first we check if it's not already in the queue right so if not say set contents key so if it's not in the key it's not in the set then we can put it into the set and then we can push it into the queue and before doing that let's compare so if next that zero equals to x and next zero equals to y then let's return level otherwise we add that to the set we add it to the queue and then for this we are done but then let's switch one and two oh that's not good it's not a good coding style because i'm copy and paste but i don't want to waste time on thinking what how to make the code look clean so again if it's equal if it's not already content then if it's equal to the result we return the current level otherwise we add it to the key okay so this is what we do for the next level right and then we head to next level so we are supposed to yeah but if i use the while true it won't return it won't reach to here right so will i receive an arrow saying they won't compile arrow 15. okay huh q over so 23 and uh arrowver will already define oh god okay so i cannot use this okay so let's do the uh m and m so then let's change the index so then that was p m and n okay so yeah unreachable so i have to make it reachable but if i don't do this i will also get an arrow saying that no return value right i think oh no okay already so i shouldn't have this so we only have two examples well i was trying to get five okay so let's do 300 i'm not sure if this is reachable though oh some of the well okay so let's do 0 300 and 180 120 and i'm not sure those are reachable though if not then i will be in an infinite loop but i'm not okay so i guess if there's no other age cases i am i'm going to sub it submit it right now i don't think there's edge cases though so how about like do i deal with did i deal with zero no right i forgot to deal with zero yeah so yeah infinite loop so i actually so but can i make it go into here but i don't so it's better that i just deal with zero outside of the loop because if i because i only check the if it's reached to the point after we dequeue right we don't check that before in q we check that after we dequeue but before we enqueue before we add them to the queue it will be faster right because i want the one to add a lot of things into the queue and then only when pull them out of the queue i check the result so yeah before i put that into the queue i need to check if this is already the result so let me just if x zero and y equals to zero then just return zero i think so i think zero should be the answer right yep so i guess this the only age case that we have i don't think there is any more edge case so i will be brave enough to submit and oh my god i have a problem here i know oh i didn't check still 300 i thought i covered this i thought i covered 000 but i don't cover so why negative number will give me a problem though is it because i let me check if i deal the negative number correctly i did so y negative 300 will give me trouble so about zero i remember 0 300 didn't give me any trouble so how about negative 300 and 0. so why only this one is giving me trouble did didn't miss anything oh but that's the last of our input so what's the next what's the one that make me go into infinite loop what did i do wrong 37 pass so do i know which one is 38 oh maybe it's because it's too slow so i won't pass the 37 so wait so is there any better way to do it because i firmly believe if i submit again you will still die on the 37th but what i did was just the basic dfs right did i make anything duplicate so yeah it's basic dfs yeah i don't know why i failed on the 37 case yeah still 37 there must be something that make my program slow or my algorithms low but i can't figure out okay i will think about it for three more minutes and i will see the solution to see what i'm doing wrong in here yeah because a queue and a set and we want the number we can use bfs and that's what i'm using and i try one two and two one so i know i can probably optimize it to go only one dimensional so if there are four dimensions not dimension what they're called i don't know but if i can because i mean hello yes i'm just trying to figure out my medium question did you do the contest yes i did i only solved three questions on each contest so yeah i haven't have time to actually read other people's solution to see how to solve it already i don't i didn't oh okay yeah i don't know but i guess the whole day well for now i don't even have hold on i think i can restrict this to one only one direction right so i don't probably need to go like negative because the negative number will be the same of the positive number right so if this is the larger i will return and then if x is less than zero x so i'm not sure if this is correct though i should probably just read the solution but let me do the one let's try i'm just yeah i probably should read the solution though i probably should give up and then when i have the next one i will just check i will need to check if they are both are larger than zero so i will do this if x larger or 0 then 0 and y is larger or equal than 0 and so i'm going to only focus on the coordinate that's larger than zero because they are symmetrical right so no matter which direction you go like their steps are the same so now let me try it and how about 0 negative 300 and then how about negative 140 negative one or not 40 50. will that be faster yeah it still fell in the same places okay so this is not actually improvement on the time that i spent so let's wave the white flag surrender and i want to see the solution okay let's do it so solution bfs oh okay you do this and then you have a visited oh smart and then you have a queue and then you have this so what if i done wrong yeah i think this should be slower i mean you check this when you d pull them all from the queue and then for each offset you have this as the and you checked if not visited you do the bits and then you enqueue and then you step plus note in java the headset is not the most efficient data structure for this reason using the hashtag to keep check the visit cell in java implementation where is oh my god really so it's a thing using java okay bi-directional oh bi-directional okay bi-directional okay bi-directional okay and dfs is actually faster is a pattern with prioritized depth and rest during the so please tell me why dfs won't get tle oh there's a follow up so let's check so actually our bfs got to only because we are using java and we are using hash set in java okay so now let's see why dfs using map will pass dfs and if you contain the key yeah so that you don't need to recalculate right and then you plus if return zero okay oh yeah if they are both zero right and if they are to return to yeah it is doing the same thing like i only check one direction which is all positive right so integer return mean so you are doing two and then okay so in this their dfs actually is faster because doing that in only one direction is helpful for dfs but not for bfs only because i'm using a hash set so now if i want to improve my solution so make it not tle i should either use an array or do a bi-directional or do a bi-directional or do a bi-directional bfs so let's see which the fast way faster way for me to do that okay so if i have another cat in here oh my god okay i think the best way for me to change is to do another hashtag but instead using an array right so and so the size will be and because i also only check one direction so i only need it to be let's do it 300 right okay so okay cat please so let's replace the set to uh integer only because we are doing java so replace the set by a two-dimensional let's still call it a two-dimensional let's still call it a two-dimensional let's still call it set equals to ah set is a little confusing visited so new integer so 301 so now we don't need a key right so this will be replaced by um what am i doing integer no boolean b-o-o-l-e-a-n so that will be replaced by like visited 0 is true yeah i never know so if i have a chance to use just array i should use array because i'm using java i guess that's what i learned today so where do i check the set in here and so i will just need to change it to like a video x y larger than zero oh god not x y what am i doing this and this larger than zero now i'm wondering if this works because i actually was okay now i'm wondering if this works so let me change it back because i want to see if this is working i am curious right because i should check if this should be still correct and let's just directly check if it passed oh god so this is not even correct yeah but why i mean i am using the similar way of this dfs solution right i only check one dimension not one dimension one direction or only check the positive value just like this abs and then also they have a key of this it's exactly like my code and then they only do abs oh i forgot another thing right i should no but if it's okay so what am i doing one output four but it should be two oh okay for doing this because i remove one dimension i actually emulate eliminate the chance of i doing i go to one point which is negative but then i go back to the positive that only cost me two but if i insist everything should be stay in the positive that will cause me more to make a circle and come back to the same point so that's why by doing this they still in here change it to a positive value not just checking and doing this so for doing that i need to like remove this i need to remove this and then the easier way is to yes to do a abs math the abs oh i don't expect this question to cost me so many times so much time just because java is not good so i'm going to okay now i'm curious will this help oh yeah so this works so my optimization actually works but i mess up by not doing this and just check the positive or negative value so okay so at least i learned that i learned this i didn't actually learn that i didn't actually know in the past that hash set is not the most efficient data structure in java for this reason using a hashtag data structure to keep track of the visited cell in java implementation will result in tle now that i learned this now i next time i will try to use a boolean array bling array is not too spaced expensive right not too expensive in the space okay yeah but i'm just wondering like wow dfs the code is shorter but they passed the task all the test case and then maybe next time we should try to learn the bi-directional dfs not be it the bi-directional dfs not be it the bi-directional dfs not be it bi-directional bfs which is bi-directional bfs which is bi-directional bfs which is you start to bfs simultaneously from the start and the end and grow together because if you only do one bfs the child q will grow so big but if you simultaneously start to bfs when they overlap to each other the child size will be only like help of them so yeah next time we should try this and now that we don't have much time left let's do the hard one so the hard one is number 65 valid number so let's come back so value number and this is a hard question i already show so oh my cat is doing so for this there's no hint so i'm going to watch the solution and see if i can implement this okay so but for now let's read the hard question together so very number a valid number can be slip up into this component in order a decimal number or an integer then optional and e or e followed by an integer okay and then a decimal number can be slipped into this component in order so optimal you have a sign and then one of the following so at least one digit followed by a dot so zero dot is valid okay at least one digit followed by a dot followed by at least one digit i thought these are the same right i mean just start and follow by zero or more digit but anyway so 0.0 but anyway so 0.0 but anyway so 0.0 is valid too a dot followed by at least one digit what so you have zero dot zero and dot zero all of them are valid to this decimal point number oh tedious question you mean this one or the previous one both for me are not that both of me are a little bit complex oh this one yeah even just i mean did you guys do it i don't think i can do it though i'm gonna try to finish before midnight it's almost midnight already so yeah and like i said i already used three time travel tickets so i can't afford to use any more so i need to do it before midnight oh my god okay so integer again we have optimal what's the point of using time travel you pay seven coins yeah i pay seven coins no i just i don't know because like i want to collect everything i want to see a x red x in here i just want everything green so yeah okay so integer we also have out of one more so whether or not we have this is valid and then we have at least one digit so for example for all the following r valley number two oh zero a9 is a very number oh my god so i guess this is just a lot of if right i mean if i'm stupid too stupid to know the correct way to do this i think it's just a lot of if this then that and if this or that then that else that right i think well following are not a b c okay because we only we can only have e but why one e is not valley one e oh because e you need to have an integer after e okay and then so if you have an e you have to have number in before and after so okay and then 99 is okay 99 e is okay but after e you can only have integer right okay and then you cannot have two negatives probably draw the machine and figure out okay if i want to draw a state machine i will not be able to finish that by midnight yeah so that's why i say that i probably will need to see the solution so by doing a state machine is because you don't want to like recompare the same thing again and again right so that's why you can quickly go back to your state and then continue from there but then we have a start state we have to define end and i don't even know what's the end state though so once you find one valid decimal number that's one ending point right or once you find the integer that's another ending state once you find the e you cannot end you can only end when you find another integer so we probably have three end state right terminate state or anyway the last state and then you traverse through the entire string by the end when you finish traversing it you see if you stop in within this three state right but that's so hard for me to generate a finance day machine well the first one is easy the first step is to check whether or not there is a sign even if there is not it's okay oh okay so if i don't do a finite state machine how would i do this just try verse and then do a if because it doesn't say that i have to do it linear time so it doesn't say that i have to traverse only once right so if i'm not doing a finite state machine it should be good and the lens is only 20 right as consists of only english letters both uppercase and lowercase digit plus sign ah i mean different people draw the stain machine differently based on your the understanding of your question so just if i'm so stupid or i am but i am how would i solve this without doing a finite state machine if like for i equals to zero till the end of the string and if char at this equals to this and we haven't find e and we already find this then we return false okay now i have more cats okay now i'm going to try to see i know too many cats okay you sleep there okay do i want to what's the time now do i want to see the solution or do i want to try to do a state machine let's do a state machine shall we how to do a stain machine i didn't practice those at all so how to do a state machine what's the data structure that you can do a state machine map cue map because map is a key and then point to a state right so if we have state like from zero one two three four five and then if i found say sign i go to the state one to wait for a digit right and if i don't find if i find the digit oh it's so hard i actually never practice any financing machine question before okay so zero is the initial state one if we found sine we go to one if we found digi we go to one can we do that or i'm about to give up and see how a finite state machine should be coded because i don't have i know we probably should use a map and then use a number to represent the state but to draw a state machine i don't have experience though okay stay machine is your mental picture you still write if else or switch okay so if we would to do a finance dimension then of course we are going to let me code this first because this is the easy part of course we need to traverse through this like once for each character only once right so for this uh string ss dot length l e n e l e n g t h i plus and then i do the char c equals to s dot char at i okay and then um we probably need a current state so i will have either a array or a map based on the previous experience of the previous question hashmap or hashtag might not be the best for java but i'm still going to do it because i don't know the other way so i will have a lot of map so i need a list of map to map the current character that we read to the next okay so let's say that we have a arraylist of a map let's cheat it let's see the solution if somebody already draw one and let's read it okay shall we ah i don't want to give up but there's nothing in my mind how to do this though let's try one right so i will have a list of map of string which is the current state to an integer which is the integer index of the list so that i can find the next map to traverse right is that so or i can use an array but i think that's the same thing i'm not using array because currently i have nothing drawn in my head so i don't know how many state that we have so i cannot declare array that's why i declare a list for now finance state machine fsm okay uh okay i'm gonna see how people do it because for now i only know and i forgot most of them so i probably will have a zero as my initial state and then i try to read the character if i got this i go to another state which is state 1 to wait for a digit or a point yeah i will have a lot of uh okay so do i like do i make a map and then just like if current state is one and then we receive this and based on the map we go to okay let me read how people solve this i really don't know so before looking at the discussion let's look at the solution so follow the rules which means you don't do a state machine or you are implicitly doing a state machine you also have rules so the solution one is you have a set of digit a server sign a set of exponent a set of dot which is and anything else that will not return true and then the rule is oh after you have digit sing digit if you have sign you have a sing site right i think you declare say something sings sin did you sing exponent thing dot oh there's no sin sign okay oh it seems short but the algorithm is so long i mean the coding is so short and then let me see how many and o n why because you are doing so this is basically almost like uh or it is a finite state machine right okay this approach to is deterministic finite automaton dfa okay dfa finite automaton okay never heard of it before oh we have another question we can practice this oh my god even after reading the solution i don't think i can do it though try this your own before reading anything further take a few minutes to try to design a tfa dfa keep in mind that a state can point to itself for example one two three four five then of course it's digits so you keep pointing yourself so yes i understand that and the green node indicates a valley and state okay so yeah they have three and state yeah yes that's what i thought but i cannot come up with this not to mention in the setting though oh my god when you need to draw something in a coding interview that's insane so yeah i have this in mind there will be an initial state which is zero and then i read the sign but i can't figure out this okay so you read the sign and you go into two oh okay if you read digit you can read a lot of digit and then when you read dot you can jump to another one and then if you resign you cannot go to one you go to two and then you cannot resign again you can only read digi which brings you to digit one to state one or if you read dot bring you to the dot and then you have to have digit afterward and then but in digit you can have either digit or exponent wow okay and then we are in state four you can only have exponent and then this point is after you do an exponent you will try to find an integer so if you read a sign it's okay you agree the digit you go to the endpoint if you read the digit you directly go to here you can read any sign anymore oh so how do i code this a map a list of map okay and then map of ah although i am coding in java what is map of though this is java right okay list off and then you can have a list map of i assume that's digit to 1 sine to 2 dot to 3 right so it's a map of string to integer oh i almost got it no not almost by far well i'm far away from making it to this point and then there are all of the valid finisher state okay so you make a set of one four seven as your ending state and then every time you read one character and then you memorize the current state what is the string group why do we need a string group oh to map to the state oh okay so you read one character you check if it's digit group is digit otherwise if it's plus minus then it's sine if it's e or e is exponent if it start otherwise you directly return false and then if you cannot get the current state with the key that you want which is this so if you don't even have that line from that point then you directly return force oh this is simpler otherwise you like forwarding the state oh wow and then when you finish the string you check if the current state is in the valid final state okay but somehow i think when i try to code this i need to have this picture in here so how about it's just coding here okay but now we all understand this right i mean at least now i do understand yeah because originally i was not too sure that after i read the dj or after i read the sign which state do i go to i have to design this yes okay so and i have to learn the list of hold on before we start coding let's see if discussion have a better way korean java with i ifs what is ifs oh that's ifs so actually this is our first solution right but i want to see if we have other solution if a design the design pattern wow okay i have to say that i will probably need to come back here to read more after tonight after midnight because i'm now doing this with dfa because i need to i want to summon this by midnight but it looks like other than dfa there are still other things that we need to learn so i think i will come back to this but i want to see if other people draw oh that's a good drawing digit did you digit sine digit digital so this is almost the same with the one but it looks like they have one two three four ending state and then you can read blank i don't know if blank is allowed in our current question do we allow blank i don't think so yeah but because of adding blank there is actually another ending state because after digit you can read as many as of blank that you want but what's the benefit of ending blank you skip the e and you go to here to add infinite blank okay i think this one with the blank involved is more confusing so i've decided let's do this i think the drawing or the stain machine of the solution is a little bit better and cleaner than that one in the discussion but somehow that one is the second highest vote on the discussion so maybe i will come back to that later so let's learn this by reading the solution so first again we have a list of maps of string to integer which is our state and it's called dfa automaton deterministic finite automaton and then now i learned this off will generate you a list and now i learn map off will give you mepta off right let's start off yeah i have a typo so off is actually a method that i haven't learned so i need a list of a bunch of maps and then based on this picture we will have map off so the first list is 0 right so from 0 if i got the digit i go to one if i got what's that called sine i go to 2 and then we can have dot yes if we have dot we go to three and then there's nothing more so this is one now this is zero and then we have map dot off this is so hard so now we are in state one if we have digit we stay in one if we have dot now we have one two three four we have so after you have digit i even have a table so if there you have a digi i have to watch the picture i can't pretend that i know okay so if so for from fun from one you can read when you have a digit you can have dot to become a this decimal or you can have a digit to become yourself you can have an exponent to become a new thing which is e expo this is one and then one is after you read one digit and then what is two is after you read sign so when you resign you have to read digit oh or you can read dot okay so let me copy this so after you did i have a title so this is two so after you two is after you read a sign after you reassign you need a digit digi will bring you to one you can read export you can have dot will bring you to three because dot cannot bring you to four okay this is what i'm confusing i always forgot that i need to go to or i somehow want to go to four after reading a dot but actually i have to go to another state which is the same from zero to okay wow so hard to draw this okay that makes sense so if i read it a dot if i read a dot i should actually go to three okay no you go to four this one is one oh but from here you actually go to three so you are you will be able to go to the same one i can rather have my head around this if i without looking at this picture i might go to a different state after i have three from two i might forgot and just go to a different state when you're reading it makes sense but you when you are doing it yourself joining the dfa by yourself is so hard so in two you go to three and then in two there's no other because you can only after you read a sign you can only have digit or dot now that we are in three did you study linear algebra yeah a long time ago i already forgot them all i yeah returned that back to my teacher already so yeah so now you can consider me not never read linear ejoba no i already forgot no so okay no i forgot them all digits so now that i am i try not to look at this but i have to look at it otherwise i can't come up with my own idea so now when you are in three means that you have a dot right so after you have a dot you can have a digit or not have a digit then what this what is that state though without looking at i won't think of four is a good state after you read the dot and yeah three is after you read a dot and now the only thing you can have is digit okay my cat is here again ah huh why do people not working in machine learning and say they know machine learning they don't know well about me i do not work in machine learning and i don't i won't say that i know machine learning so rest assured that i won't tell you that i know machine learning okay so now we are in three the only thing we can read is a digit why because we have a sign we have a oh because if you are in three you only have a dot you never have a digit ah okay that won't make sense and then you go to four and four is after you read digit so you can read digit and digit again and you can also read exponent right okay but ah did i in one did i do exponent no yeah i did okay that's another thing that's confusing so both bring you to five but dot bring you to three but this dot bring you to four okay what how about basic machine learning the statistic learning book linear and linear programming i think linear programming some might study a little bit when they are studying algorithm right otherwise no i never studied those or maybe i might i just remember well i think everybody studies statistic a little bit but for me i remember i did study that before but i don't remember anything now so yeah okay so at state 4 is after we read the digit and we can read digit again and then we can also read expo to 5. okay i think this is the hard part and after five you can only have integers so five is not an ending state five you can only read digit i think right oh you can have sine oh god so it's almost like this and then you will so stitch will bring you to probably six okay they do is seven so let's do seven and then sign will give you two six but anyway it will bring you to two different new state and then of course digit you can read bunch of digit right so this is zero one two three four five this is five okay sorry i'm just doing it slow so slowly because i am trying to understand that myself so now that you are in six is after you read a sign then you need digit right so the only thing that you can do is digit right am i right yes did you seven okay and then finally we finally reached the seven so i think this dfa is way more easier than the previous one well the then the one in the discussion so now that we reach seven we can read a bunch of digit and still in seven and that's it right okay so are we doing it correctly zero you can go to one two three by reading digit reading sign and reading dot for one after you read the digit you can read digit a little bit even in time and or you can read a dot or you can read an s poll and in two if you read digit you go to one if you read a dot you go to three yeah you don't go to four you go to three because you need at least one digit okay the three exists because you are forced to have a digit now i don't know okay four you can go to four yourself and five and then for five you can only go to six and seven with sign dot and six you go to seven okay it's probably correct right okay now the green one is the end ending so we have a set of integer valid ending so the first way of adding it is to do an array right i think oh set off oh okay i thought i need a array but you can just do set now okay i need to read the java book again i think set off okay now finally that's built then we can now traverse through the star length so and then hold on we need the current state do i have a current state no see your current state equals to zero so we start with zero so did you manage to solve any number oh you are doing it right now oh i didn't solve it i read the solution and based on the financing machine in here dfa in here i'm trying to code and then while coding i'm learning java because i didn't know you can use list of map of instead of so yeah there's so much thing that i need to learn so going through each character as the char at i and then you categorize your character into either digi sign dot or expo if c is larger or equal than zero and c is smaller or equal than i then oh we need a string state s t r n g s t h states the state can i use state i should be able to use this so data science role is more senior but sometimes the web dev will make more money sometimes i think most of the time the web dev is what depends well every company needs web dev right so there are smaller or very small organization then they have their own web dev and then they probably not got paid really good so yeah it depends i think okay so c then state s-t-s-t-a-t-e then state s-t-s-t-a-t-e then state s-t-s-t-a-t-e is well it's not actually state it's the transition i should not name it state so what's what do they name it to group okay i don't know i probably will name it transitions transition how to spell trans transie so this is lowercase digit else if c equals to like let's say second thing is sine so plus or c equals to minus this state or transient equals to let's call we call it sine sometimes the web that will get 300k over not machine learning i think it still depends like if i would to get a job as a web dev and now that you saw me coding like this i will probably not even get 50k let alone 300k so yeah uh trans c transient okay else if like c is equal to now that we have signed let's do a dot what is dot this is dot oh god control z ctrl z i should type in here dot and then transc equals to dot else if okay now we have dot let's do expo is c equals to e or c equals to e trans c equals to expo and i guess that's it right digit sign dot expo we only have four different transition and now we got our transition and then we should get our current state first so uh and the current state this number should always be valid right so dfa dot get curve we don't even need to check if it's valid now we get a map that we need to see if there is a key there is a transition slide so we need to see contents key of the transie shin so if it's not there then we return false let's do an early return now when we reach this point it is there so our we will set our current state equals to we get curve we get transient so dfa dot get curve and then the get trans the tr i can spell transie and that's it right so now we update our curve somehow i think that's it okay sorry i have music coming there are even who don't know the but they are different i mean quants also always almost always work in fintech right and ml probably not so i guess there are two different i mean quantities almost sde but ml is sometimes also sde but it's more like a data track right i think okay so now we update our current status is that it i think that's it for now right we just keep progressing through the finite state machine and then when we get out from the for loop if the current state is not in or should we say that uh valley ending not contain for the tens for the tens for the tens key i'm not content it's a set intense curve return false otherwise return true right why i think i missed something oh i miss your comment they just follow the market every day they know a lot about how the market move together do you know this i don't i'm not a i'm not as sd like i told you last time so no i don't okay i think that is it what else do we need to do i don't know let's try it ah huh cur equals dfa typo if dfa got content key transient the variable transit has not been initialized okay i didn't true how many test cases they provide us and do we want to do our own test case like they give us a lot of different things to test so let's try i don't know let's try them all right why not okay wow there are so many test cases that i can do so those this bunch should all return true and let's try the false later and now let's do this fourth hmm okay maybe we can submit it and i shouldn't submit in here i will miss the deadline test by submitting i'm just too lazy sorry i know i should come up with my idea of how this should test but this is a hard question though it's already hard for me to code let alone test you know yeah we should start meeting here oh okay what a bad day oh my god so what we learned okay i remember there is another p person doing the dfs right so instead of map let's see how other people what's the data structure python huh i don't do python is that called dictionary or they should dairy right okay i think and then what other people do with dfa c plus and uh oh cool yeah but why for ending state what's the fourth one so we read a digit digital this is the first ending state we read a dot that's also another ending state dot plus digit that's another indian state digit that's an answer that's all before the expose so i guess they there are one more i think right but that's all and with digit so you have digit and because after you have dot you actually can go back to okay my cat's easier again probably i spend too much time doing the hard question and he's not happy yeah but i think the only difference is that after reading the s6 oh i should say after is s6 and then you read the digit actually you can go back to can you go back to s2 because s2 and s7 are essentially the same right so you read a dot and now you read a digit you go to go back to oh no but you can go back to s2 because you can read any more dot so yeah i think everybody can draw their own finite state machine or dfa what i keep calling it financially machine deterministic finite automata so everybody have their own idea drawing that s2 yeah as to receive another dot yes i you cannot do s2 again yeah so okay yeah so i think i should try to learn to draw a stainless of dfa and then come up with this idea first because this is the essential part first resolving for solving this question right so yeah anyway i hope you guys learned something or maybe you guys already know how to draw this i'm the only one who don't know so then thank you guys for learning with me and okay definitely it's too tedious to follow all the rules correctly to come up with yeah so i think what i'm afraid of is that this is a coding like if even a coding interview you usually don't have anything to draw right i mean usually so probably we won't during this like pandemic era we won't have this kind of question when doing online right because usually when you do online coding there's no whiteboard right unless you're doing system design so if there's no whiteboard you can draw so it's so hard for the interviewer to ask this kind of question to know whether or not if you do really understand and what if the person the interviewee is actually exceptionally smart that this dfa just start drawing inside his or her head and then he start coding right so i don't know i just wish i won't encounter those type of questions but i do think this is something i need to learn because watching it and then code is easy the hard part is to come up with this and make sure it runs correctly before you start coding so yeah i think this is probably a good question i just hope and pray that i won't encounter this ever again and also oh by the way also i learned a lot of things that i don't know about java like those type of yeah otherwise for somebody as stupid as me i will probably declare a list and then start adding everything like into it so how do you know but he only the interviewer only need to study this one and then he can interview a hundred people using this one in two weeks and then he changed to another one right so i don't know i just i don't know yeah but good it's 20 minutes less than 20 minutes before midnight and then they won't able to spot but i okay but i don't know if recently because people or company start thinking that this pandemic is not going away soon so originally when everybody is doing the coding interview online originally everybody is just using the like text editor right so they won't actually compile they might be they might take a picture and go back and type and compile but i think recently i heard somebody that even when doing the online coding interview or virtual on site they are using an editor which is compilable like an ide and then to make sure that your code compiles so i don't know if they do that then my chance of getting into any company is i don't know but at least that helped me find my typo right if you notice i have a lot of typos so i don't know okay so good and 20 minutes later i believe we will have another hard question because it's legal it's someday whatever they might do they might give us another hard question so tomorrow might be another hard day for me to do the legal challenge and i might still again start reading the solution before i start actually coding it but i hope i can learn something from it and hope you can learn something from it too and then i guess that's it for today it's already late so everybody have a good night and i'm going to sleep too and prepare for tomorrow's hard question and then i will see you tomorrow guys thank you for watching bye good night
Minimum Knight Moves
parsing-a-boolean-expression
In an **infinite** chess board with coordinates from `-infinity` to `+infinity`, you have a **knight** at square `[0, 0]`. A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction. Return _the minimum number of steps needed to move the knight to the square_ `[x, y]`. It is guaranteed the answer exists. **Example 1:** **Input:** x = 2, y = 1 **Output:** 1 **Explanation:** \[0, 0\] -> \[2, 1\] **Example 2:** **Input:** x = 5, y = 5 **Output:** 4 **Explanation:** \[0, 0\] -> \[2, 1\] -> \[4, 2\] -> \[3, 4\] -> \[5, 5\] **Constraints:** * `-300 <= x, y <= 300` * `0 <= |x| + |y| <= 300` "t", evaluating to True; "f", evaluating to False; "!(expression)", evaluating to the logical NOT of the expression inside the parentheses; "&(expression1,expression2,...)", evaluating to the logical AND of 2 or more expressions; "|(expression1,expression2,...)", evaluating to the logical OR of 2 or more expressions.
Write a function "parse" which calls helper functions "parse_or", "parse_and", "parse_not".
String,Stack,Recursion
Hard
null
336
Hello friends, once again welcome all of you to my YouTube channel for free, so friend in today's video we have taken very interesting questions about palindrome purse and friend, if you are not watching the video for two-three days before starting the video, then not watching the video for two-three days before starting the video, then not watching the video for two-three days before starting the video, then its Sorry for this, due to some reasons, I am not making it but from now onwards, I will try to do it regularly again. Before starting the video, if you have not subscribed the channel then please do so and like the video. It is necessary to do it so that you can get motivation. With this, let's move towards the question and let's see what to do. Basically, question means some list of words is given in the question which is unique. We have to tell how many such words are there which if combined will give the word. By becoming a combine, that is a palindrome, so the van of the broad force approach is correct, there is a list of words, here like world van and van this is w2 this is W3 and so on man, if there are four words then let me make pairs. Will w van and w2 form any leg? How will we assume that this leg exists? If w1 + w2 are catened into If w1 + w2 are catened into If w1 + w2 are catened into strings then it should be a palindrome. So this is the meaning of doing this. If it is about the number of trees that will exit then it has to be packed and returned. List means if it is 121 then we will make a list of list. Van Kama Tu one foot exits like similarly if Van Kama is four then it will do like this then brat for approach. It's okay with this, friend, put two for loops and for H member keep checking that Han in, this is a palindrome, do this with this is okay, it means group force, what is efficient way? Now efficient way tells us that See what I said that w1 which will be the first condition if the reverse of w1. I said if I put w1 in the reverse function that brother go reverse then we supported that when we put w1 in the reverse function then w1 which By reverse coming it came something like Dibrugarh Dash. Now my belief is that look if I have a string ABCD is in itself no first thing if I make it a palindrome then why don't I if I reverse it DCB and it will be made with it first. This will lookup, it will lookup that friend, which are the words in this entire list of words which are exactly the reverse of mine, it is obvious, will lookout, will step with them, this one point is cleared, next scenario, now what is the next scenario, w1 8 members Which is exactly the reverse of the same, now the things are over, after that now it comes to the fact that we have done this, now we have one thing, any 4H particular word for w1, now it will lookup that man, I am Palindrome, if there is no parendum yet, then it will do the lookup with its reverse by congadnet. Now it comes to the question that if there is any empty string in all these lists, the case number is the entire list of words. If there is an empty string then it is obvious that for every word we can check that if there is concatenate with w1mt then only w1 will be formed then w1 if pen is drum w1 if it is palindrome then what can we write that If placed on the main world index and placed on the fourth and third index, this pairing can be done because w1 is the case for every word if this is the case for every word. Previous cases for d individual world This is the case for every word if this is the case for the entire If any single string in the list of world, even a single word, is empty, then what will we have to do in the case, if we concatenate all the words with it, then we are going to get the same words when we do w1 with it. So if we do w1 w2 then we will get w2, w3 will get w3 and w four itself is not the same, so we can directly check whether this is a word, is this word a palindrome, if this word is a palindrome then one leg will be cut off, leg will be formed. No, why won't it be made like you, I told that if I assume that I have word for, I have an empty word for, what pairing option will I get, should I add w1 and it, I said w1 + I add w1 and it, I said w1 + I add w1 and it, I said w1 + MD string. And what I said in the beginning, if we make a palindrome by crossing them, then we will include the spare, then MT will be added with w1, if w1 is not there, then you check w1 only, is it equal to w1, that is, its If it is reverse then it will be parentrome, so we will make one more leg exist, so I hope this thing is also clear but if they are reverse to each other, then which case comes in that, I said that if w1, I have a word. I know that this word has an empty string, whether it is there or not, it has become a different case, okay, that is a different thing, we said now w1 is not a paren drum, I have taken w1 is not a hair, obviously, we know that it is not there. There will be some characters in w1, that is, we say that is there any substance in w1, if in parenter I have taken any substating, let's assume from zero to starting from the initial til, this is a palindrome, then if what is the region after this, see how w1. We would have said that w1 would have been made with the help of two strings. Let's assume that starting from zero of D and Van, the string from zero to index plus the index of w1 or whatever can be made till the end. It will happen that w1 is ABCD then A B C is made from A B plus C the region. Later I am saying that now see what I said here that w1 is complete with me, make it like this. Now I said that if this region in w1 is my first drama. If this region is my Parinda Mix, then the whole string means this, if I want to make it a palindrome, then what do I have to do? Either I do the same thing, if this is a palindrome, then if I say that I reverse the one in front of it. If I reverse the one next to this, I reverse the one put here, then it will not be formed, how what I said, if we take an example, let's take example ABCD, however, what is formed by reversing ABCD, exactly this is a palindrome, so what do I know that For sum's point from zero to K, if there is any string ahead of it, if it is a palindrome then only this has to be reduced in adervise, then the matter is over. If it is a palindrome, then reverse the region of the next string. You can reverse it and put it in front of it, so if this is the reverse of the sting which was an ad, if the ad is somewhere in the entire world list, then what can we create an index by concatenating both of them. And D first index is making un par adervise second case what if this is not the case like now what we did is add S tu and S1 how will we add S1 and S2 now if I take a part of the string like a BA, we take this, add whatever, but now we write like give here, now give, now in this region, what did I say that this is this region, this is the region, the one behind this is the region. Reverse it and put it forward, put pe ad here, put id here, still this becomes a complete palindrome string. So what have we said exactly, in this case what have we said that what is its reverse, what is ad, if ad is a complete word. If it appears anywhere in the list then what we are doing is if we are adding its reverse named S2 add to S1 then we will definitely get one leg named Van Kama 2 and if we add the reverse then we will add 2 1 which is the previous case. These are the four cases which you have to take care of while coding. We have to take care during coding because only these cases can be solved in an optimized way. Now let's go straight to the coding part. I hope this is clear to you. If it has not happened, then definitely watch the video once again, it will become clear to you, what to do for coding, first of all, let's create the answer in which we are going to return the answer, in which what am I storing, all the things. I will store everyone's reverse and their indices, so for this world, its reverse and its index in front, whatever its index will be, also use string builder, you use de reverse function, so that language dependency is not to be done, we have to follow the algorithm, that's it, now we are done. Will travel and get H word and I earn word, this is nothing, I am simply picking up both index and word at the same time, what will those people do for us, for I inta = 0 I &lt; common thing in this Don't think too much, word and that together came for index word, it will be clear, now we will check, is it that word, is it my word, is it in reverse, if is it my word, which I have just picked up. If you pick up your word ABCD man, then what is ABCD? Is ABCD read in reverse for some other string? Is A B C given in reverse for some other string? Who is yours in it? What are all those words? Reverse of all those words. If you read the reverse order of the words then I take it, if any word comes like word tu mere pas kya aaya, world van mere pas tha, ABCD ok, what tu mere pas kuch aisa DC ba to DCB, mere pas hi hai. So what did I say about this Word in Hash Map So what is DCB What is the meaning of being in Hashmat DCBA is someone's reverse Whose reverse was ABCD's reverse So I can chat my # It means items and also see the index Let's assume that in his mind he may not have got the index of the word on the tree, like if I talk to him, do n't bother yourself with the index, we are like, if we talk about this example, then first we will give this ABC. People, here we have checked whether it is in ABCD, so what is ABCD, so we will meet it, now when we come to DCB, what will we check after coming to DCP, is it DCB, what do we have, DC is also there, we have ADCB in SMAP. What does it mean to be DCB because ABCD is also the reverse DC of ABCD so it is in the map, neither is it lying in this map, so that means with whom it is making its feet. Current I index it with ABCD. If you are making legs, then what team did we give for it? Apne Answer. After that what we have to check now we checked for our empty case if man lo world what do I have let's first if I don't have world mp but I have an empty string lying in has map So what I told you is that Emti can share it with everyone, so what will have to be checked for that whether that word is a palindrome or not, then what should this word be equal to the reverse of the world, it can become its own difference in the case, this is my Passed together, after this what did I say, if we handle the third case together, then we will take four in the range, we will take the length of the world, we will break the word into substrings and get it checked, the same two cases will be taken till further. What is the word of mine, how can it be in the word from the beginning to the beginning of the story, does its reverse exist or not and what is the region behind that, my first liquid, what is the region behind that, be equal to The word something is reverse, it should be there in this map, then drum is first, then it is ok, I have appended the answer, the index is equal to paisa, it is ok, so if you like the video, subscribe so that you can keep getting motivation, see you tomorrow's next. Thank you in the video
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
48
hello everyone welcome to tic this is khushal and today we will be going through this question rotate image so let's see what the question says you're given an n cross n 2d matrix representing an image so uh we will be given a 2d square matrix where the number of rows and number of columns will be same and we are supposed to rotate that matrix of the image by 90 degrees clockwise what does that mean okay so if we have this matrix one two three four five six seven eight nine if we pick up that matrix and rotate it by ninety degrees clockwise here is how the resulting matrix is going to look like seven four one eight five two nine six three so what is happening here the first row one two three is coming over here one two three four five six is going to come over here four five six seven eight nine which is the last row is going to be the first column seven eight nine so the first thought that comes to my mind is to take a extra matrix iterate through the first row put those elements as the last column in the new matrix iterate the second row put the elements over here iterate the third row with the elements over here okay but we are actually not allowed to do that in the question itself it is say that we need to do this operation in place that means we are not allowed to use any extra space okay so if we wish to do this operation in place without using any extra space we should think in the terms of coordinates x and y so if you consider this element 1 which is at 0 1 position that one needs to go at zero two position but if one is going to go over here where is three going to go here but how exactly are we going to do that at first side that this might look a little bit tricky but if you look at things more carefully if you look at rows and columns in general you might notice that the elements of the columns are going at the row and the elements of row are going at the column suppose if we consider 143 those elements are going over here but just not that those elements are also getting reversed okay so what i'm going to tell you is if we consider the first column 147 the column is getting converted into one four seven as zero but you know it's also getting reversed at the same time seven four one which is the first row of our desired matrix so converting each of the rows as columns and columns as rows does that sound familiar to you so we're basically taking the transpose of the matrix and after taking the transpose we're gonna reverse each of the rows to get the desired matrix uh let's move on to the coding part and see what needs to be done okay so in the beginning we're gonna check some edge cases if matrix equal to null or matrix dot length equal to zero we're just gonna return now uh as per our discussion we're gonna do this question in two parts so first we're gonna transpose and then reverse so in order to transpose the matrix we're gonna have to iterate through the matrix we're gonna visit the elements and interchange their x and y coordinates okay so we are going to have two loops matrix dot length and plus so this loop was for rows now for columns so you might not understand the range i just wrote but we will go through this after i write the code so if we need to interchange i j to j i we're gonna have to have a temporary variable so temporary variable will have value matrix of inj now we're gonna have this value inj assigned to matrix of j i now matrix of gi will have the value of matrix i j which we have stored it in this temporary variable just for now consider that i have not restricted the range so we're going to take each and every element of the matrix i'm gonna interchange their x and y coordinates uh the diagonal elements are going to remain at their place only because their x and y coordinates are the same so when we come at this place 2 and 4 will be interchanged now 3 and 7 will be interchanged when we come at this place we will have 2 here and 4 over here so if we still take 2 into the consideration 2 and 4 will again get interchanged and both of the elements will have their original position so we do not want that so for that we are taking the only elements into the consideration below the diagonal that's why the j will go from 0 to i so now we have already completed this part of the problem we have already transposed our matrix so now the only thing left to do is reverse each and every row of the matrix you can have different logics for reversing the rows but what i'm gonna do is i'm gonna have two pointers one will be at the start one will be the end their position is going to be interchanged they're gonna come closer into change come closer interchange till it comes to the middle of the row so for that we're gonna have two for loops so this for loop is for traversing through the rows the other one um the columns now for the columns the range is going to go till matrix.length range is going to go till matrix.length range is going to go till matrix.length divided by 2 the middle of the row j plus okay as we need to interchange the position of the first and the last element we're going to have to use a temporary variable here so integer temp will be uh matrix dot uh i j okay uh we're gonna assign i j the value of the last element so the value will be i will be same the column matrix dot length minus 1 which is the last index minus j because in the beginning the value of g will be 0 at that time the other element will be the last element but when j increases when it becomes one we also need to decrease the value and we'll have both of the pointers closer to each other so this will work in the end we're gonna assign this to temp let's see if this works out perfectly let's try to submit the solution now so our solution is pretty fast and turns out the memory usage is pretty decent as well so what would be the exact time and space complexity here as we're iterating through the matrix twice once for transposing the matrix another one for reversing the rows the exact time complexity will be 2 into n square so the time complexity is in the form of n square and for the space complexity as we are not using any extra space here the space complexity will be o of one which is constant so uh that concludes the video uh thank you everyone for watching do like share and subscribe
Rotate Image
rotate-image
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise). You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\] **Example 2:** **Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\] **Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\] **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 20` * `-1000 <= matrix[i][j] <= 1000`
null
Array,Math,Matrix
Medium
2015
283
hey guys welcome to a new video in today's video we're going to look at the lead code problem and the problem's name is move zeros in this question we're given an integer array called nums and we have to move all the zeros present inside that array nums to the end of it while maintaining the relative order of the non-zero elements and the most the non-zero elements and the most the non-zero elements and the most important thing is that you have to do it in place without creating a new copy of the array coming to the function this is the function name move zeros and we are given an input array of integer data type called nums and the return type is void which means that you don't have to return anything we just have to move the zeros to the end of the array and maintain the relative order of the non-zero elements also we have to do it non-zero elements also we have to do it non-zero elements also we have to do it in place which means that you have to modify the input array nums and not create a new array to solve the question so let's take a look at the example and see how this question can be solved let's take a look at the example one I've drawn the same nums array here so in this question we are going to iterate through the nums array from left to AI starting from the zeroth index position until the length of the nums array a task is to move the zeros to the end of the array and maintaining the relative position of the other non-zero elements position of the other non-zero elements position of the other non-zero elements so using a for Loop I'll Loop through the nums array using I and I declare the variable index so using a for loop I am going to iterate through the nums array and I'll check if the element at the height index position is a non-zero height index position is a non-zero height index position is a non-zero element or not initially I is pointing at the zeroth index position it is a zero so we have to check for non-zero so we have to check for non-zero so we have to check for non-zero right so we can move further as it is not a non-zero number not a non-zero number not a non-zero number so I will be pointing here now I is pointing to a non-zero element so we add pointing to a non-zero element so we add pointing to a non-zero element so we add that non-zero element at the pointer that non-zero element at the pointer that non-zero element at the pointer index and we can increment index holes so index and higher pointing there we can go to the next iteration I is pointing here it is a zero if it is a 0 we simply move further now I is pointing here it is a non-zero element so we insert that non-zero element so we insert that non-zero element so we insert that non-zero element at index so index is non-zero element at index so index is non-zero element at index so index is pointing here so add that element here now we need to increment the index for the next iteration so I will be pointing here it is a non-zero element so insert that it is a non-zero element so insert that it is a non-zero element so insert that non-zero element at index non-zero element at index non-zero element at index now we increment the index variable and move on to the next iteration in the next iteration I will be pointing here and we reach the end of the array so once we reach the end of the array we can come out of the for Loop and start a new for Loop starting from index until the end of the array and in each iteration we need to replace those elements with the zero so index is now pointing at the third index position and replace that element with a zero no increment index replace that element with a zero now increment index now we reach the end of the array so we can end the for Loop now you can see we have achieved the task of moving the zeros to the end so zeros are now at the end and the non-zero elements now at the end and the non-zero elements now at the end and the non-zero elements are in the beginning maintaining the relative order of insertion finally our output array will look like this so without using a new array we change the input array into the output array here and we return that as the output so let's take a look at the code I declared the index variable and initialized it to 0 I use the for Loop to loop from 0 till the end of the array and checking if it is a non-zero element we add that is a non-zero element we add that is a non-zero element we add that element at index and increment index variable so this will happen for all the non-zero elements these three elements non-zero elements these three elements non-zero elements these three elements will be added and Now using another for Loop starting from index position so index was pointing here right we iterate and add zeros like how we did here once index reaches the end of the array we come out of the for Loop and we don't have to return anything because the return type is void so we didn't create a new array we modified the original input array so the time complexity of this approach is O of n where n is the number of elements in the input are in arms and the space complexity is of 1. we change the original array in place that's it guys thank you for watching and I'll see you in the next one hold on
Move Zeroes
move-zeroes
Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. **Note** that you must do this in-place without making a copy of the array. **Example 1:** **Input:** nums = \[0,1,0,3,12\] **Output:** \[1,3,12,0,0\] **Example 2:** **Input:** nums = \[0\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Could you minimize the total number of operations done?
In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.
Array,Two Pointers
Easy
27
1,482
foreign welcome back to the DSA classes so we were noticing in the previous couple of programs that though a question at the first site may not seem like a binary search based questions whenever contiguous allocation has to be performed right you can use binary search to find the optimal solution now to prove that once more I have picked another really interesting question which is from lead code question number 1482 which is called as the minimum number of days to make M bookcase now what does this question mean you may ask let me take you directly to lead code and show you what the question is asking us to do so this is the question given an array called as Bloom day an integer M and an integer K this is what is given we need to make M bouquet so you know bokeh is nothing but you take multiple flowers and wrap them up together and you know when you want to congratulate someone or something you give them a bouquet right we need to make n bookcase to make a bouquet you need to use K flowers you need K flowers to make the bouquet but the key word here is adjacent flowers now why is this important I'll tell you need to use K adjacent flowers from the garden consists of n flowers so there are n flowers in the garden the eye flower will bloom in the bloom day eye and then can be used in exactly one bouquet okay return the minimum number of days you need to wait to be able to make M bouquets from the garden if it is possible to if it is impossible to make MBO case return minus one and few examples they have given now you can also go and read this question right and try to come up with a solution on your own please pause this video and try it out assuming that you have tried it out now let us move further and try to understand what exactly the question is asking us to do okay now please understand what the question is saying is like this you will be given an array in this array there are few values what this value stands for is that this is the first flower second flower third flower fourth flower fifth flower sixth flower the first flower you know how flowers right if you have ever observed nature you know flowers take some time to bloom right first it will be a small bird and then slowly it'll open up one find it'll Bloom and become a complete flower so the first flower will take one day to bloom so one day to all it takes to blow second flower on the other end takes 10 days to bloom third flower three days fourth flower takes nine days fifth flower takes ten days six flower takes two days now this is your garden and these are your flowers right so I'm just showing the flowers like this what they will do is they will give you an M value guys they'll give you an M value and this m value is the number of bouquets you must create using these flowers right and the to make a bouquet they'll give you a k value and they're saying that minimum you need two flowers to make a bouquet but you can't just take any two flowers you must take flowers which is adjacent to each other which means you can make a bouquet with this flower and this flower these two flowers you can make one bouquet these two flowers one bouquet these in other words adjacent flowers only you can use but different flowers will Bloom at different days right so what they are trying to say is understand let us assume the first day let us see in our garden how many flowers would have bloomed okay so day one first floor will take only one day to bloom so 100 it will Bloom so I'm putting yes second flower will take 10 days to bloom so that would have not bloomed yes so no this next flower will take three days so no next flower will take nine days so no next flower will take 10 days so no next flower will take two days no which means at the end of day one how many flowers is there in your garden just one flower minimum you require 2 4 hours to make a bouquet so tell me you have one flower in the garden can you make a bouquet no means eggs any confusion tiller day two obviously first floral boom because it takes only one day every day that flower will blow so yes next flower no or the last one takes only two days so yes any confusion tiller so now can you make a bouquet now you may say yes I have two flowers I can make a volcano you're wrong why because the this first flower bloomed last flower bloomed are they adjacent is it one next to the other no is it contiguous no if it is not contiguous not adjacent is another word for contiguous I'll be able to think you can't make a bouquet which means no did you understand day three First Flower yes no third flower yes because it'll take three days then no yes because I will take only two days right so obviously it will also be there can you make a bouquet you have three flowers in your garden but you don't have two contiguous flowers you can't make similarly day four yes no yes again no two contiguous flowers you can't make similarly day five also you can't make day six also you can't make day seven also you can't make day eight also you can't make but when it comes to day nine First Flower would have bloomed second flower would have not bloomed third flower would have bloomed fourth flower would have broomed fifth flower would have not bloomed last flower would have bloomed but if you notice suddenly you have two adjacent flowers if you have two adjacent flowers you can make a bouquet so on day number nine you can make one bouquet but how many bouquets are you supposed to make three bouquets so did you understand what the question is asking tell me a day in which based on these kind of flowers and these kind of blooming periods I can make three bouquets which makes use of two adjacent flowers I'll be able to think let's come to day 10 all flowers would have bloomed which means do you see adjacent right how many flowers can I make how many bouquets can I make three bouquets two three bouquets you made m is three which means 10th day you can make three bouquets now if tenth day you could make three bouquets 11th day also you could have made three bouquets 12th today also you could have made three bouquets 13th day also you could have made three bouquets possible but they are asking you tell me the minimum of the maximum days in which I can make three bouquets in 11 12 13 14 you can make vocation all those days but out all those days day 10 is that day which is the maximum time it will take for all the flowers to bloom such that you can create M bouquets and each bouquet makes use of K adjacent flowers so this ten must be your output did you understand the question ultimately here also contiguous allocation only you're doing similar to the buccal location problem contiguous allocation only you are doing right now if contiguous allocation you're doing maybe you cannot make use of binary search on this array but would you agree you can use binary search on this range that is from day one till day 10. or whatever I'll be able to think this is sequential this is sorted and ultimately you are trying to search for a day which will allow you to make MBO case of K flowers each which must be adjacent so this is our search range easy is your brain slowly able to understand the pattern now that you understood this is very simple let's go ahead and S this is my new array now I have to create see now uh what I will do is I'll change the variable names they are calling it as mnk for easy understanding I will change that M value to b o q means bookcase how many bookcase should you create four bookcase instead of K I will change the value to flowers because I need those many flowers to make a bouquet let us assume I need two adjacent flowers any confusion tiller now what I want you to understand is very simple you must find that day that Max today which is actually the minimum of the all other maximum days it can take okay so what I'm going to do is simple first let's establish our search rate now what could be the search Rich well ultimately if I look at this array I will see the smallest value I have is 2. which means the flower which will take the least amount of days to bloom is this flower which will take just two days so I'll keep the two there similarly you require the high also the range right now look at this and tell me which is the flower which will take maximum days to bloom it is nothing but this 10 I hope you're able to think right so I'll keep 10 there now think about it you want to find such a day in which you will have enough adjacent flowers to be able to create four bouquets which have two flowers each that's all you need now please understand that there is no need for all the flowers to bloom for me to be able to create four bouquets because look at this if these two flowers bloom I can make one bouquet they're adjacent if these two flowers bloom I can make one more bouquet because they are adjacent if these two flowers bloom I can make one more bouquet if they're adjacent I can make one more bouquet out of this so this flower need not have even bloomed however able to think but this is my search rage to find the day because less than two days I will not even have a single flower in my garden I can't make a bouquet now more than 10 days I don't need Because by the time that I reach 10 days all the flowers would have bloomed so I will have enough flowers for my bouquet right but our duty is not to find the max our duty is trying to find minimize the days as much as possible such that I can make the required number of bouquets any confusion so you found your search range if you found your search range you can apply binary search let's apply it okay so I'm bringing up the table lowest to highest and may become six I'm assuming sixth day is the day where I love you know flowers but I need to check whether it's a possible solution so what I will do is I will pause pass the same value to my function is possible solution now just the logic of this is possible solution may slightly change now however are we going to check whether on the sixth day you will have enough adjacent flowers to create four bouquets if you ask me simple listen to me I'll create a variable called as adj for adjacent initialize it to zero that variable will tell me how many adjacent flowers I have I'll be able to think next I'll create one more variable called as BC for bokeh count I will initialize it to zero ultimately this will tell me that on day six how many bouquets could have been possible our parabolism now see how I will write the code I will run a loop okay on my array here so I begins from 0. so for right from 0 to length of a inside that very simple I want to see whether this flower the eighth flower has bloomed on the given day M or not I want to check how will you check that if you ask me simple if at all this flower would have blue then would you agree its value should be lesser than or equal to the m value if its value is lesser 100 bloomed if it is equal to also it would have bloomed that's what I'm checking if in case the ith element in my array is it less than or equal to m in this case is it less than equal to M yes it is if it is condition true I will come inside instead what will you do if it blooms now I am assuming that I found one flower I found one adjacent flower okay so what I will do is I will update the value of a DJ I will update it so a d j plus means now this a DJ value is going to become 1. any confusion tiller yes we understood next what you may ask next what means now I incremented the adjacent value now please understand whenever you increment adjacent value don't you think there is a very good possibility that adjacent value could have become equal to the number of adjacent flowers that you need to make a bouquet possible right so what I will do is immediately I will check he is the adjacent value equal to the number of flowers I need to create about okay if it is equal to the number of flowers I need then I can create one bouquet I can create that and tell that the book account has to increase so this bokeh account from 0 has to become 1 so to do that obviously here it should not become one so I'm just reverting that I will just tell B C plus means bokeh count I am trying to increment now think about it you found a flower which has bloomed you incremented adjacent value check the fee of should we do what you have to do is now you have to check if in case the number of bouquet count that you have is it equal to the number of bouquets you're supposed to make you must check that so I will check if in case the bokeh count is equal to this boq which is the number of bookcase I should make if it is equal then this day is a possible solution so I will just return to true now not only will I return true please understand this condition will only work if in case I have formed enough bookcase but if this condition is not true then I'll come outside if I come outside what it goes on to mean is that I created one bouquet see when I incremented this what does it mean I created one bouquet when did I increment it when the number of adjacent flowers I have is equal to the expected number of flowers which means those two flowers which were adjacent to each other I already used it now I should again restart my count of adjacent flowers because I can't reuse it I've already used it so what should you do shouldn't you re-initialize adjacent to zero so you re-initialize adjacent to zero so you re-initialize adjacent to zero so see I will initialize adjacent back to zero I'll be able to think that is how you have to do now that is if in case a flower has bloomed if it has not bloomed then don't you agree the count of your adjacent remains 0 only because you are counting adjacent flowers and if at all a flower didn't blow then that adjacent uh you know that streak broke that contiguous nature broke so adjacent again becomes zero now if at all there is a solution then somewhere this condition will satisfy you will come out if you come out of this Loop it means that you never were able to create enough bookcase if you are never able to create enough bookcase which means this m is not a solution then just return false as simple as that any confusion dealer Great sir we understood what else means let me trace this for you okay so let's start uh first and foremost I'm starting from the eighth index is the ith element lesser than the day yes means it will Bloom if it blooms I will increment the value of a d j it becomes one after that I'm checking if in case I have enough adjacent flowers to create a bouquet how will you do that check if a DJ value is equal to flowers is it equal to flowers no because that is one minimum flowers you need is two so what will happen is nothing you are within a loop obviously I value increments I value goes to the next element tell me is this lesser than the M value S5 is less than 6 which means this flower will also Bloom if it blooms what I will do is I'll increment the adjacent value from 1 now becomes 2. now I will check if I have enough adjacent flowers to create a bouquet by checking is adjacent equal to the number of flowers yes if so I can create a bouquet increment the book account so bokeh count becomes one any confusion till here okay great now I made a bouquet now have I made enough bouquets according to the question I should check so I will check if in case the bokeh count is equal to the number of bouquets I should make which is boq no it is not equal which means I'll come out of if I come out of if what it means is that you already created a bokeh using these two adjacent plus you already created up okay now you can't create one more bouquet out of it which means again I should reset that adjacent value to zero I should reset it to zero and that is what I'm doing you are within a loop I moves forward Imo's for next what happens if you ask me now if in case you look at it the bokeh count I mean you know it is 2 means it is lesser than 6 it will Bloom 100 will blow if it blooms I'll increment adjacent value becomes one after that what I will do is I will check if in case I have enough flowers to create a bouquet no I need minimum two flowers then I will come outside I am within a loop I value moves forward if I value moves forward look at it nine is not less than 6 which means it's a lot bloom or the sixth day the ninth flower is like nine days will not bloom which means this condition is false if this condition is false then come outside else and make that adjacent as zero that is what we have to do and that is what I am also doing adjacent becomes zero also do you notice that in making that adjacent as zero you have taken care of this condition where this flower didn't blow if this didn't flower didn't Bloom then this Bloom flower is useless for me because I can't use it unless it's adjacent flower is also bloomed which means here you increment it at this encount but because this didn't Bloom adjacent control the questions taking care of itself how the logic is taking care of itself great you are within a loop I moves forward three is hundred percent lesser than 6 which means this flower will blow this flower will Bloom I'll increment adjacent value it becomes one after that I will check whether I have enough adjacent flowers to make up okay no I have only one flower I need two flowers okay great no problem this conditional not satisfy I am within a loop I'll move forward next flower is will take 10 days I am in day number six it will not bloom not blue means this condition will be false if it is false adjacency broke see adjacency broke if it broke then that one should become zero and that is what the code will take care of come to else make adjacent as zero I'll be able to think so that is what I'm doing I'm making it back a zero now I'm within a loop it moves forward uh next you can say is 4 if in case it is uh four then definitely it is less than six it will Bloom so adjacent count I will increment it I'll check if I have enough flowers no okay I'm within uh loop I will move forward uh 6 is equal to 6 that flower will also blue which means I found another adjacent flower I'll increment adjacent value it will become 2 any confusion next I will check whether I have enough adjacent uh flowers yes I have enough adjacent flowers I'll create a bouquet BC plus bokeh count will become one after that I will check whether I made enough bookcase or not no I need four bouquets I've made only one so I made one bouquet now you use the two adjacent flowers you use these two adjacent flowers you made a bouquet isn't it once you make bouquet then shouldn't you make that adjacent as zero because you can't use these two flowers again so Jason count it becomes zero and that is what the code takes care of adjacent count comes here available to think again I will move forward within the loop next 5 is less than 6 it will Bloom I'll increment adjacent value it becomes one I'll check if I have enough flowers no so I'm within a loop I moves forward 6 is equal to six so obviously I found another adjacent flower adjacent count becomes two next what happens is I'll check if I have enough flowers to create a bouquet yes I'll increment the value of bokeh count so from one bokeh count now becomes two after uh becomes three bouquets I've been able to make right after which next what happens is I will check if I've made enough bookcase no I need four I made only three so I'll not return two I'll replay suggestion zero I'm within a loop I moves forward if I moves forward I'm out of the loop if I'm out of the loop I will come here look at that and tell me have I been able to make four bouquets no how many bookcase did you make three bouquets I hope you're able to think so you made only three bouquets but you're supposed to make four bouquets which means it is not a solution now that is a return false now return false means come look at this sixth day you check if it's a possible solution no you couldn't make enough bouquets so if you have common sense will you try to reduce the day or increase the day obviously you have to increase the days only then more flowers will Bloom so tell me should search go to the left or to the right means low should become mid plus one and that is what I am also doing low becomes mid plus 1 high Remains the Same so now your low is 7 and your high is 10 in which case your mid becomes 8. is the Eighth Day a possible solution we will check if in case I go to the eighth day and if in case I start checking if in case it is a possible solution then we will easily observe that hundred percent it is not a solution how will you find out if it is not a solution if you ask me we will use this is possible solution if I use this possible solution one thing that you can clearly observe is that I will start I from 0. from the zeroth elemental starting now obviously 2 is less than 8 it will Bloom increment adjacent count now I'm not going to explain each and everything increment adjacent count becomes one five is less than eight it increments adjacent count becomes two so next two flowers I have so I can create a bouquet bokeh count increases adjacent count becomes zero I will check if in case I have made four bookcase now I made only one bouquet right which means a loop will now move forward next this two again I found an adjacent flower because it would have bloomed on the eighth day so I'll increment adjacent count next I will uh check if I have enough flowers no I don't have enough flowers I have only one adjacent flower I cannot create a bouquet next it moves forward if in case it moves forward nine ninth that flower which will take nine days would have not bloomed on the eighth day which means obviously this flower will not bloom I will not increment the adjacent count and my adjacency broke which means I'll come to else and re-initialize adjacent to zero else and re-initialize adjacent to zero else and re-initialize adjacent to zero so as of now I've been able to create only one bouquet right next it moves forward again you see 3 is less than 8 yes I found one adjacent I'll increment it next I moves forward 10 is not lesser than that which means obviously you know it will not bloom if it will not bloom adjacency broke so I will come to else part reset adjacent to zero then what I will do is I moves forward now this flower will definitely Bloom it's four days will take we are in the eighth day so adjacent count increases then the Sixth Day flower will also Bloom right because it is less than eight so adjacent count increases I can create a bouquet because I have two flowers now I'll increment bokeh count how many bookcase I have made two bookcase if I made up okay adjacent flowers count has to become zero again and that is what I am doing after that I moves forward next this fifth flower will also Bloom uh next adjacent count increases sixth flower will also blue adjacent count increases two flowers have created I'll increment the BC count which is the bokeh account and now the bokeh count becomes three I hope you're able to think after that I'll check do I have enough bookcase I don't have enough bookcase which means I moves forward and then I'm out of the loop I've made only three bookcase I needed four bouquets it is not a possible solution return false if it is not a possible solution obviously the number of days has to increase how we're able to think so uh low becomes mid plus one and that is what I am also showing uh low becomes Midwest eight a plus one nine High Remains the time 10 plus 9 is 19 divided by 2 is 9. any confusion tiller so my new MID value is low happens to be 9 high happens to be 10 mid happens to be 9. now is 9 a possible solution let us see let us start so I will send it to is possible solution iteration begins from the zeroth element will it Bloom yes increment adjacent count move forward will it Bloom yes increment adjustment count two flowers you found create a bouquet element bokeh count okay since you've created a bouquet these two flowers cannot be used make adjacent count back as zero next I moves forward will this flower bloom yes increment adjacent count will the next flower bloom yes increment adjacent count because it is equal to nine two flowers you found increment bokeh count becomes two right after that you created a bouquet so check if it is equal to the number of bookcase now 2 is not equal to 4 which means still you have not found a solution great no problem increment I if I uh now the moment you uh created a bouquet you should also reset adjacent value it becomes zero now three will it Bloom yes increment adjacent count next 10 will it Bloom no means adjacency is broken reset adjacency account is zero all this is code will take care of okay get great you are within a loop move I forward will this fourth with this flower bloom yes increment as a Sentry count it becomes one right move this forward will this Bloom yes increase adjacency count it becomes two now two flowers you have create a bouquet increment bouquet count three bouquets you have created beautiful see if three is equal to the number of bouquets that you want no means you have to still move forward right but because I created up okay I need to reset the adjacency account it becomes zero next I'll move forward will this bokeh can you uh this will this flower bloom yes increment adjacent account it becomes one then will this flower bloom yes increment adjacency count it becomes 2 a prayable to think two flowers you have which means you can create a bouquet increment the bokeh count becomes four is four equal to four yes first time this condition is satisfied is b c equal to b o q Yes means return true means it is a possible solution beautiful this is a possible solution but tell me our duty is to minimize this value as much as possible 9 is a possible solution but there can be a day lesser than nine ah to search that now your search should not be to the right your search will be restricted to the left if search should be restricted to the left then high should become mid minus 1 that's what I'm doing High becomes mid minus one low is the same but the moment you do that low becomes greater than high binary search Loop terminates and you come outside and hence what is your result was the last possible solution which is nothing but nine I hope everybody understood nothing new I'm doing it is vastly similar to all those previous problems that I have done right so I really hope you understood this question so if you can see whenever you have to perform contiguous allocation and then either maximize or minimize something then binary search is a beautiful option for you to explore right and the only change which happens is in this is possible solution logic which depends upon the kind of conditions that the question imposes upon you allocating books had different conditions imposed on you bokeh's question has different kind of conditions imposed on you that painter partition problem had different kind of questions imposed upon you depending upon that this changes but here all you can see is you must iterate over the loop and check for the conditions that the question has imposed upon you that's it I'll be able to think great now what are we really waiting for let's go write some code all right my friends let's write some code okay so you can see I have my Min day bookcase that is the name again because we have to find the minimum days in which you can create MBO case right and it is taking my array and boq and flowers number of bouquets and adjacent flowers required to create one book also we need is possible solution we look at that anyways I'll come inside this and all I will do is first and foremost uh before just going and doing all our looping I'll directly check for one condition let us assume you have uh three flowers in your garden so the array is three it will Bloom at different days some value I'm giving okay now you need to create three bouquets let us assume you need to create three bookcase and for every bouquet the number of flowers you require is two flowers which means totally how many flowers you need three bouquets into two flowers each six flowers how many elements are there in your array just three which means only three flowers in the garden but you want six flowers every day to create three bouquets is it possible can a solution be provided no so if in case the total number of flowers required for a bouquet which is nothing but bouquet into flowers if that is greater than the number of you know flowers in the garden then directly return minus one or tell that solution is not possible that's what I'm doing if in case bokeh into flowers that is the total number of flowers which I need is greater than the number of elements in my array AR dot length then return minus 1. otherwise simply you'll be wasting your time okay next now we have to set low and high so low is the minimum value in your array so I'm assuming initially the first value is only the minimum value okay next high value also is nothing but the largest element in your array so I will just make that as a r of 0 I will assume that the first element is only high now I'll run a loop to find the actual low and actual high so for um I'll just run a loop over my array inside that I will check if in case a r of ie is lesser than L value then that should be the L value so L is equal to AR of I one more condition I will check if in case a r of I is greater than H then that is the actual H value that is higher right so I will replace H with a r of I that's pretty much it simple so you found the maximum and minimum in your array which is your low and high now what I will do is call it I will now tell as long as low is less than equal to high I am applying binary search then what I'm going to do is insert that very simple I will now find mid and okay next what I will do is I will create one variable called as a result on top and I'll assume that initially there is no result so I'll make it as minus 1. good now what I will do is just a simple thing I will now check if in case I want to check if this m is a possible solution so I'll call is possible solution and pass M to it so if you look at it I am passing my array I'm passing the number of bouquets I should create I'm passing the number of adjacent flowers required and then value now if at all this returns true if this returns true then I know I found a solution but my duty is to minimize that solution so what I will do is I will first store that solution inside result is equal to m but I want to find a lesser solution so what I will do is I will restrict the search to the left side by making high equal to Mid minus 1. okay else means what this gave you false no solution means increase the number of the day so uh low is equal to Mid plus one and then ultimately I'll come out of the loop and I will return result that's it guys simple now there is possible solution logic Let's uh okay yeah declare that on top fact now watch it I'll go or to its possible solution and there what I'm going to do is a very simple thing which is inside that I will go and first and foremost I'll run I'll create a variable column as int adj adjacent flowers make it a zero also I'll create one variable called as BC bokeh count I'll make it a zero next I'll run a loop on my array AR next what I'm going to do is after running a loop on my array ARS leave some space inside this I will come and I will start my logic so first and foremost I will check if in case the ith element is lesser than n m is the day so if the eighth element is lesser than the day the flower will Bloom so if it blooms less than equal to is also fine if it is less than equal to then I'll increment the adjacent flower count by one next I will check if I have sufficient adjacent flowers to create a bouquet so I'll check if in case a d j is equal to this flowers value if so then bring that bracket down if so what I will do now is I will increment the book account because I know I can create one bucket so BC Plus now you created a bouquet if you created a bouquet there is a chance you have created enough number of bookcase as the question expects so I'll check that if in case uh BC is equal to b o q if that is the case then what I will do is I'll return true because it is a solution so but if at all this was not equal then I'll come outside this if here I'll come outside that if and I have created a bouquet if I have created a bouquet then it is my duty to ensure that I will reset the adjacent value to zero because I've already used those two flowers so a d j equal to 0. any confusion till this point of time great that is if in case a flower bloomed bring that bracket also that is if in case that flower bloomed otherwise I will come to else ah in else what will you do sir in else what I will do is if it comes to else it means adjacency condition broke something bloomed something didn't Bloom and again adjacent valuation becomes zero that is it I hope I'm clear okay and if I come out of the for Loop it means I never was able to create the amount of bouquets I was supposed to so return false not a solution good now what we will do is we will first come down and I will copy this entire function from int from in see I'll not copy static I'll tell you why from int till that end I will copy and paste it inside lead code um as I ask you to copy fully okay anyways paste the solutions now the method name go on top if you can just increase the size of this make it full screen there full screen yeah not working okay so now the thing is that scrolled up this function name has to be Min days according to lead code okay so here you can see they've called Ras Bloom day we have called as AR so I'll replace that with ar they have called M I'll call it as boq the number of bookcase they have called it a scale call it as flowers the number of adjacent flowers required so that change in the signature you can definitely do it any confusion till there but you cannot change the name of the function that is defined now I need this is possible solution now you may think sir why didn't you copy static because understand it is inside a class called a solution now you guys know anything inside a class is an instance method right he's a member of the class and you should not declare it as static is if you wanted to not be called using an object so here they are putting it inside a class make it a member function or an instance method itself okay great now I'll just go and I'll also copy that other is possible solution function and that too without static and what I'm just going to do now is I'll just paste it there great now let's submit the code so if I submit the code then it is running all the test cases accepted okay I'll submit it if I submit it then yeah bring this so 15 millisecond faster than 95 percent of java online submissions okay whatever good great so it has been accepted okay so do you see it's an interesting question and I seriously hope all of you enjoyed and slowly your brain is trying is able to recognize patterns and questions and apply the right algorithm to solve it I will catch you in the next class with even more cooler programs till then take care bye
Minimum Number of Days to Make m Bouquets
how-many-numbers-are-smaller-than-the-current-number
You are given an integer array `bloomDay`, an integer `m` and an integer `k`. You want to make `m` bouquets. To make a bouquet, you need to use `k` **adjacent flowers** from the garden. The garden consists of `n` flowers, the `ith` flower will bloom in the `bloomDay[i]` and then can be used in **exactly one** bouquet. Return _the minimum number of days you need to wait to be able to make_ `m` _bouquets from the garden_. If it is impossible to make m bouquets return `-1`. **Example 1:** **Input:** bloomDay = \[1,10,3,10,2\], m = 3, k = 1 **Output:** 3 **Explanation:** Let us see what happened in the first three days. x means flower bloomed and \_ means flower did not bloom in the garden. We need 3 bouquets each should contain 1 flower. After day 1: \[x, \_, \_, \_, \_\] // we can only make one bouquet. After day 2: \[x, \_, \_, \_, x\] // we can only make two bouquets. After day 3: \[x, \_, x, \_, x\] // we can make 3 bouquets. The answer is 3. **Example 2:** **Input:** bloomDay = \[1,10,3,10,2\], m = 3, k = 2 **Output:** -1 **Explanation:** We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1. **Example 3:** **Input:** bloomDay = \[7,7,7,7,12,7,7\], m = 2, k = 3 **Output:** 12 **Explanation:** We need 2 bouquets each should have 3 flowers. Here is the garden after the 7 and 12 days: After day 7: \[x, x, x, x, \_, x, x\] We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent. After day 12: \[x, x, x, x, x, x, x\] It is obvious that we can make two bouquets in different ways. **Constraints:** * `bloomDay.length == n` * `1 <= n <= 105` * `1 <= bloomDay[i] <= 109` * `1 <= m <= 106` * `1 <= k <= n`
Brute force for each array element. In order to improve the time complexity, we can sort the array and get the answer for each array element.
Array,Hash Table,Sorting,Counting
Easy
315
1,073
we cool 1073 adding to our net megabind every numbers I don't it's a mega man I cannot read mega binary numbers come in two numbers we mice in a no way oh it's a no way but all rights still a bad grammar name okay give me two numbers away one in a way to and page negative two we turn to be self adding them together each number is given in a way format as an array of 0 and ones from the most significant bit to Lisa never can bit okay for example there's just some example I don't know me down that a number way in a waveform it's also guarantee tab no leading zeros okay I know a way as you go to see or just okay we turned those we saw of adding them in the same format okay man and in pace negative two I don't I've definitely done stuff in database before but definitely not in the last I want to say ten years so I had to kind of think about is a little bit all right let's I think for here I usually actually produce paper for this but obviously I need to set up some kind of pen and iPad type situation but I'm just gonna play around with one two inputs and then kind of see if I understand it so this is what they give to the like I used to know stuff about negative places Python so okay so I have an off I whenever even in the visualization so what is this even you costume your 11:00 is it tells you so costume your 11:00 is it tells you so costume your 11:00 is it tells you so what does it means to be Nick and base they get to so in basically they've to and it just means that it sounds like okay so how do I convert this to binary right well you know that for even yeah for even powers you could just I mean this doesn't change so I was two four eight sixteen so you can just sum these up you had 21 obviously that's not the answer because you have two negative powers they go to negative was it hey okay I mean that part is straightforward in theory I think one of the thing I'm doing to try to think of whether it's worth it I mean it might not be is kind of converting it to a number like a base-10 number in an atom and in a base-10 number in an atom and in a base-10 number in an atom and in converted back way I and I think in this case they don't want you to do it because they're with their wavelength is 1,000 so you can have a really 1,000 so you can have a really 1,000 so you can have a really big number for like two to the thousand which is I don't even know I mean digits what is that a lot of digits so you probably need to do that like in place and in this case I mean I wish take their input or not are not symmetric because I feel like you're going I guess the answer is not symmetric we're just good enough and it's still a little weird because people would get trapped above it by people I mean me okay so I think and yeah I just - 101 one zero one think and yeah I just - 101 one zero one think and yeah I just - 101 one zero one what is that so that's just five right so in this case obviously you got two and then now in normally with METEC you would carry what does carry mean in this case I mean that's the only trick well maybe not the only trick but one of the tricks so now there's a because it's not quite a carried it's like I'm weird okay I think this is straight for I mean straight for an understanding not to for solving no like weird note because I feel like there's always okay I think to get a better intuition I'm just going and sometimes I will wait to sell it is kind of just like look at the first K numbers and figure out what the representation is also one is just one two is four times two wait so it's gonna be a mouthful then four is that huh so it's all hmm that's an interesting maybe observations is that or negative of or base negative two numbers have to have odd number of digits maybe let's say that codes so five is eight times or eight minus three so eight is no wait eight is the negative one so five is actually 16 - negative one so five is actually 16 - negative one so five is actually 16 - where is it now five is just 4 plus one I can't no man getting confused here but 6 is the tricky one yeah maybe because 6 is 16 minus 10 right what a mouthful so my name is time so that's time which little bit confirms my odd number of digits I don't have that helps enough 7 is just 1 okay what does it mean to carry so actually just carry I think just cancels out because well carry under even powers can shout the lap next one just - powers can shout the lap next one just - powers can shout the lap next one just - Oh true the other way to her because if there's a carry by definition that means there's two of them and two of these because they have opposite signs with their number of the power that one bigger than their you even now okay so for example this is a and then it just will go around until happens if you I would carry and the previous number is zero it's not even possible okay let's try it so let's say you're this what is this number is that possible probably so that's a plus five so that's 13 minus five chance there should be a oops and this will be tuned this would be to this how does this carry well these to carry out from obese earlier to be zero hmm how do we get in come here well 8 is 16 minus 8 okay till then let's just say these two cancels out this actually goes to this and this right because that's just how you represent - I think I messed up represent - I think I messed up represent - I think I messed up somewhere right okay let's try again okay what is this number 16 minus 8 is 8 plus 5 is 13 and this is 5 Oh No why am i subtracting that's why my thing is a little weird criticism okay 18 okay so then these two cancels out and then this is a 2 which we can bring up to the previous frame okay and this is now 20 minus 2 so 18 okay I think that's essentially how I'm gonna try together hey I'm recognizing welcome back and I see you again so I was just in the middle of figure out what phase two means and I think I got some Vosges I think for carrying and I think this actually turns into a bit of a whatchamacallit state machine I think actually and maybe it's the state machine or like some kind of circuit type thing where like I mean and we go over a really way back on like arithmetic but if I carry and you have like you know so I think there's just some condition based on that I think the two thing I noticed is that while just adding is fine and then so yeah on so if we have so if that's it I mean we've didn't know carry bit is easy way but I say there's a carry there's two x and y which I think doesn't matter oh just some because it's X plus y which is going to express Y so carry and the bigger number is one then they cancel out so which means everything's zeros if the carry is one which because if there's no carry them we know how to do it then actually it becomes like one with another carry of one to the bigger one because it's going to be the power plus two minus power plus one is two Delta to get that carry weight I think I'm kind of make sense okay so that's what I'm thinking about it I mean I'd enjoy order you know the two did it three boolean table or whatever you pull it but we kind of did this but I guess there's another out carry we're just yeah okay I'll put this in code so we kind of thing but hopefully you enjoy watching me kind of take food is having this is a fun problem actually I don't know if it didn't do I mean mmm but we'll analyze it after I get it done because I think though it's always gonna be weird edge cases for me okay cool so add out numbers okay first thing I'm going to do is reverse the numbers to be least significant digits first okay just be worse right Trenton always confused sometimes I confused string helpful Rapids and already helping ref it's okay it's not giving me compile it hopefully that's good enough for me I mean here I was I would point it out but here does anybody give me anything but they don't give me another answer but actually I could do my thirteen plus five thing so that's also symmetric so I you know yet again in doing something not symmetric but I can just point out something else to make sure I agree with them so if you bear with me bearing with me with this hopefully with enough practice of a five on three I you know and that's what it is a lot of time where you're doing that practice you're gonna get more Katherine you've been silly things like sorting and reversing in this case and using library especially because like I could definitely I have some confidence about reversing a list manually myself but you know but when you're in a contest you know it takes a while oh yeah and blacks you'll be happy to know that I actually did the last contest and did pretty okay mostly in Python I think maybe I might I bow down and actually use your check but now I'm switching a little bit to use Python 3 as you notice oh yeah cool okay so now we could one thing I want to do is to an extend that's a Python stand to a wavelength just so that it's a little bit easier okay so the padding thing is actually that's okay right so it's actually what I thought it would be I don't maybe there's a library where okay okay and then there are we 1 to X next time I guess it's just times total doing this a little weird I mean it's functionally true so now tip off with length n which is great see ya I have too many years of C++ I've even I have too many years of C++ I've even I have too many years of C++ I've even seen argument C++ I've actually just seen argument C++ I've actually just seen argument C++ I've actually just mostly white C code with like a couple of libraries from the end to be honest like I don't know I don't even know how you see in and so on that funky stuff so I should know at some time a lot of things I need to learn those so that's besides the point so now we're saying this carry bit okay so let's just put to be so in a way one okay there's a little bit maybe six first why it could be to wait so that's why is it oh wait I could do it in there properly actually I could do that's just do Impa I could do in place but I wanted to do it in a way that I'll just make sure that I don't do anything silly okay here is Dustin - then that's fine when I went to even - then that's fine when I went to even - then that's fine when I went to even as we set the carry heavy he goes one and mmm used to be a most worried anyway right so okay it's maybe roughly right no think this is right but I want to see what it returns now and just as we were stired to beaver sit back doesn't look like it's right which is fine that we don't handle a lot of cases I think I didn't even do half the things I said I was gonna do which is okay so if this is 210 its yeah okay - done like I'm trying to be too cute that's let's do this because the carry has a negative sign I think that's for that I was know confused about actually okay nothing now stuff possibly makes sense because it's a negative carry because a negative power oka but now I have to kind of make sure that I'm right because now we could have a negative one turn I Drive a negative one now that's the thing with this zero one okay I'll do you and Carius you go to one and current is you go to one just flipping the sign requires you to get two of the current thing which means is now the carry goes to the next one okay I think it's just this right yeah that way it could be treated not anymore okay hmm I mean one out two out three isn't so bad right okay actually remember this second test cases supposed to represent and how will you my mmm somewhat well somewhat very wrong that is but okay what is this I tell was my other case 13 plus 5 is equal to 18 so okay so I this what's 18 is 100 wait no this is 18 what's 13 no that's just to this one that says this is the wrong answer oh I'm getting along again Circle me so this is 21 plus 5 is you go to 26 which 26 is 16 all right just up to 21 so uh man 64 minus 32 minus 8 that's 24 plus or minus 2 is that right 26 all right let me do my math real quick that's 24 2000 K which means is something like 7 yes that's right minus 2 plus 4 minus 8 minus 32 plus 64 so the answers oh my I'm looking at the expected output okay boy am I so walk okay let's walk through this I have work for how I would solve this okay first of all that's out there so this is zeroes which becomes a carry which becomes one with an additional carry which just becomes 2 which okay let's try again and I did too fast I think I confuse myself okay so this prompts to so we raise it and then over carry on here okay so you have a negative carry this is negative one you set it to one with another carry and analysis to it and become zero with weight this is a negative value and positive carry maybe that's where I got confused oh well first I have to add first that's why so now it's two and then now one from the negative carry but then I don't carry hmm okay I think my carry has to maybe be signed a little bit weird and dad's too tricky for it let's hear it becomes one but it should be an additional carry right hmm because this carry is that it needs negative weight okay oh give me one more try okay this is too okay that's fine so now it is negative they could have carry on this count that's right and I don't think encode I did it to anything else look at Carrie well now it's a negative this is a negative one actually which we flip to one an additional tab as we wonder plus four and there are a lot of double negatives in my head I'm thinking for that's when I'm you wondering what I'm thinking about I'm just trying to think of that's all this makes sense yeah that's where you get the chewy you do want one of those more yeah because you do need to flip this sign you want you don't want just a regular you want the negative of whatever you okay maybe that's makes sense yeah what are we well I'm still not confident about this to be honest because I think I might have let's try some really base case there's just one past one which should be two which is four times more four minus two so it okay is there a way to get only one carry like I have this weird thing which I don't explain which aren't good always gonna be true where just a negative carry bit how do I get a negative carry bit I guess you grab negative numbers actually I didn't really think about it so okay that's true so you have that satellite so this is a weird thing really man I guess so all right that's just Yolo I'm sure I'll find it each case of this isn't right it's yeah okay oh I did I don't know whatchamacallit I don't kill leading zeros okay fine I mean I'm okay with this in well I'm okay in the sense that you know that's something that I know I didn't take a concern to versus something that like you considered but it's wrong so you don't know how to solve it I mean here it's kind of like you know I mean I still need to do better but that's another thing but yeah I just have no leading zero we turn it is in the way of zeros and ones with no leanings oh okay so I had to check the other one to where I guess this is the one and yet to check cuz can you get leading zeros in any other way maybe not right let's see I guess I'll do it before we were so it's easier Wow the last element is equal zero whoops pepper just one answer it how did I get a leading zero how does one know - is so in general can I can do one know - is so in general can I can do one know - is so in general can I can do things do in any other way that is in zero well I try a slightly bigger one which is this is 402 - - or something which is this is 402 - - or something which is this is 402 - - or something like that just want to check to try anything okay let's see again okay cool that's not that uh yeah so how long did it took me with all this you know thing about half an hour that we could be doing better we're done cool hmm I want to say about this I think if you get this an interview well one is good luck two is I think you know obviously articulate your thought process as much as you can as possible and then yeah and then just grind as much as you can like I kind of did here I don't know if I have any advice with this I like I feel like I have some intuition about this but not really to be honest so I think this is the sentry us how is it okay to him okay consider that next time everyone thanks but uh but yeah I don't know all right I like you get a problem like this way it's like very custom way one off like I mean I don't think you can see this on interview and II see if you are like when you do like it so I consider I like good enough whisk to not kind of like memorize this poem but and but you know maybe practice this problem just to kind of figure out you know what how do you learn to kind of I mean I think some of this problem kind of forced you to kind of remember how to do great school with my take of like figure out the calories and all that stuff and what does it mean I know that's not way but on in terms of like so maybe see if you can learn something from there but in terms of like memorizing this problem was something like that I don't think it's worth it sometimes if just like you just get bad luck I don't know I would imagine this is not on an interview but who knows maybe someone was having a bad day and giving you but I would say yeah I mean otherwise but that's just for interview yeah for in general yeah I mean over it's a fun form but I wouldn't expect this to me in any of you what's that well I mean it's just oh and where n is the number of digits because you just call in this addition so you go through it you know each pitch it up over the command it told me like a minute the line of code okay yeah cool yeah I mean I think that's what I'm saying I wouldn't expect to see this but yeah have you do then maybe I accept that it's not my day cool
Adding Two Negabinary Numbers
number-of-enclaves
Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together. Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`. Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros. **Example 1:** **Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\] **Output:** \[1,0,0,0,0\] **Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16. **Example 2:** **Input:** arr1 = \[0\], arr2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** arr1 = \[0\], arr2 = \[1\] **Output:** \[1\] **Constraints:** * `1 <= arr1.length, arr2.length <= 1000` * `arr1[i]` and `arr2[i]` are `0` or `1` * `arr1` and `arr2` have no leading zeros
Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary. Return as answer the number of nodes that are not reachable from the exterior node.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
null
237
hi everyone it's sorin today we are going to solve lead code 237 the lead note in a link list problem the problem is we are given a link at list and we need to return a node in it we are not given access to the head of the linked list and also the all values in linked list are unique and we have four requirements here so the value of the given note should not exist in the linked list the another one is the number of notes in a linked list should decrease by one and the all values before Noe should be in the same order and the all values after the note should be in the same order uh let's take this example in the first example we have 4 5 1 and 9 we are given access only so uh the node that is given to us is five is this node and we need to remove this Noe so how we can do that obviously we don't have access to the previous Noe to four so what we are going to do we are not actually going to remove this node but we are going to mimic exactly node that comes after it so what I mean by that for example in this case we have five right if we are replacing five with one and we are pointing that to nine then in that case we actually uh we are mimicking this note so the in this case this is the link at least that actually we want as a result so we have one and four points to our note we don't know what is this node so we don't have access to it we have access only to the node that we want to delete and uh we are replacing the value of it with the value that come value of the note that comes after it and we are pointing to the note that comes next to it so in that case we are as a result of it we get 4. to1 and 1. 29 which is exactly what we want as a result okay let's take this example 4 51 and 9 and we need to remove five that note so in order to do that we are not actually removing the note but we are mimicking the next note so what I mean by that the value of the node value is becomes node next value right so it becomes one and also the Noe so that Noe five is not now pointing to one but it points to nine so next is pointing not to one but it points to note next to n okay let's run it okay it works as expected time and space complexity since we are not using any space and the time complexity also would be a constant uh okay that's it for today hope you like my content if you like it please hit the like button and subscribe my channel see you next time bye
Delete Node in a Linked List
delete-node-in-a-linked-list
There is a singly-linked list `head` and we want to delete a node `node` in it. You are given the node to be deleted `node`. You will **not be given access** to the first node of `head`. All the values of the linked list are **unique**, and it is guaranteed that the given node `node` is not the last node in the linked list. Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: * The value of the given node should not exist in the linked list. * The number of nodes in the linked list should decrease by one. * All the values before `node` should be in the same order. * All the values after `node` should be in the same order. **Custom testing:** * For the input, you should provide the entire linked list `head` and the node to be given `node`. `node` should not be the last node of the list and should be an actual node in the list. * We will build the linked list and pass the node to your function. * The output will be the entire list after calling your function. **Example 1:** **Input:** head = \[4,5,1,9\], node = 5 **Output:** \[4,1,9\] **Explanation:** You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. **Example 2:** **Input:** head = \[4,5,1,9\], node = 1 **Output:** \[4,5,9\] **Explanation:** You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. **Constraints:** * The number of the nodes in the given list is in the range `[2, 1000]`. * `-1000 <= Node.val <= 1000` * The value of each node in the list is **unique**. * The `node` to be deleted is **in the list** and is **not a tail** node.
null
Linked List
Easy
203
1,095
hello guys welcome back to the channel so in this video we are going to solve the problem which is today's daily lead code problem lead code daily challenge so I haven't solved this problem yet and I have just tried this problem on 26th of July I think so let's just read the problem statement and try we will just try to build the logic I haven't thought of this like how to solve this yet I'm going to solve this problem live you can say you may recall an array Mountain so I read the problem a long time ago so I have to just read the problem once again and understand what it is saying you may recall an array Mountain array if it is length greater than three okay there exist some I with 0 to length minus one so that okay 0 to till I it is in increasing and from I to length minus one it is decreasing okay given a mountain array uh what is this ar oh this is a class that has been defined here fine return the minimum index say that mountain. get index do get Returns the element of the array at that particular index okay uh Mountain harry. get index equals toal to Target we have to just return the minimum index so that this condition is satisfied and if there is no such index then return minus one fine uh you cannot access the mountain error directly okay submissions making more than 100 calls to the mountain. get will be judged wrong that is why I was getting a wrong answer because I have just uh implemented a br Force where I'm just iting over all the elements and checking the first element from the left that is equals to Target that is what we have to return here so the brute force can be just activate for all the elements and return the first one but that will that might make more than 100 calls and this will be justed wrong as per their statement so what else we can do here one thing that is obvious that the elements will be in the form of mountain okay and elements are strictly inre or not let me check okay there can't be same element there can't be same adjacent element so every element is unique and strictly increasing okay means basically on the from Peak to left hand side all the elements will be unique that is what I'm trying to say so the elements will be in the form of this particular Mountain there will be some Peak like here it is 1 2 3 4 5 and after that 3 1 3 and 1 so this is what uh in the in this form the input has been given to us and we have to just output the first index that is equals to the Target uh let's suppose the target is three and this was not equal to three else it will it is four and it is five and this one is six then in this case we have to return this index because this is the first index where we are getting uh number equals to Target so what do you think what we can do in this problem let's first build a logic then we will try to implement this one thing that I can observe here is if we have been given some Target then that particular Target can be found on the left hand side okay and on sorry on the so that particular Target can be found only on the left hand side once or right hand side and since our array is strictly increasing if I divide this in two parts then in this part my array is increasing and in this part AR is decreasing uh as you can see that here is monotonicity so and all the numbers are unique also so we have it's just a standard binary search problem I think where if we are dividing the ARR into two parts from Peak to left hand side and from Peak to right hand side then on the left hand side we have our AR sorted and we have to search for a Target value if we are getting the Target on the left hand side then we have to return the index otherwise we have to search for that particular Target on the right hand side because on the right hand side the AR is the array is also sorted in the decreasing order and we also look for Target in that particular search space so I think it is just a standard binary search problem where we have to find the peak element and apply binary search on the left hand side and on the right hand side yeah this is all about this problem I think so let's just try to implement this and see what we are getting so for implementation purpose first of all what is our Target we have to find the peak value so that we can divide the array into two parts like the array is given in this form we have to find this particular thing this thing so that we can apply boundary search on the left hand side and on the right hand side how can we do this m let me just Implement a function that will return with the peak find PE and it will Pi Mountain arrrow as input and in this particular thing I have to find the peak value Peak and also Peak should be found also we have to find Peak in less than 100 calls in overall the call should be less than 100 so let's just first of all trying to analyze the time complexity Here length is 10^ length is 10^ length is 10^ 4 so in search first of all you have to search for Peak that will take uh order of login which is almost what 17 operations then we have to apply binary search on the left hand side which will cost us 17 operation at Max this is approx value and 17 values for the right hand side so 51 calls in worst case Okay this will work yeah so first of all I'll take left hand side equals to Z and right hand side equals to do length minus one or we are just finding P so just take leaving one elements on the both hand side now we have to apply binary search in order to search the peak element to F left is and right and how can I get the uh first of all find M mid equals to left plus right minus uh left by two after that if I'm searching for Peak then uh what I can do let's suppose I want this number so if this value is greater than the this will be three and this will be two greater than this one so we have to shift our right to Mid minus one so mid if uh how can I get the value ARR Dot get mid if the mid value is greater than array. get mid + one is greater than array. get mid + one is greater than array. get mid + one then in that case we have to shift our right to Mid else we have to shift uh just left to+ to+ to+ one return right because that will be on the position so yeah this is the peak we have found the peak value let's just check that if we getting right or not in PE equals to find Peak M compilation why error length oh sorry was a spelling mistake so we are trying to find the peak first after that we will see what we have to do uh 0 1 2 3 and four this is the peak yeah working fine now what we have to do we have to apply binary search on the left hand side so I'll make two functions in binary search left which will take uh two arguments Mountain array and Target value after that we have to just apply the standard binary search in this particular range in left = to0 and in left = to0 and in left = to0 and uh actually for finding this particular thing I'll pass two values in left range and right range so while left is less than right less than or equals to Right End midal to left plus right minus left by two and if our array. get mid equals to arror get mid if our Target since all the numbers will be unique because they're strictly in so we don't have to care about that multiple threes will be there consecutive threes so just if you're getting the value equals to Target then just return mid else if uh ARR do get mid is less than Target then what we have to do less if it is less then we have to shift all left to m + one and have to shift all left to m + one and have to shift all left to m + one and shift right to midus one fine otherwise itus one and one more function I'll make for to search on the right hand side which will be similar to this and just one chain because this will be greater then we have to shift that particular thing because the number will be in the reverse order on the right hand side I hope it is clear to everyone this is just a standard binary search on the reverse sorted array and this is the standard binary search on the sorted array in ascending order basically now I have to find the peak element Peak equals to find Peak Mountain array okay now I have to calculate an answer for left in left answer equals to binary search left which will take Mountain ARR and Target and this will be from zero to Peak we have to search and in WR rals to binary search on right hand side which will take two arguments M AR Target and the search space range which will be P +1 2 and minus one and what is will be P +1 2 and minus one and what is will be P +1 2 and minus one and what is in here Nal to m ar. l yeah and first of all you have to check first of all we have to give credit to the left hand side element because we have to uh return the minimum index so if left answer does not equals to minus1 then return left answer otherwise just return the right answer yeah I think I'm done with the code part I hope I'm not getting any compilation errors uh Mountain array what is the issue Mountain array okay it is Mountain aray fine here also we have to change it M ARR yeah I hope it works because this seems correct to me what is the error binary search left what's the issue red declared uh oh sorry I have to change the name of the function okay it is working on the samples let's try to submit this okay nice we got an accepted verdict here so it was just a standard binary search problem where we have to find the peak element and divide that into two parts and just apply binary s on the left hand side on the ascending order sorted array and on the reverse sorted array and this is just it just a standard B sour problem guys and the tag is Al given hard but it is not that hard if you know binary search and the overall time complexity the number of total calls as I have explained that this will take maximum 17 calls this will take maximum 17 and maximum so in total we will get in the worst case if I consider 60 calls because we had taking this also in the worst case just considered the to be on the safer side that it will make the 60 calls and we have been given the limit as 100 so yeah this is acceptable thank you guys for watching the video
Find in Mountain Array
two-city-scheduling
_(This problem is an **interactive problem**.)_ You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `mountainArr`, return the **minimum** `index` such that `mountainArr.get(index) == target`. If such an `index` does not exist, return `-1`. **You cannot access the mountain array directly.** You may only access the array using a `MountainArray` interface: * `MountainArray.get(k)` returns the element of the array at index `k` (0-indexed). * `MountainArray.length()` returns the length of the array. Submissions making more than `100` calls to `MountainArray.get` will be judged _Wrong Answer_. Also, any solutions that attempt to circumvent the judge will result in disqualification. **Example 1:** **Input:** array = \[1,2,3,4,5,3,1\], target = 3 **Output:** 2 **Explanation:** 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. **Example 2:** **Input:** array = \[0,1,2,4,2,1\], target = 3 **Output:** -1 **Explanation:** 3 does not exist in `the array,` so we return -1. **Constraints:** * `3 <= mountain_arr.length() <= 104` * `0 <= target <= 109` * `0 <= mountain_arr.get(index) <= 109`
null
Array,Greedy,Sorting
Medium
null
63
so in this video we are going to understand the unique path second right so we have already seen uh the I think in the first part of this uh playlist the unique path right so this is the third part third video of this uh you can say playlist right the 63 unique path second so what we have to find here let us understand from the question so you are given a matrix M cross n integer in the grid right that is an array so there is a robot initially located at the top left corner as you can see here in the example that is at 0 uh position in the grid so that bottom line is how we are going to Traverse from here to here at the bottom right top left corner to bottom right corner how we are going to do that we are going to understand so first we have to understand the initial position what we have so initial position at zero that is the top left corner and we have to reach what at the bottom right corner that is ah you can say m minus n and M minus 1 and N minus 1 that is the last row last column and that is called the grid M minus 1 and this one okay so the robot can either move downward or rightward at any point of time so there is an obstacle right and space are marked as one or zero respectively in the grid right so obstacle ah as one and a space as a zero means if obstacle is coming so he cannot move right so a path that robot take cannot include any space that is an obstacle right we have to return the possible unique paths that the robot can take to reach the bottom right corner the test case is generated similarly to 09 this case so we can see later don't worry so obstacle grid we have given like this right zero and there is one here as you can see and the rest of the r0 0 okay so he cannot travel through the obstacle right because apart that robot takes cannot include any square that is an obstacle this Square he cannot take right so how is how he is going to move right so there is one as there is one obstacle in the middle of the greedy as you can see here in the figure right so this is Three cross three grid right so there are two ways to reach the uh bottom right corner either he can go from here to here or either he can go from here to here right means he can take right and then down and he either he can take down then right okay so this is the second question of the unique path you have already seen the first part path of the unique right in which what how we are going to calculate for calculating the DP at uh let's suppose uh I and J right what we are going to do we are taking Grid at uh let's suppose I and J the current value at the grid plus we are calculating DP at I minus I plus 1 take I plus 1 and J and we are taking what DP at I and J plus 1 okay and which one is minimum right we are calculating and that we will store into the current value of the grid and that will come as a grid here right so the similar questions we have in this ah unique path but only things we have added as a obstacle we cannot include the obstacle path right you can see the another question another example right so here is obstacle so he cannot take this path right so he can take only one path so there is one only one answer right now coming back to here right you can see the figure and you can understand how he can go right he can start from here and he can move like this as he is moving right so at the last he will reach at this position how he are going to starting from here right he can go like this okay let's understand how we are going to find so first of all we will calculate rho and another will calculate column now at 0 is nothing but 1 right if this obstacle gate contains one means we are not going to do anything we will return our control there only okay so it is saying that if obstacle is already at the first grid okay so first of all let's suppose what we are trying to do here let's suppose is obstacle is already here right so how he can move right he cannot move so we will return from him there only so this should also be your case right case like with starts with ah obstacle start with obstacle right so we cannot move next we can Mark 0 as 1 now because we have already done right now from I 1 to um rho First Row 2 the last row will move right how will move that we are going to see the first is I write I and 0 right so 0 will remain same right here in this case and I will get change right so for all the row we are coming from here to here okay next time we will move to here right two path is here so I will go with the first for the downward right this is for the downward and this is for the right word right that's why we are going for i 0 to ah you can say ah row and this is for the column that is right word okay so that is why the zero will remain same and how we are going to find will check if I zero is at 0 means we can go and it shouldn't obstacle should not we will take minus one zero right and if equal to one we will return one otherwise zero if it is equal to one right then we will return one otherwise return 0. similarly we will do for the column will pass the same value 0 and I minus 1 equal to this at this right now for row and column ah we'll do right so we will start from one to one ah for the row and another for Looper column will check if I and J equal to 0 then we will calculate obstacle I minus 1 and obstacle J minus 1 right you can see and we can find your value as you know that now I will take I otherwise what we will do we will pass I and J is equal to zero we are not going to do anything ok and at the last we will return R minus 1 and C minus 1 means we calculate from here last grade last sale of the grid right and we will return the value got it let me recap one more time so we are taking row and column will take initial value if it is equal to 1 we will return 0 right if not then we will Mark ah 0 as 1 then we will start from all uh one all the row and will check if it is equal to 0 and this I minus 1 and 0 right is equal to 1 right if this is the case that we have already done right if this is the case it means what we will put 1 right otherwise 0 okay and this way sorry in this way we will increase so what we are trying to do here is we will start from here right so we will Mark after moving we will Mark right we will mark this position as a one if obstacle will take we are not doing anything okay otherwise we will mark this line so that it will become like this so he is starting from as you can see here right he is starting from here some position he is moving this if that is not the case he is marking as a one like this he will Mark and the last you can see here he is starting from here he will marking his marking and he is calculating two path two part in the last he has two path okay like this so that is why either will pass one or zero if obstacle at I am means row that row 0 if it is 0 and minus 1 0 if I have one right it means we have to pass one okay otherwise zero similarly for the column also if it is equal to ah 0 or I minus 1 0 and I minus 1 will pass then will be convert this one you can mark this as J also so it will be completely easy for you now uh for the I and J will move and we'll check if it is equal to 0 right because we have already marked all this one right so if it is equal to 0 we'll we will find the value at this position and value at this position if both are 1 then it will become 2 at this position right otherwise we will mark it as 0 only and finally we will return at here and that's why we are ah coming initially we have already marked or everything and then we are updating the value right 2 otherwise the rest of will remain zero so finally at the last grid we will return this value okay I think you understood so complexity we are going through all the row and column but the space complexity is of 1 okay so thank you guys thank you for watching this video If you like this video please uh watch the another part of this series right in which we will see the tangle question right and thank you for watching please subscribe and please check out the whole videos in this playlist
Unique Paths II
unique-paths-ii
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle. Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The testcases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** 2 **Explanation:** There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right **Example 2:** **Input:** obstacleGrid = \[\[0,1\],\[0,0\]\] **Output:** 1 **Constraints:** * `m == obstacleGrid.length` * `n == obstacleGrid[i].length` * `1 <= m, n <= 100` * `obstacleGrid[i][j]` is `0` or `1`.
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] else obstacleGrid[i,j] = 0 You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem. if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j] else obstacleGrid[i,j] = 0
Array,Dynamic Programming,Matrix
Medium
62,1022
4
hello my friends my name is Alexander barmin and this is my new YouTube show lead code with me where we solve lead code challenges don't forget to subscribe to my channel give me a like and write a comment so what's in the agenda for today we're going to have our first hard level challenge and we will solve it gracefully without any doubts let's get started and go ahead okay this is our first hard level coding challenge and on the very high level it sounds quite simple we are given this two sorted arrays nums one and nums two of size M and N respectively return the median of the two sorted arrays they were all around time complexity should be all log M plus n okay this is quite hard but let's see what we can do and before we start we need to understand what is median so this is my array for example one two three four one two three let's start with it so median is an element which has a position in the middle of array so what does it mean so this is my array one two three it has three elements so element V is in the middle is two so this is median two because my array has all number of elements it is uh always a cynical element so in case if my array has more than one element this is where median stays so it is between two and three so in order to calculate the median I need to summarize and I need to add 2 to 3 and divide it by half okay divided by two previously known by half so this is uh overall idea of this task so roughly speaking let's try to solve it in the simplest possible way so we have to arrays of nums one and nums two what can we do if we don't want to think we can try to create a new array which will include um all elements from both the arrays nums to dot length and next we need to put elements so let's use system array copy from every one from position zero I will copy to every all starting from position 0 to nums one length so this is elements from the first array system array copy let me copy from and re2 from position 0 to array 0 so 23 all and starting from insert element from nums length one and I need to include lengths two so and what will I have at the end it will have array of all elements which is twice longer than uh maybe not twice longer but the its length is equal to sum of length of both the initial arrays and what I need to do next I need to sort my new array and in case if for example a length of my array is equal to one I need to return all zero element in case if my array has uh all the number of elements music will uh what I need to do I need to find an element in the middle so what I need to do for it I need to uh distract one and in case if my array has even number of elements I need to calculate first uh roughly speaking lift element to do that I need to take Elementary index all land divide by two final end all right which is equal which I'm taking from here again all length divided by 2 minus one and next I need to return a double uh left or last right divide by two write and divide by two it should work let's see how it will yep it works uh let me even try to submit this approach this solution we will see at the end of day um yeah it is accepted but I don't think it should be a very good approach because see it shows that it beats only 25 percent of all the submissions which is not so good as it could be let's get back to the description and description gives us a quiet interesting hint so hint is we have two sorted arrays so that we don't need to sort them and what we need to do we need to actually find the median of two arrays yeah this is a several goal but we don't have to join this arrays we can iterate through both the arrays using two pointers one pointer will point to the first array second pointer will point to the secondary and we need to iterate to end element in our let's say overall array which consists of these two and ID is that this nth element will be a median of the both arrays so we just need to iterate through one array till roughly speak until the middle of it second array till the middle of it and next just speaking take the element which is on nth position which is in the middle let's try to implement it this time it will be bit harder so what they need to know first I need to know full length of both arrays nums one length plus nums to length why do I need to know it because I need to know uh is it's odd or even so what I need to do in order to determine it full length equal to 2 divided by 2 is equal to one so full length so in case if I have a rest which is equal to one it is odd if the rest is equal to zero it is even so what next I need to do next I need to understand what will be the last element I need to iterate to in both arrays for example it's important that in both arrays last element will be index of last element will beam uh full land divided by two plus one what does it mean so uh I am always iterating over to arrays let's imagine the scenario that I have these two arrays one two three and four so full length of them is four and I need to find indexes of these two elements of elements with values two and three uh their indexes is one and two correspondently so full length is four and last one element I need to iterate two is two has index two so this is my full length of them is four two plus two I'm dividing it by two uh four divided by two e is 2 and plus one is three uh because why it is free because I will iterate to the element which is previous before the uh before the element in the middle you will see it in the moment let's imagine the different use case when I have elements we're gonna have array of these odd number of elements and in this case I need to iterate on I need to find this element which has index one this is index of the index of this element and again so full length uh full size of both arrays is three divided by two is one and one plus one is two so I'm iterating to the element which is previous before two so here imitation before 2 here I'm integrating to the element which is uh before free so this is how it works so what else I need to do I know that I need to save my current element and previous element because in common scenario and common scenario I have I may have an array of which has even number of elements so that I need to know my current value in previous value so let's have two variables current which is equal to zero and previous which is all this equal to zero and I need to know uh indexes my pointers in both the arrays so current will have a value of my current latest element previous will have a value of the previous elements so for example if I need to iterate 2 through 1 2 3 current will have value free at the end previous will have value 2 at the end in case if I am iterating over visery current will have value too previous will have value 1. this is quite important for us because uh roughly speaking in case if my array is odd and it has odd number of elements I don't need to do anything I can just return my current element my last red element but in case of my array has even number of elements what I need to do I need to div I need to summarize current plus previous and divide it by 2. so this is a very idea what else I need to do obviously I need to scroll to the last element in two arrays in order to do that I'm again using while loop in case if index 1 plus index 2 is less than last uh element this is my last element is always greater than um is always greater than LM than index I need to scroll to it is always in this scenario it is free one zero one two three so I'm scrolling up to third element excluding third in this scenario up to Second element excluded in second zero one two is excluded I'm scrolling only to the previous before to the element before two so that this is strictly less and I need to store my previous which is equal to current so because I'm again sliding my Tuple uh over my arrays and here I have a quiet simple approach so in case if index 1 is less than nums one dot length and index two is less than it means that both arrays I mean little I am in the middle of both arrays at the moment so what I need to do I need to take the smallest element I need to read an element from the smallest element so in order to do that I need to compare nums one at position index one with numps do at position index two and in case if this condition is true I need to read from array 1 from nums 1 at index one and then moving index one step forward otherwise I need to read current from nums to index 2 and move second pointer one step forward so a second condition so first condition only works if I'm in the middle of both arrays so let's assume a scenario then second array is over so in this case index 1 is less than nums one length and I'm reading only from the first array so current is equal nums one index one plus and the third possible scenario is I'm reading from the second array only current is equal to nums to index 2 plus so what I'm doing here I'm just scrolling my pointers to the middle of concatenated arrays in this case a complexity of this approach is oppa or full or it's a it's typo in this case complexity of this approach is much less because I'm not reading I don't need to concatenate arrays I don't need to sort both of them what I need to do I need just to iterate over all of them so in this scenario complexity even less than o log M plus n because it is it has complexity all from n plus n and as you may see this is a super cool solution which beats 100 of users who use this Java so be smart that's it for today we hope you enjoyed the video and if so please don't forget to give me a like write a comment and subscribe to my channel see you next week bye thank you foreign
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays. The overall run time complexity should be `O(log (m+n))`. **Example 1:** **Input:** nums1 = \[1,3\], nums2 = \[2\] **Output:** 2.00000 **Explanation:** merged array = \[1,2,3\] and median is 2. **Example 2:** **Input:** nums1 = \[1,2\], nums2 = \[3,4\] **Output:** 2.50000 **Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5. **Constraints:** * `nums1.length == m` * `nums2.length == n` * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` * `-106 <= nums1[i], nums2[i] <= 106`
null
Array,Binary Search,Divide and Conquer
Hard
null
1,029
hey everyone nitish aside hope you're doing well so let's start with your question so the question is two city scheduling okay so a company is planning to interview two n people and given the array cost so where cost i equal to eighth cost and b cost the basically the cost of flying the ith person to city a is at cost i and the cost of flying the ith person to city b is b at costa okay so you are given an array basically a 2d array in which one is 8th cost i and second is bs cost i and what you have to do you have to return the minimum cost to fly every person to a city such that exactly 10 people arriving each city okay so you are given a 2d array of cost and basically what you have to do like the zeroth element is representing the cost to a and the one element basically represent a cost to b so what you have to do you have to uh take people like it's a if you count as abcd so like two people will go to and uh one city and two people will go to other cities so the equal number of like the n people will if there is two n so and people will go to a city and then people will go to bct and you have to do this in the minimum cost okay so let's see with an example okay so let's take this example okay so uh let's say this is uh city a this b this a this is b this is a and b and you have one person let's give her index zero one two so you have four person and out of like four person uh in a two people will come and also in b two people will come so let's say like the first two will go to the 8th city so if we calculate the cost so for the 2 it will be 10 plus 30 and if i calculate for this so this will be calculated for b 50 plus 20 okay this can be a possible scenario so if we do the sum so this will become 40 and this will become 70 and if we do overall sum so this will be one temp so this can be a possible uh you can say output let's say like this uh zeroth person and second person go to a so this will be 10 plus 400 and let's say this one and three index or three people will go to city b so this will be uh okay like but b will be like six second index so 200 plus 20 so if we calculate the cost it will be 410 and this will be 220 and if we do the sum so this will be 630 so you can easily see like from this scenario we are getting output as 110 but if we change like let's say we take the second index we got our output at 630 but we need the minimum one okay so how we can approach this question okay so if you can see what we need is we need the minimum cost to reach to either to a or to b okay so in the zeroth index we need the smallest element similarly in the one index uh let's take it right on it let's say this is 1020 and this is 3200 okay so i want uh for a i need the smallest in uh index similarly i want for b i need a smaller index okay so how can i achieve that okay so for the a i know like i know um basically i need to know the smallest element similarly for the b i need to get the smallest element so what i can do is basically uh for if i have to give like this person will be go to a i don't have to care about the city b similarly if the person will go to b i will not care about this zeroth index okay i don't care like whether this value is bigger or like but this value should be smaller as like for the case of b similarly for the a case uh zeroth index should be minimum similarly for b i want the one index should be minimum okay so which means like for the zeroth index in the a the value is lesser so for the zero value is minimum but for b uh at this case the zero will have the maximum value similarly for one i will do not care so i can take a maximum value because i will send a person to zero city and in b i will i can send uh i need the minimum basically because but b i need the minimum output okay so what we can do is we can calculate the difference between them okay so let's calculate the difference between the cost of city a and cost of city b so if you calculate the difference it will be minus 10 minus 20 here if i calculate so this will be 30 minus 200 it's minus 170 okay and if i do the difference so this will be 350 okay and if i do the difference for this so this will be 10 and like i calculate the difference okay now what we can do is we can sort it's on the basis of difference why we sorted because uh we need the zeroth element as minimum as possible in the start and in the last we need the 1ith element as minimum as possible so what we will do we will sort it so this will become minus 170 this will become minus 10 and then 350. okay so if we arrange them in our 2d array so this will become you can say 30 200 then we have 1020 then we have a 10 of 30 20 then we have 450 okay so if you can see here we have them like we are not confirmed whether the zeroth element is minimum or not but one element is maximum which we will not take it similarly if you see for this case uh we have the minimum element hat here but we have the maximum element which we can skip it so which will we will skip this and our cost is also reduced so what we will do we will take a counter variable and what we will do lets take a quest value so this will be our array after sorting it so till half we will take the zeroth index and after this we will take the one at index okay so we will do cost equal to 30 then we'll do plus 10 so this will become 40. after this will come to here we'll do cost equal to 40 plus now we'll go for 20 and we'll do for 50. so this will become 110 so this is the minimum output we can get okay let's take one more example okay so let's take this example so what we need is at the start we need the smallest element at zeroth index and we need the one element smallest at the last so let's sort it okay so first sort them on the basis of difference so let's calculate the difference first this is minus 70 this is 40 minus 90 is minus 50 this is 0 this is 20 okay now let's sort it so this will become like this is already sorted if you confirm so minus 70 minus 50 is 0 and 20 okay so what we will do we will start from here and we'll take the minimum like till half what we will do let's write so till half will take the 0th index and after this we'll take the 1 at index so we'll take our cost variable so this will be 30 plus 40 this will become 70 and after this will commit here so we'll do 70 plus 50 which is one uh 170 so this is the minimum cost which takes uh for the city and c2b uh hope you got it so let's write the solution for this okay so first step is to sort it that is that sort posts we'll take a comparator class and we'll overwrite the compare function compare what we will do we'll take uh errors it's a 2d array what we have to do a difference of 0th index minus 1 index so this will be 1 and lu minus will do b of 0 minus b of 1 so this will sort our array on the basis of difference okay so the smallest zero index will come at here at the start and the smallest one at the index will reach to the end after this we'll take a cost variable and let's take a quartz dot length let's loop over till half and by two i plus and what we will do we will basically cost plus equal to cost of i zeroth index similarly we have to do for uh you can say for one index so this will be and divide by two this will be n and we'll take the first index and we just written our cost okay let's run it so as you can see this is accepted let's submit it okay so our code is submitted and the time complexity for this is like we are sorting the array so this is uh n log n and after this we are doing a loop over an error so it's an order of n so on an average so the bigger one so it's order of n log n and space is just order of one constant complexity hope you like it thank you for watching my video and do join the telegram group if you have any doubt any concern thank you
Two City Scheduling
vertical-order-traversal-of-a-binary-tree
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`. Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city. **Example 1:** **Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\] **Output:** 110 **Explanation:** The first person goes to city A for a cost of 10. The second person goes to city A for a cost of 30. The third person goes to city B for a cost of 50. The fourth person goes to city B for a cost of 20. The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. **Example 2:** **Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\] **Output:** 1859 **Example 3:** **Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\] **Output:** 3086 **Constraints:** * `2 * n == costs.length` * `2 <= costs.length <= 100` * `costs.length` is even. * `1 <= aCosti, bCosti <= 1000`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Hard
null
376
welcome to june thursday code challenge wiggle subsequence a wiggle seek sequence is a sequence where differences between successive numbers strictly alternate between positive and negative numbers the first difference if one exists may be positive or negative a sequence with one element and a sequence with non two non equal elements are truly wiggle sequence so for example we have the sequence one seven four nine two five which is it's a weak i'll say wiggle sequence because difference between uh one to seven is six difference between seven to four is negative three difference between four to nine is five difference between nine to two is negative seven and this is between f two three and five is three also between positive negative in contrast you have uh one four seven two five and one seven four five are not wiggle sequences because the first is uh not because the first two sequences are positive and the second is not because the last difference is no it's not zero so five is not zero and then we have a positive increase and a positive increase again which is why it's not a sub sequence is obtained but leaving some elements possibly zero from the original sequence leaving the remaining elements in the original order given a integer array numbers return the length the longest wiggle sip sequence of nums so we define the longest subsequence where it is uh basic of nums where is a wiggle sequence subsequence i should say so we see here the example given in this example the entire sequence is a wiggle sequence with differences as such and we see the bottom here the wiggle sequence is seven which includes everything up to um so you should i should delete this is one of the sequences actually you just delete um five from here all the fives for this sequence you have increasing so the longest wiggle sequence is actually any two numbers so one two and the rest is there you go the length of nums between one two thousand and length of index i is between zero to a thousand as well so you solve this using bigger and time complexity i think so from this the basic approach is that we the fact that a wiggle sequence must either end with a positive or negative difference so if we know this then we can come up with the current relation so that the maximum length of a wiggle subsequence must be a maximum length of the wiggle sequence subsequence that ends with a positive or negative difference so in order to kind of walk through that i'll just say we have a number that goes up and down so this is called up and down or peaks and valleys whatever you want to call it and this is going to be assigned to zero so this indicates the number uh the length of the subsequence that ends with either a positive or negative difference right so next thing you want to do is you iterate through the elements and if the difference in the next element was a positive then you add the previous speaker sequence you can add it to the account so for i in range uh length of nums minus one if the first number is positive then index i plus one will be um minus nums at index i is greater than zero so this means that if the first number is positive then we want to do is do the following up equals uh down plus one else if the number is negative that means that nums at index i plus one minus nums at i is less than zero then we want to update the down to be up plus one and then on all this we return so we keep on going back and forth until we figure um so we add one to sip sequence of the length in contrast so the difference between the next element is negative then we add to the previous element which is positive then we save the length and therefore we just want to return the maximum between the up and down plus one let's run this code so this is kind of using a dynamic programming approach there you go and this is using a big o of n um so big o n time complexity because we have a for loop here for space complexity we're also using uh big o of constant space because we keep everything we just find the maximum between the numbers alright that's it have a great day guys
Wiggle Subsequence
wiggle-subsequence
A **wiggle sequence** is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. * For example, `[1, 7, 4, 9, 2, 5]` is a **wiggle sequence** because the differences `(6, -3, 5, -7, 3)` alternate between positive and negative. * In contrast, `[1, 4, 7, 2, 5]` and `[1, 7, 4, 5, 5]` are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero. A **subsequence** is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. Given an integer array `nums`, return _the length of the longest **wiggle subsequence** of_ `nums`. **Example 1:** **Input:** nums = \[1,7,4,9,2,5\] **Output:** 6 **Explanation:** The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3). **Example 2:** **Input:** nums = \[1,17,5,10,13,15,10,5,16,8\] **Output:** 7 **Explanation:** There are several subsequences that achieve this length. One is \[1, 17, 10, 13, 10, 16, 8\] with differences (16, -7, 3, -3, 6, -8). **Example 3:** **Input:** nums = \[1,2,3,4,5,6,7,8,9\] **Output:** 2 **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] <= 1000` **Follow up:** Could you solve this in `O(n)` time?
null
Array,Dynamic Programming,Greedy
Medium
2271
1,192
welcome to april's eco challenge this problem is called critical connections in a network and you can see i missed it uh what are you gonna do there are n servers numbered from zero to n minus one connected by undirected server to server connections forming a network where connections i which is going to be a list of two numbers a to b represents a connection between servers a and b now any server can reach any other server directly or indirectly through the network so what that means is our graph is completely connected we can travel to any node even if it's like indirectly now a critical connection is a connection that if removed will make some server or servers unable to reach some other server so return all critical connections in the network in any order so we have this graph that's connected we could see that this line here is critical if we remove that there's no way we can come back from that so once we go like we can't travel to three if this is essentially a bridge uh from these two from the rest of the nodes these three nodes like unlike this one if we move one zero we can still travel from one to zero by going through two okay so here's our hint use tarjan's algorithm which is a dumb hint because i don't know tarjan's algorithm who's gonna know that but i did look it up and i'll do my best to explain it uh essentially what tarjan's algorithm is all about is there's this graph here is considered super connected but there's also uh sub super connected groups in here there's groups in here because this one is completely connected like this but this one here is kind of on its own it only has this one bridge that connects it and the way tarzan's algorithm works is we have some sort of variable that's going to be set to timer and we do it that first search through all the nodes but we'll also keep track of any back edges and any time we can go back and we'll store the discovery time so we start with zero this would be like one this would be like two three uh whatever but if we see that we could go back have gone back we'll update our discovery number to be the lowest one between the two so what that means is what we'll have is two um data structures here we'll have uh just an array for discovery and this is just like when was this node in order discovered like when do we travel here so this will just be an array this will be the low and the reason we need this low we actually need to keep track of both because if we just updated discovery then that's just going to make everything all the same since it's completely connected so this target's algorithm basically allows us to create these subgroups what we'll have is self.time this needs to be self because self.time this needs to be self because self.time this needs to be self because i'm going to do a depth first search we'll start with zero and we'll also need to create an adjacency list or some sort of graph uh to be able to do our debt for search so let's see what else do i need a visited set to keep track of the ones i visited as well as our output it's going to be a list and as well as a graph and the graph is just going to be a default dict with the nodes being the key and lists being all the neighbors i can go to okay so first let's create our graph so for sourced target in connections we know this is bi-directional right so we can actually bi-directional right so we can actually bi-directional right so we can actually append it both ways we'll have our graph from source and append the target we'll also go to graph target and attend the source now this is going to allow us to do our debt first search and we'll have to write it here our def search and what we'll need to pass in is our current node but we'll also need to keep track of our previous one and the reasons for that are a little complex but uh just know that if we have the previous one that's at the very least gonna allow us to know when there's gonna be like let's say we came from the previous and now we're at the current we don't want to just go right back to the previous one right because obviously it's bi-directional so that obviously it's bi-directional so that obviously it's bi-directional so that doesn't make any sense so we'll have that to keep track of all right so the first thing we want to do is add to our visit set so that we will not travel to this node again and we'll also increase our time by one okay so the first thing we want to do is update our discovery of the current as well as the low because of the very first time we visit it's going to be the same and this is going to equal the self.time and this is going to equal the self.time and this is going to equal the self.time now to do our debt for search we'll say 4 let's call it next in graph uh current we gonna have to write a couple things here first thing we need to check is well if it's not visited then we just do our depth of search okay so if it's not visited let's do our debt for search but we'll also need update our low um in case the next lows were lower so let's see if next not in visited what we'll do is get the search of the next and now the current is going to be the previous one and we'll update our low cur to equal the minimum between the low cur and the low next because whatever that updates to that's going to be there okay so we also have one more thing we need to check well if the next does not equal the previous okay so we accounting for you know we're not going to go back and forth uh when that happens we actually want to update our occur to go the minimum queen will occur and this time uh we want to get the minimum between the discovery the next okay now finally if this is a bridge uh how can we tech no that's a bridge well essentially like if this low dot next if this is greater than the discovery of our occur that means that once the this shouldn't happen if there was a way to go back like our discovery should always be greater than the previous ones but if we find that the low necks is actually greater that means there was there's no there's not going to be another way there was never a way in this definition that we can actually like lower that so what that means is this is a bridge so we'll append that to our list here and what we'll need to it doesn't actually matter we can say current next or next current uh but we'll just add that to our outputs and finally that would be it so just call our default search string will be zero and the previous just make it negative one and return our output let's see if this works okay so that does look like it's working let's go ahead and submit it oh there we go accepted so time complexity wise it's all of n because we travel to every node just once because of our visit set but we do use open space because of all these you know visited discovery all sorts of stuff so we do use extra space um now i'll be the first one to admit i don't understand how this works it somehow works i have a kind of intuition of how we're dividing these groups up like if i were to print the low end discovery you can kind of see what it's doing um see like this is the discovery it's just gonna be in order one two three four but you can see with this low zero one two three i've all been initialized to the same group here all ones this one though four it's kind of not been updated and what that essentially means is like these three are group and this one is kind of its own group so this connection here once we remove it that's a bridge like because this is the only connection um if this usually in tarjan's algorithm it looks like it's directed connections um so this is undirected right so it's a little bit tricky to like understand i don't fully understand how it works um i think the big takeaway from this problem for me is i really need to study more graphic algorithms because i only know dextrose and this one like really just threw me off so all right i hope that helps if you don't i don't think i explained it very well um but if i really want to explain it better i would have to like do this deep dive and just don't have time for that but i will come back to this one day okay because i would like to understand it better okay thanks for watching my channel remember do not trust me i know nothing
Critical Connections in a Network
divide-chocolate
There are `n` servers numbered from `0` to `n - 1` connected by undirected server-to-server `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between servers `ai` and `bi`. Any server can reach other servers directly or indirectly through the network. A _critical connection_ is a connection that, if removed, will make some servers unable to reach some other server. Return all critical connections in the network in any order. **Example 1:** **Input:** n = 4, connections = \[\[0,1\],\[1,2\],\[2,0\],\[1,3\]\] **Output:** \[\[1,3\]\] **Explanation:** \[\[3,1\]\] is also accepted. **Example 2:** **Input:** n = 2, connections = \[\[0,1\]\] **Output:** \[\[0,1\]\] **Constraints:** * `2 <= n <= 105` * `n - 1 <= connections.length <= 105` * `0 <= ai, bi <= n - 1` * `ai != bi` * There are no repeated connections.
After dividing the array into K+1 sub-arrays, you will pick the sub-array with the minimum sum. Divide the sub-array into K+1 sub-arrays such that the minimum sub-array sum is as maximum as possible. Use binary search with greedy check.
Array,Binary Search
Hard
410,1056
17
foreign question number 17 there are combinations of a phone number so first let's read the question given a string containing digits from 2 to 9 inclusive written all possible letter combinations that number could represent the answer in any order a mapping of digits two letters just like on the telephone buttons is given below note that one does not map to any letters so here 1 and 0 does not map to any letters so there's only mapping from 2 to 9 inclusively let's see how to solve this problem so whenever you encounter this kind of combinations and permutations problem you supposed to visualize in the form of tree binary tree or any energy then the off of the problem will be solved let's see how to solve this problem using like visualizing the tree so first let's take the first example let's take first two three so this is the zeroth level we have empty string so first letter first number is 2 so from these two we can start string with any three of these letters a b c so B C so not 2 is done you can cross it out next number is 3 and 3 we have d e f you can map each of the letters from 3 to this graph so that means a will be mapping to three letters from three so it will become a d a f so again from B also b d b a b f from C D CA CF so this is the solution that we've these are the possible combinations of two digit number um now let's increase one more number let's take two three four three completed again four we have g h i so here again the tree grows in the form of n for n a d g a d h a d i so like this Tree Grows you need to call this process recursively until all numbers gets completed so at the end of every base call you need to store the results now let's see the time complexity for this solution so if we take this is a zeroth level this is the first level this is second level and this is third level so here so it will become three power one that means three outputs we got so here 3 Square here we got nine outputs here 3 Cube in this level 3 we got 27 outputs here you can see Indian 9 in the keypad we have four letters w x y z so in the worst case the string will become length is 4 so it is 4 power n in the worst case if the string starts with the letter nine the number so and again at every stage you generate a one n string output that you need to map and show it in the results it will take n time to concaten it all digits in it from the tree so the total time complexity will be n into 4 power n now we will see how to solve this problem with using the recursion in python as well as Java so now let's write code in Python here I already created the on empty dictionary which contains all mapping letters so first we have to check for base case if digits equal to empty that means you have to return empty array that oh that's in the length equal to length of digits creating one empty area to store the results now let's create a function DFS step for search function which takes the two arguments one is position and another one is string to track the combination of the string over the recursor calls so if the position equal to length simulator right create this function inside the function if it is equal to length then we supposed to append it to the result dot string else that means still some more questions are left we need to map to the previous string so in that case extract the letters from phone so the position which we are going to extract is digits of position so we get the position from the we get we have the current position with that position we find the which digit we are going to mapping next we take the digit and we cross check with the phone dictionary then we take out those letters and we iterate through iterate to through all letters and we make a recursive DFS call foreign letters AFS now we need to increment one position then add it to the existing string so then finally call this function DFS starting with zero position and with empty string and finally return the result so now let's write code in Java here already created one hashmir Panda inserted the required values into it now first we have to check the base case if digits equal to null or digits dot length equal to zero return one empty array list now let's create the main DFS function so first private void DSS so first we pass the position that we use to find like where we are in the digits next string of digits next string Builder next the result list of string result then finally map of character on string yep so we are taking the one two three four five arguments now first we need to check the base condition if position equal to digits Dot length is supposed to add it to the results that string that we traced back for the recursor calls result dot add Str Dot to string then return else you need to take the current position from the digits and get the digit get the information from the map phone dictionary take those letters and iterate about those letters and again call this recursive call VFS recursively so for that string temp let's say letters pull to map Dot get digits Dot here at of position per in I equal to 0 I less than let us dot length I plus now you need to add this string like add the current or E take each letter and add it to the string and call the DFS call so string dot happen let us Dot hear it I Now call this DFS function recursively and DFS increase one position digits on a string test result then map now decrease the string length Str Dot set then set length PR dot at least length minus one so it's pretty much for this function it's almost completed now we supposed to call this function in the main function list of string result equal to new array list all this DFS function start with 0 next digits initialize new string Builder and result then map phone dictionary turn result thank you guys I will see you in the next video foreign
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
112
what's up everyone today we're going to go over lee code 112 valid path sum first we'll look at the input and the output then we'll look at the diagrams and finally we're going to look at the code and complexity the input is going to be a binary tree and an integer called sum and the output needs to be boolean true or false if we can go from the root all the way down to a leaf node such that the numbers in that path add up to this sum so for 22 we have 5 plus 4 9 plus 11 20 and 20 plus 2 22 so we return true any path from the root to leaf is valid if we can have a valid sum so only one is required the output to be true here are the diagrams what we're going to do is take our sum and pass it in to our children so the parent is going to pass its child a parameter sum and it's going to say okay every time i pass from myself to my child i'm going to subtract my value when this parameter and the recursive stack gets down to a leaf node the leaf node is going to check okay we've subtracted every single ancestor or parent from the original sum by the time it gets down to me the value should be equal to the value of the leaf node if it is then we found a valid path sum so top down void versus bottom up boolean what's the difference here the return type is going to be void whereas here the return type is going to be boolean here we're going to pass the original sum down so 22 is going to be given to 5 and 5 is going to subtract itself from 22 to its children so 5 is going to give its left and right child 17 4 is going to give its love child 13 8 is going to give us left and right child 9. so on and so forth and any time we get to a leaf node what's valid so the valid is where the value that's given in 2 is equal to itself 2. we have a global variable that's going to be a boolean true or false and if we get 1 that's sufficient and we know we can return true here what we have to actually do is give the sum to our children and it's going to do the same thing subtract the value and if something is true it's going to actually return up so this one is true so it's going to return true green is true whereas orange is false so all they're going to do is bubble up with the or so false or true and this is false so they're both going to return false ultimately we return true let's compare the two versions of the code here's the top down void and here's the bottom up boolean for this version we're going to have a global variable called res and we're going to use it to see if any of the leaf nodes that we visit satisfies our condition if it is we simply return res so here's a recursive function if the root is known we return otherwise if we're visiting a leaf node we're going to see if the number that was passed in through the sum parameter is equal to the value of the node we're visiting if it is then yes we found a valid path sum so we just set the global flag to be true that's pretty much all we have to do otherwise we simply recurse left and right and subtract the roots value from the sum parameter that was passed in for the bottom up boolean we have to actually wait for the leaves to return their answers so here we're just going to call it and we have a return type of boolean keep in mind this return type boolean is different than this void tie boolean if we have a null root we return false otherwise once again we check if we've seen a leaf node if so we compare the sum that was passed in to the value of the root and if it is equal we return true otherwise we're going to return false otherwise what we're going to do is just recursively call left and right and we do an or on both the branches this is because we only need one branch to be a valid path sum so if any of the truth from the left or right bubble up then that's fine to get all the way to the top time complexity is going to be o of n because we have to visit every single node and the space complexity is going to be of one because we're not using any additional data structures sort of state or anything like that of course if you consider the recursive stack to be space then the answer is going to be different but now i'm going to take it as constant so that's how you solve leak code 112. if you like the video please thumbs up and if you want to see more don't forget to subscribe
Path Sum
path-sum
Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22 **Output:** true **Explanation:** The root-to-leaf path with the target sum is shown. **Example 2:** **Input:** root = \[1,2,3\], targetSum = 5 **Output:** false **Explanation:** There two root-to-leaf paths in the tree: (1 --> 2): The sum is 3. (1 --> 3): The sum is 4. There is no root-to-leaf path with sum = 5. **Example 3:** **Input:** root = \[\], targetSum = 0 **Output:** false **Explanation:** Since the tree is empty, there are no root-to-leaf paths. **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-1000 <= Node.val <= 1000` * `-1000 <= targetSum <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
113,124,129,437,666
218
Hi gas welcome and welcome back to my channel so in today's video we are going to solve the line problem of the country ok so what has been given to us in this problem statement we will understand all that through examples ok now what to do na Read the entire statement once, understand the problem, what is given, what is to be found, if you do not understand, then no problem, we will understand through the example, what is our problem, so here I have taken the first example. What have we given here and what do I have to find? We will understand here. Okay, so look, here we have given you some buildings. We have given you this one building, this is the second, third, fourth and fifth. These five buildings are given here only. Okay, so here there is a 'Hey' in the name of building, Okay, so here there is a 'Hey' in the name of building, Okay, so here there is a 'Hey' in the name of building, what does it mean, in this you have three elements, one is your left point, right, you can call it the point of the building, till which point it is, where is its point and 10 is this. This is the height, this is your height, this is given 10. Okay, first one, what is yours, left point, this is the right point, this is your height, what is the height of the other building here, 37 15, this is the left point, this is the right point and this is the height of this one is 15. How many feet are there on the right side and its height is fine? What do we have to do here? Don't look here, these are your buildings. What do you have to do? You can speak to the sky from a distance. There is a distance. You have to see this building. Okay and you don't have to fine its outer line. What will be the outer line? You must have solved this type of reasoning problem, now he will have given some blocks and there will be four-five options to tell and there will be four-five options to tell and there will be four-five options to tell who will be whose outline and who will be the outline of this building. It would be like, what will be the outline of this block, so what will you see in the outline, it used to be like this here, how is the building given, there is an outline, so here also what we have to do is to see its outline, okay, so what is its outline? This is happening, let's do the second color, I will fix it, look, this is your outline, this is the outline of this building, this is the outline, then you will come till here, so what should we do here, you will have a lot of points on offline, right, all these. These points, all these points, there will be infinite points. Which point do we have to find or can we call a point, we have to find it and give it. Actually, whenever we see a particular height, it is the first point of the particular height. You can say like look here, this given in red color is actually the answer, so the first point of this height will be this corner will be yours, this will be the corner, this corner will be yours, this will be the first point of this height, if you look from above. So this will be visible to you right, so we have to give this point. This is the first point to be given in the answer. Okay, when you see this height, you will see it starting from here. Right, now if you look from the top, it will be visible here, it will appear like this. You will see the horizontal line starting from here, you will not see this corner which is actually starting from here, this building will not be visible from here, it will be visible, so you have to give this point from here, okay, you have to give this point, okay so you can see this point. People and you also have to keep in mind that if you take one point of a horizontal line, then if you get a horizontal line from the consecutive line, then you will not give another point there. Okay, so what to do here. In case you cannot answer these points, it is okay, you are answering these points, you are giving these points, you cannot take the height from the consecutive, you do not have to take the height from the mains to the horizontal line, this is given in your problem statement, okay So here we can't take this, that's why we ca n't take this, then here we will take here, if you look from above, you will see this height, till this point it starts, here you will see this start, this point has to be taken, okay then this You will see this height, its starting point is this, you have to answer this, you have done it again here, this building is starting from here but this height is this height here, if you see the starting point from above. You will see this starting point, so you will see this point by running, okay this is done, you will return the height, now you will see this point of this height, so this point also, what do you have to do, you have to turn and give it, okay now we How can we solve this problem, how will we solve this form here, see firstly what we have to do, in one way, what we have to do is left point, always see, in this case also we are taking left point. Also we are taking the left point but in this case when someone of your higher height is overlapping then you are not giving this left point, you are giving this point. What is this actually, its right point. From here if we We will take So in this case we are seeing here, not seeing here also, seeing here, so we also have to keep in mind that when someone is overlapping, we are not seeing its starting point in the case. You can take it because here when we look from above, the maximum height will be visible, so the building of this height will be visible to you, otherwise if it is visible, then the right of it will be visible to you somewhere. You will see the starting point height, equal to it, but whatever X will be your right of it. Okay, so we have to take care of this also, the same is happening in this case, what is happening here, this starting point will be visible, which is its right point, but this start is coming from here. If this is not happening, then you have to take care of this also, then how will we know which is left and which is right, for this, what will we do, will we take a vector of feet here, okay, let me tell you the map, what will we do by taking trees. Your height here right now is left, this is right, then you will understand that if it is negative, then with the left point, your height is negative. Well, height is positive for you, so it is left or right just for the sake of it. For this, we will take negative here, okay, what will we do in the case of positive What will we take plus 12, this will tell us what is our right side 15 is 15, what will we do in this case, we will take minus 10, we will take 10, okay this is done, it should be the total time, we will sort on the basis of first element because the answer which is yours here. You are looking at it is in the sort form 37 3 2 3 7 12 15 20 24 Is this short it is in the form right so what we have to do is we have to sort it so what we will do is we will sort it ok short it people so what It will be yours here, we will take the first element, ok, we have taken it, what is the intake after that, 15 79 10 - 810, we will take a multi set, what will we do with the multi set, why will we do it, the live building you have till now, which one has the maximum height, the light building? What does it mean that look at this point there is this building also at this point there is this building so here whose height is higher this one is higher or this one is higher so because of this what will we do a multi set We will take it and it will tell us what is the maximum height till now, it is ok so whatever we put in it will be in sort it form, so we will do it in multi set so that what we can do, I will tell you this in multi set. Now you can make any data structure similar to this. What happens in multi set is that whatever elements you take, it is in the sort form. Okay, so in this, what will we take in the initial, we will take zero, I will tell again why this. We are doing it so that you can understand it well. Okay, below, you will start from here with zero height, so you will keep it at zero. Okay, now where do you start, okay, what will we do here, we will take a previous one, what will we see from above. What will be visible is the one with the highest height, it will be visible right, so we will start from here, from 210, now what is our height, if it is 10, then what to do, insert 10 in it will be in sorted, so 10 will be here, okay it will be 10. So now what we will do is take the last element of the current here, okay, so what we did here is take it, take 10, okay, what will we do now, you have gone from zero to 10, okay, so this If both yours are not equal then what will we do in that case, we will store the value and the value of current in the answer vector that this is our starting point of this building, this is the starting point of the building with height of 10, okay this is negative. So we have inserted it here. We have come to know that you insert the negative one here because this negative means that it is on the left side and it will be the starting point of the building, so you insert 10 here and Update to the current. What is the current height of the building? Now you have inserted 10, so now it is 10, now you will bring the current here, now you will see whether the previous and current are equal. If it is equal, then we are building from date mains. You must have taken his point, if you will not take it again, then here you will see whether this is the previous height from yours, what have you given to us, you have seen in the statement that if you have a horizontal line from yours, then again. No people, this is why you have to take the previous and current details so that you can check that your height was not the height of your previous one. Okay, so here we have checked that you have to hide your previous height from zero to your height. Whatever we were previous to, now we are on 10th, so I have written this, what will we do, this What will you do? Since now you are going to see the next building, whatever height it may be or not, we don't know what we will do, before that what will we do, what will we update from the current one, what will we do here, update the previous one from the current one. We will make our current 10, there is nothing right now, first we will see what is the height of the next building, okay, so when you come here, you will know that its height is 15 and it is negative, it is on the left side, so what will we do here, insert this. We will insert it, okay, now we have done instinct and updated the paint, look now, our height is 15, then it will compare what is previous and what is its height, what is not from what is not, okay date is a different building and this If it is on the left side only then what will we do, we will insert it here, we will insert three and the current is the height of our building, that is 3 and 15. If we insert this then this will be inserted. The second answer is done, what will you do after that. Again you will update the previous one, now you will go to see the next building but before that what will you do with the previous one? Will you update it? Otherwise what will be the previous one? It will be equal to the current one. I did 15 here, now let the current one remain, nothing is there now, it is zero, okay now. We will come to this, we will come to 12, now when we come to 12, it is in negative, okay, if it is in negative, then you will insert 12, otherwise it will be here, it remains in short it, okay, whatever you are doing with the data. Yes, it is in sorted, so it is after zero, 10, after 12, after 15, so from here, if you go to the last element, what will you do, then the current will be 15. Okay, what will be in the current, if it will be 15, then you will see that, previously it will be 15 height. And the current is also of 15 height, so there is a horizontal line from both of them, that is, since the height is there will be a horizontal line, neither will we accept it in the condition, nor will we take it in the condition, we will not consider it, where is your case being made? This one is being built is n't it? If you are coming here then what will you do if people are not here then they will not take it ok? Actually who is this prisoner? Right now the maximum height will be, you know, it is 15, that is, whatever surface will be there, whatever floor will be above this one will overlap this one, the maximum height of the building till now is 15, this is still live, this is over. The rights for this have also not come yet, we have not got the right, if we had got the right then we would have got the positive height here and whenever we get the positive height, we will understand that building has reached its last level and its life has ended. It will be negative, we will remove this height which we had inserted here, it is okay, but when you go here to the 512, you will know that 15, there is a building of 15 height which is still there, on the right side of it. We are fine, so it means it will overlap, the height of 12 will not be visible, you will see the height of 15, because of this, what will we do here, 15-15, we will do here, 15-15, we will do here, 15-15, we will get our SIM here and what we will do, we will not insert it in it, okay answer. I will not do my inside. Okay, now we will come here at 7:15. What will happen when we will come here at 7:15. What will happen when we will come here at 7:15. What will happen when we come at 7:15? There will come at 7:15? There will still be no current here, you have nothing right now, so you will see, this is positive, what is this is positive. In debt, if we have acquired the rights of someone, we have acquired the rights of a building, then whatever will be the negative value of this, whatever its value will be, it will be already confirmed, it will be the variety, because if it is positive, if it is negative, then the one with height will be This will happen, if there is any harm in it, then what should I do, I will remove it from there because it is finished, you remove it from here, remove it, this is it, now what are you current people, front people, then you will know the maximum height of 12 till now. What is the maximum height of 12? Okay, now you will compare both of them, what is better than previous and friend? It is better than both. Okay, so what will we do, if we insert this value and current value, then 7 and 12, this seven will become 12. This is done. Your opening is done, it's done, okay, now you come here, now what to do, here you separate the previous one, what do you do, after this you will update it here, meaning next building, now the current one, we do not know, we are here. We will come here, 10, the negative one is already inserted here, so what will you do, you will remove it from here, it will go 10, we will remove it because it will be in the positive, the negative one will definitely be of value. So what we will do here is to remove this. Then we come here to the 12 part, this is also in positive. Okay, this is also positive, so what we will do is to put it in the condition. We will remove this because positive means that this building's It is ours, now the building is about to end, what was ours plus what was, we are slowly moving forward, as we leave our building, positive means you have reached the building on the right side, now from there. You are moving ahead and the building itself will not be visible. We will see the number 12 on the side of the particular building. This is also in positive. The date main's negative left side will be already inserted in it. Whatever is on this side, tell the height here and remove it from here. OK, if you remove it, then what will you do after that, what will you do here, what will be the current, what will be its element, now here you will see zero, you will get zero, okay, you will get zero, what will happen after getting zero, then you will see that these two are somewhere. Yours is not equal, no, it is not equal, then what will we do, whatever is the current You will do this and move ahead from zero, when here i.e. this left right i.e. this left right i.e. this left right is starting from a building, then we will insert 10 here, we do it only in positive, not in negative, if we do it in positive, then we will insert it here. Okay, once you insert the current, what will you do? Take from the back, whatever element is there from the garden, we will take 10 from here, we will see that both will be equal, that is, if this is not the original line, then what will we do with this 15 from here and this What will you do by inserting 10, this will become the answer, after that you update the previous one, now the previous one is your 10, okay then now you will move ahead here, what is this, your 8, what is this, you come here. Which is what is your negative, so now if you insert the negative here, then where will all these be, one here will be inserted here, it is set here, so after that when you insert it here, we cannot take it here, okay this is We can take ours here because both are from height key and we have already taken this height so we cannot give horizontal line from it. Okay, this will not reduce the case, then we will move ahead, again your previous one will be 10 only. Current is yours, so what is this, it is on your right side, that is, that building of yours is going to be finished, it is certain whose negative ball you have inserted, now remove it here, remove it, after that insert it, now people will see that both the current and this height are not equal. It is not equal. Okay, it is not equal. We can insert the date mains. In the answer, current is 20 and cant comes and Now let's see whether we get it further or not. Okay, so what will happen to your previous one? Here it will be 8 and you will not know the current. You will come here 24 and you will get 8. Well, this is positive, that is, this building is coming to an end, so you What to do a search and delete it from here. 8 khojenge will be found here. It has been deleted. Okay, now what will the current get from the last? What does the current element do? It takes the last element. Okay, so it will take zero here because till now there is zero height only. This point has reached here actually so we will see whether both are equal or not the previous year or not equal then take 24 So you have come across this problem, you must have understood that see when this kiss is being formed, this one which we are removing, when this point of yours is A, okay, that means here it must be a positive point A, so now this height. You must have finished, you are finished, this building is finished or when it came here, you must have come to know that hey this height is now out on the right side because we have taken the right positive in the positive. It will be understood that you have already inserted the height of this height from left to right. In this, you remove it from there because this building is coming to an end, right, so this is the kiss, that is why we are doing it in multi set here, okay. So that we can search and remove, now you can do any data structure which is your sotinter, okay short it, whatever you insert here should be in ascending order and any element you get from here whenever you insert any element if it is If you want to delete Okay, now let's come to the part, I understand you, what we have seen is the same, what will we do first, let's prepare one of ours, what will be the intern in the leg, what will be tight first, what will we take first, left hand remains and right height. Okay, this means that your starting point is there, then what are you doing? Taking the right point, d and height, you have to take it in positive, this means that we have placed our last point on some building in front. We have reached here, so here we take P in positive, okay then we have to short it, we have definitely kept it short in a previous mission and kept the current zero, okay then we have taken multi set M, okay multi set is yours and the answer here is you. Will you shoot today in vector, this is why the answer is taken here, the result is fine by name, now we will insert M in all these, zero in the initial, OK, now we will go through each element which we have prepared here. We will go through what was prepared, okay, when we see that I second give our lace, the date is zero, then we will understand that now we are on the left point, we are on the left side of the building, okay, so what will we do because here we have inserted negative. And in multisite, we have to do it in positive, so we will do minus i dot second. Okay, then in this condition, if it is not negative, your date mains, you have reached the right point, now what we have to do is to find it and call it element. Have to remove it from there so m dot race m dot fine i dot second ok second found done then in the current what are we doing the multi set of here eight and begin doing it na r begin do it It means that the one which is starting from the right side i.e. the which is starting from the right side i.e. the which is starting from the right side i.e. the last element is ok then this last element will give you ok so here I had printed it ok then what will we do then we will update the previous one with the current one ok this is Now the result is done, what will we do in the final, we will return it, ok, let's check it has been submitted, thank you.
The Skyline Problem
the-skyline-problem
A city's **skyline** is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return _the **skyline** formed by these buildings collectively_. The geometric information of each building is given in the array `buildings` where `buildings[i] = [lefti, righti, heighti]`: * `lefti` is the x coordinate of the left edge of the `ith` building. * `righti` is the x coordinate of the right edge of the `ith` building. * `heighti` is the height of the `ith` building. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height `0`. The **skyline** should be represented as a list of "key points " **sorted by their x-coordinate** in the form `[[x1,y1],[x2,y2],...]`. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate `0` and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. **Note:** There must be no consecutive horizontal lines of equal height in the output skyline. For instance, `[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]` is not acceptable; the three lines of height 5 should be merged into one in the final output as such: `[...,[2 3],[4 5],[12 7],...]` **Example 1:** **Input:** buildings = \[\[2,9,10\],\[3,7,15\],\[5,12,12\],\[15,20,10\],\[19,24,8\]\] **Output:** \[\[2,10\],\[3,15\],\[7,12\],\[12,0\],\[15,10\],\[20,8\],\[24,0\]\] **Explanation:** Figure A shows the buildings of the input. Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list. **Example 2:** **Input:** buildings = \[\[0,2,3\],\[2,5,3\]\] **Output:** \[\[0,3\],\[5,0\]\] **Constraints:** * `1 <= buildings.length <= 104` * `0 <= lefti < righti <= 231 - 1` * `1 <= heighti <= 231 - 1` * `buildings` is sorted by `lefti` in non-decreasing order.
null
Array,Divide and Conquer,Binary Indexed Tree,Segment Tree,Line Sweep,Heap (Priority Queue),Ordered Set
Hard
699
1,880
hi guys today we are solving this problem called check if word equals submission of two words this was asked in today's contest and this was the easiest thumb there so let's try to solve this the problem says the letter value of a letter is its position in the alphabet starting from zero that means a equals to numerical zero b equals to numerical one c equals numerical 2 and so on the numerical value of some string is of lowercase english letters is s is concatenation of the letter values of each letter in s which is then converted into integer for example if we have abc when we concatenate each letters numeric value it results in 0 to 1 which after converting into normal form we get 21 which means c is at 2 position as we saw earlier and b is at first position and a points to 0 so that is how after concatenating we get 21. you are given 3 strings first word second word and target word each consists of lower case english letters from a to j inclusive return true if summation of numeric values of first word and second word equals to the numeric value of target word or else return false so these are the test cases which this one is what we just saw now let's see the second one a points to zero a point to zero again a points to zero so the summation of the first string is 0 the second string is also 0 and the target string is not 0 because we have 0 and 1 so that is why we return false the third one everything is 0 so we return true so after reading the problem what we can figure out is that there are two halves to this problem the first half is to check if uh for stored the numeric value of for stored left second word equals to equal to um yes so basically you have to find the numeric values of these so for that we will have another function the first task is to check if the numeric values of these two are equal let's see what we can do here we'll have a numeric function as we just said this is true then we return to or else we return false so that is what we can do just by having an equal to equal symbol in between so now we will make our numeric function that is the second part in that what we're going to do is we're going to have a private int numeric because we need to return the integer value of the sums of these individual strings and we have to check if these two sum up to the target word so that's why we return sum so let us just return sum and then initialize sub it's sum equals to 0 and now comes the main part of the question wherein we are going to perform our operation which is also very simple which you're going to do using a single for loop in this for loop what we're going to do is we're going to um take each letter of the string which is passed so let's say the string passed is called word so each character for each gap in word we check and sum up its initial values or that is a pointing to zero b pointing to one c pointing to two so that we can calculate in uh in string using a very simple uh methodology which is if we want to calculate the numeric value of that particular character what we do is we convert the character into integer after subtracting a from it so let's say our a was at its ascii value let's say it is 97 or 65 i just have to check it's one of those so let's say if it was 97 and we remove 97 from so a points to 0 now if it was b then b would have been 98 so we subtract 97 from that and we get 1 so that is how we are plotting each values as discussed a 0 b is 1 c is 2 and so on and this we're going to add to our recurring sum equals to sum into 10 plus inch of character minus z so why we are doing sum into 10 because we need to concatenate the sum that is if a is pointing to 0 and b is pointing to 1 and c is pointing to c in this case if we have string as acb so we will have 0 and then we're going to multiply the 0th position to make it 10th position and 0 will move forward and then we will have a c into consideration c is at position 2 so we adding c at the tenth position at the units position when a is at 10 and then we multiply the submission which is 0 2 into 10 so 0 comes at hundreds two comes at tens and b is whatever numeric value is that is one comes at the units position so that is how everything is sorted perfectly so let's see if this is running okay now we have to convert this word to character array now let's see if this works let's try all the test pieces and let's try to submit this okay you're done for today i hope you guys understood i'll see you again tomorrow thank you
Check if Word Equals Summation of Two Words
largest-merge-of-two-strings
The **letter value** of a letter is its position in the alphabet **starting from 0** (i.e. `'a' -> 0`, `'b' -> 1`, `'c' -> 2`, etc.). The **numerical value** of some string of lowercase English letters `s` is the **concatenation** of the **letter values** of each letter in `s`, which is then **converted** into an integer. * For example, if `s = "acb "`, we concatenate each letter's letter value, resulting in `"021 "`. After converting it, we get `21`. You are given three strings `firstWord`, `secondWord`, and `targetWord`, each consisting of lowercase English letters `'a'` through `'j'` **inclusive**. Return `true` _if the **summation** of the **numerical values** of_ `firstWord` _and_ `secondWord` _equals the **numerical value** of_ `targetWord`_, or_ `false` _otherwise._ **Example 1:** **Input:** firstWord = "acb ", secondWord = "cba ", targetWord = "cdb " **Output:** true **Explanation:** The numerical value of firstWord is "acb " -> "021 " -> 21. The numerical value of secondWord is "cba " -> "210 " -> 210. The numerical value of targetWord is "cdb " -> "231 " -> 231. We return true because 21 + 210 == 231. **Example 2:** **Input:** firstWord = "aaa ", secondWord = "a ", targetWord = "aab " **Output:** false **Explanation:** The numerical value of firstWord is "aaa " -> "000 " -> 0. The numerical value of secondWord is "a " -> "0 " -> 0. The numerical value of targetWord is "aab " -> "001 " -> 1. We return false because 0 + 0 != 1. **Example 3:** **Input:** firstWord = "aaa ", secondWord = "a ", targetWord = "aaaa " **Output:** true **Explanation:** The numerical value of firstWord is "aaa " -> "000 " -> 0. The numerical value of secondWord is "a " -> "0 " -> 0. The numerical value of targetWord is "aaaa " -> "0000 " -> 0. We return true because 0 + 0 == 0. **Constraints:** * `1 <= firstWord.length,` `secondWord.length,` `targetWord.length <= 8` * `firstWord`, `secondWord`, and `targetWord` consist of lowercase English letters from `'a'` to `'j'` **inclusive**.
Build the result character by character. At each step, you choose a character from one of the two strings. If the next character of the first string is larger than that of the second string, or vice versa, it's optimal to use the larger one. If both are equal, think of a criteria that lets you decide which string to consume the next character from. You should choose the next character from the larger string.
Two Pointers,String,Greedy
Medium
null
1,560
hey everybody this is larry this is me going over most visited sector in a circular track the recent easy problems of the lego contest um yeah so for this problem it's just a simulation problem uh knowing that and the biggest thing to notice with easy part especially is pay attention to the constraints and for this one it's just n and the m's are less than 100 that means that you're going to loop around at most uh 100 times so not worth doing anything but simulation i took too long on this one because i had just reading issues there's a lot of reading and i think my intuition is that or my attempt is that i just go in there and figure it out but because there's too much reading and i just couldn't understand it for the longest time uh but by idea it's just simulation uh and yeah just keep on looping and that's all you need for this problem uh and then just keep track of um the uh the num the most visited sector right so that's pretty much it and you can actually be a little bit more clever by taking a look at the starting and ending and stuff like that but totally unnecessary so i wouldn't think about it that much on a yeezy at least for competitive programming purposes uh yeah and now you can watch me solve this problem next what it's not waiting oh so okay because one two three this is not quite hmm oh so oh yep oh i see hey everybody thanks for watching me self just uh explain these problems uh i have a video for before the con for this contest for the screencast let me know what you think hit the like button hit the subscribe button and join me on discord ask questions have fun and i will see y'all next contest bye
Most Visited Sector in a Circular Track
number-of-students-doing-homework-at-a-given-time
Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds[i - 1]` and ends at sector `rounds[i]`. For example, round 1 starts at sector `rounds[0]` and ends at sector `rounds[1]` Return _an array of the most visited sectors_ sorted in **ascending** order. Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example). **Example 1:** **Input:** n = 4, rounds = \[1,3,1,2\] **Output:** \[1,2\] **Explanation:** The marathon starts at sector 1. The order of the visited sectors is as follows: 1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon) We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once. **Example 2:** **Input:** n = 2, rounds = \[2,1,2,1,2,1,2,1,2\] **Output:** \[2\] **Example 3:** **Input:** n = 7, rounds = \[1,3,5,7\] **Output:** \[1,2,3,4,5,6,7\] **Constraints:** * `2 <= n <= 100` * `1 <= m <= 100` * `rounds.length == m + 1` * `1 <= rounds[i] <= n` * `rounds[i] != rounds[i + 1]` for `0 <= i < m`
Imagine that startTime[i] and endTime[i] form an interval (i.e. [startTime[i], endTime[i]]). The answer is how many times the queryTime laid in those mentioned intervals.
Array
Easy
null
749
go arrivals are spreading rapidly and your task is to quarantine the infected areas by installing was this is 749 contained virus the world's monomer has 2d arrays of cells where zero can represents unexpected selves and one represents cells contaminated drivers of war and only one war can be installed between any two for direction and into four directionally adjacent cells on a shared boundary every night the virus spreads to all neighboring cells in all four directions unless blocked by war resources are limited each day you can install was around only one region the affected area that fund the most uninfected cells the following night dick will never be a tie how can you say today if so what's the number of wars required if not and the world becomes fully infected we turned the number of wars used okay so I mean I think this is just simulation and you only 50 elements so you can so yeah so first thing I carry you know it's kind of like think about constraints and in some cases in the past or like today I mean just we're ready Lacs on those constraints so fifty by fifty years is very small Grady probably do like an end to the fourth thing and where n is to one side and not and what this also means is reverse emanation is that at most if you progress in a Manhattan distance kind of way from one corner to the other corner is just 50 plus 50 which is a hundred steps so that means if you do a simulation of some sort and maybe to some optimization you only need to do 100 times right so we could probably do that yeah because for every hundred times you want to do any one at most I mean with that for a surge or something like that you only look at each element of well you look at each element of one time and you look at the entire grid just once or like once or twice but off and where and it's the number of cells so in that case it should after a hundred dissemination of a couple of death research which or linear in it was like a hundred times 50 maybe times some constant so that's what definitely won in time yeah so I think oh I should double-check that yeah I oh I should double-check that yeah I oh I should double-check that yeah I mean I think that's my so that's my intuition on kind of boundary analysis but I guess we had come make sure that I mean these I'm just looking for examples therefore was built I understand example two actually right now I guess I got that you can build all around this zero you get to a one turn oh I see oh maybe that's a little what is a region a wall can be installed which we made to a chaise themselves okay one neighbor says in all four directions which tell you concern so we could build for voice at the same time I mean there to contaminate readers my first day at 5:00 was okay when I my first day at 5:00 was okay when I my first day at 5:00 was okay when I sweat I guess in this case you just do the inner we wash which I guess makes sense ok in this case you defected go you identified some bonus onion ok I think I proved mcclee I mean this there's not I mean it just tells you what to do ok I mean it's just a lot of coloring may be compared yeah I mean I'll Grif Mike Lee I don't moving there's anything tricky about this I think the tricky part about this problem is probably coding and I mean I guess that's always hard but and just getting things correct yep I dunno scared by the fact that there's so many downward stairs though you guys what's a rink this I mean there's also a little tricky because you have to not count what's on the boundary but okay though so this one is 13 because you've thought about dance like this there's no me you lovin and then I guess the second turn heats this up and then Dee's up and then just but then you just put one here and one here yeah okay yeah alright let's give it a go I guess well you see it up all right probably just figure out as we go I don't think there's anything to analyze in terms of complexity I mean more than I already did I think you just do not def research and a lot of edge cases around was depth-first search cases around was depth-first search cases around was depth-first search and but I think in terms of timing there's not that much time so I should be okay I think yeah like I don't think we're on there like time stress so it should be okay hmm it is about structuring the code in a good way I guess okay I'm just going to core as much as I cared and they kind of figure out how do we come in afterwards but first we want to count no I think we could just color yeah we'll just color the graph or the DEF research okay if I need pattern aiming there so bad at naming things struggling to naming one in any way but okay let's just do this for now quite I have to fresh this out a little bit but uh at some conditional stage of it that's no move okay I guess we didn't have to be could you treat as a boolean but okay miss me most terrible yeah I know let's see yeah No someone like that job to fix a few things okay yeah so that should cut it a graph I know this is only one innovation but let's print it out just so I could kind of visualize things a little bit just making sure we're still on the right track oh hey Paige how are you doing huh just having some problems hopefully oh man what did I do hope I didn't miss 10 this I guess I was 10 minutes ago so I always got you know I get a ready intent in some form sometimes I was just typing a lot know what this huge could have different size that would be sick I'm just gonna yellow just for a little bit oh yeah private this was alone didn't intend tough I am J's in the interview maybe that could be number okay no that's not good this these should be the same colors Oh oops okay so that looks better I wish I'd interests taking it one is slightly halogen okay yeah so everything's working this progress so now we have to kind of the different islands on this thing now we have to figure out which one friends the most uninfected cell the next night oka and I won't get tired so I think that's just like a fold of bread so okay and I guess we were just doing count friend yeah okay I mean maybe we'll rename it how many colors are there hmm maybe I should have put that somewhere hmm should we see colors now I don't return see whoops so number of colors will allow us to do stuff maybe yeah by having a count one friend and this could be in I mean fifty five fifty twenty five hundred so I mean I guess not actually but I'm just gonna do that for now so I don't have to think about it I'm just gonna with the global okay hmm just might be washed yeah I should have made this move and I mean a function miss negative one Lucca should be okay well it's not okay yeah because doing the same mass same island you could actually find the same cell more than once actually and that I can do it this way actually I think I have to do the inverse of this okay yeah so the tricky cases and I mean it's not that hard to imagine it's just trying to figure out how did it do it correctly just out for yourself for example well I guess just this one night you don't want to count them to the number in just seven below eight times or four actually but in any case you don't want it to kind of multiple times so I mean that's just a finger to keep in mind how do I do it oh goodness no I'm gonna say it's not infected it's not infecting them we look at the neighbors and I've got to Kennedy took these things to use way to do a okay huh how do I do it yes I've just want your local cable donor to the colorist then I guess I'll just do it over for return and this is all this cool I'll count it okay I think that should do it for one iteration maybe four counting I mean but no yeah I took it up we still have this print so hopefully you tell me up but that points my parish wasn't allowed okay so still five four is that accurate this one two three four five and doesn't one two three four so okay so I think that function is actually true so now I have to get the back switch they promise to not have a tie breaker maybe it did I don't there would be a tie okay so now I guess we install wars among this okay nothing we just want to learn maybe massive no this could reliably factors in a future in theory but well okay now we're installing Wars well I guess we have to get the best one for us that's visa and now we actually install I kind of never was okay there's a mess over I have to keep track of the doors installed I guess colors is fine because once you've done with a color that thing is I don't want you're done with color is it true that they effectively zeroed out no cuz I guess Chris then later on it gets five more so you have to use them okay I'm glad I just won in zeros then maybe we've got to make some modifications ladle I mean we use the same logic that we use in cow I just love me okay that's a matter of which perspective we're looking I guess not okay fine lifter Culley this happens when you use a web browser to comb okay even with some syntax highlighting is still kind of trickier than it should be okay he talks with okay yeah look unfortunate copy and pasting yeah but what do you need to modernize that but uh okay let's did you go to zero then we create a wall leave a lot of edge cases only now we update acquit maybe mmm we just said some a worldly number okay that would be one elevation well not yet it still has the stuff has to expand so now they're wars against what these things so never get explained and never explained in - okay well they're never explained in - okay well they're never explained in - okay well they're just almost quick on submit well let's see what happened in there okay maybe that's good I don't know doc do you install the wars you expand wireless yeah I think it's just every cell that is next to everything every cell that's next to a while is just expands and we already we quite a quarantine we effectively kill it because it cannot expand on the ones that only exists how much you know just like it watch this a type of there yeah okay let's see nope didn't expand hmm that's actually interesting oh wait no that should be good so till then su Manish next to ya I should be like that's I got boys in college backward spit Oh oh my god yeah maybe the lunate okay cool so everything experienced oh yeah okay so I mean that does a kind of a bug which is data you have to do it in the white order or else you're gonna keep on like a cascading giveback type thing so said set this to just define this to be next to you no I just hate to be down in it mmm just one and in though technically it will not be right but mmm what's up cuz it's 3,000 that's why the extra cuz it's 3,000 that's why the extra cuz it's 3,000 that's why the extra sales okay yeah whoops now we've just collected oh okay so that's what I think I expect after one iteration so okay now I'm asked Wow am I done I'm finished if they're no more viruses I guess or no more why I was just about to experience we don't know no is sure I think that may be good was it okay so I mean I really returned collect from the first one that's kind of take look at more questions more examples I didn't exceed it well sure maybe I mean I guess by doing an infinite loop let me just do this one real quick okay maybe this is just some weird things of formatting and deposit let's actually try that well my understood wall so that and he's a one's in good time though Isis practice is the same thing they should be give you examples I could copy and paste but yeah okay so it works for this one which is good why not but now I see why doesn't work with this one 2012 now cut just pull off on your way first units back in love and that's I think that we expect and after an expansion that's here and here in I know in here and here so in fear you just need to build a wall between here and here okay but why did I ask for 12 instead yeah there's a lot of code actually hundreds every lines quite bad what's ooh let's look at this one let's just put along the way I think they make one thing I always worry about is that the states a little weird after each iteration because maybe I just don't we set two states in a queen way okay oh I did not that's right very so does Mike but the counting of boys as well okay what that's nice too fruit no that's not meaningful okay one for two Hornets so what would these things are kinda from the first one so the first eleven's legit no but then it tries to do it again why does it try to do that one again no leave my colors that one I mean they have two different colors oh but the second time they were all the same okay I just play have someone and wanted color okay lieutenant nope hmm did I changed it the color is are the greats afterwards Oh okay well that was a I knew I had so many I mean I was looking for it but I couldn't find it so I guess I was just a silly mistake bit okay that's the thing with keeping too many state and unlabeled Emily sometimes your base case changing your name in little ice okay let me just double check it's not like this still works it also made it cool I think it's close time they've exceeded yeah well this isn't bullier I probably just have my for loop is just something I guess we would do I guess I don't actually test for the case where you cannot say today so that's just my god I think that was just like a very basic case now just to make sure that okay and really you cannot save the world you cannot expand anymore so I think I'm just put expand it's a little hacky they're just cheap about us now no I did that good wine maybe just second nature that was a buddy they even tell you on the description so it's kind of my bad that I didn't solve that one okay cool well so that actually i mean- missing well so that actually i mean- missing well so that actually i mean- missing the obvious case that they actually tell you to do except for that wasn't only examples i got it on the first try so cool so that was a heart i'm gonna try to do one more I mean just took me a while public an hour yeah and I think this one algorithmically there's nothing to calm cater you just have to you know it's I mean I did it with deaf first heard you could use breadth first search similarity having it's just assimilation you had it to your boundary analysis so that you know when to terminate your process yeah rather like a straight simulation is enough and maybe there if it's not that maybe have to do some fancy fancier algorithms and to think about it and once you do to diagnose and like okay maybe there's no one then you can think about it then you can uh yeah just to a simulation which is what I did I mean there's a lot of coding on this one there's a lot to eat it's really easy to mess up and you know you've seen me mess up for me Tomita 167 lines and it's not even on your successor seven good lines I have a lot of duplicated code here that I could clean up but at the core it's just that for search and it's just about kind of keeping track of all the special cases and unique cases that you might have to take care of yeah so that's kind of as an interviewee and as a problem solver it's an okay interviewing problem I think again similar to a previous problem there's nothing too complex in terms of algorithms you just have to be really careful how you define kind of a lot of definitions along the way like number of wars or like what is a war and you kind of when you build one and how this thing's squared and so forth but at the core is a simulation problem and there's a lot of coding to make sure that in a way such that your educators are not that you don't want the edge cases or your educators are taken care of in general so again we're similar to the previous problem I would say definitely if I'm child don't interview and the person is I'm enduring the person for problem solving then maybe this isn't quite the problem but if I'm interviewing them for kind of just like for programming but yeah just for programming that I would definitely do this like for kind of coding style and it well after this I will talk about like how do you clean it up a little bit how to marginalize how they're kind of there's definitely a few things that we used multiple times and maybe in the and maybe C is a little messy to do it but like maybe using elevators or in yeah enumerators to kind of generate tunics you know candidate for stuff there's definitely a few things that we can do to clean up this code but uh yeah I think that's what I'm gonna but yeah but I think for oh yeah otherwise I mean there's just way yeah well it'll be straightforward it's just about getting a def research to be very precise and to be correct and exactly what you need it to be which is always a little
Contain Virus
shortest-completing-word
A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary. Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**. Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used. **Example 1:** **Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\] **Output:** 10 **Explanation:** There are 2 contaminated regions. On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is: On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained. **Example 2:** **Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 4 **Explanation:** Even though there is only one cell saved, there are 4 walls built. Notice that walls are only built on the shared boundary of two different cells. **Example 3:** **Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\] **Output:** 13 **Explanation:** The region on the left only builds two new walls. **Constraints:** * `m == isInfected.length` * `n == isInfected[i].length` * `1 <= m, n <= 50` * `isInfected[i][j]` is either `0` or `1`. * There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round.
Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet.
Array,Hash Table,String
Easy
null
1,629
hello everyone and welcome back to another video so today we're going to be starting the leeco question slowest key all right so in this question we have a newly designed keypad which was tested where a tester pressed a sequence of n keys at one at a time you are given a string key pressed of length n where key pressed i was the i key pressed in the testing sequence and a sorted list uh release times where release times i was the time the i key was released both of the areas are zero index so the zeroth key was pressed at time zero and every subsequent queue was uh pressed exact okay press the exact time the previous key was released so what does it actually mean so in simple words we have key press and it has c b c d so what that's telling us is first the letter c was pressed and then b and then c and then d again okay and now this release times is basically accumulate the cumulative times at which uh each key was released so essentially c was released at the nine second mark so how long was c press for so from zero to nine seconds well that's a total of nine seconds so c was pressed for nine seconds now how about b so b was released at 29 seconds okay but now the question is how long was b pressed for so that's going to be so b was pressed right after c was released so from 9 up to 29 was when b was prepped so in simple words it's just 29 minus 9 b was pressed for 20 seconds the same way c was pressed for 49 minus 29 seconds and d was pressed for 50 minus 49 seconds which is what one now the goal of this is we're going to return the key of the key press that had the longest duration okay so whatever was pressed for the longest time that's what we got to return but if there are multiple such key presses so what does that mean so let's say there were two letters uh a which was pressed for 20 seconds and the letter x which was also pressed for 20 seconds then in that case the value that we're going to return is going to be x because we got to return the lexicographically largest key of the key press the question is pretty simple and the way we're going to solve this is by just having a simple for loop and in the beginning we're going to initialize a time which has the value of whatever is at the zeroth index of release times and we're going to have a another variable which stores the actual result or the character and that's going to be initialized with whatever is the first character is in this case c so at each point what we're going to do is we're going to calculate the time a certain key was pressed for and if it is greater than the time that already exists we're going to swap it around okay and if at any point there are like i said there are two characters which were pressed for the same time the larger of the two characters is going to be the actual result okay cool so let's see how we actually do this in code it should be pretty simple so the first thing we're storing our time and like i said it's going to be release times and whatever is at the zero index and now we're going to have our results so this is going to be the character so this is going to be key pressed but whatever is at its 0 index so now that we have these two values in the beginning we're going to go in a for loop so we can just do for index and range we're going to start off at the value one because well we already accounted for whatever is at the zero index so we're going to start off at one and we're going to go all the way to the ending so we can take the length of key pressed or release times it doesn't matter they both have the same length okay so now inside of the for loop we've got to find out how long was this current key press score so let's just call that current time and this is going to be so we go to release times and we go to the index that we're currently on okay so currently the first time it will be the first index now to see how long it was pressed for it's going to be release times index minus wherever the previous uh key was released out so that's just going to be release times index minus 1 the previous index so now we have the current time so all we got to do is check if whatever the current key was pressed longer than whatever we have stored over here okay now if this is true then what happens is that this whatever is at currently over there now becomes the uh result so whatever character is currently pressed for that long is the current result okay so result is now going to be well we go to key press and whatever index we're currently on and the same way we're going to update our time so time is now going to be equal to current time because well we want to update it with the larger value but now there's another condition that we could have which is if current time over here is equal to time now in that case what we need to do we don't need to update the current the time since while they're both the same but one thing we're going to do is we might have to update our result and the result is only going to be the maximum value between whatever the current letter is so whatever the current result is and the new value that we have which is key pressed index so the maximum between these two so the lexicographically larger value is going to be selected and be stored at result so the ending of this result is going to have the value that we need and that's what we're going to end up returning so let's submit this and as you can see our submission was accepted so thanks a lot for watching guys and do let me know if you have any questions
Slowest Key
minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits
A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time. You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the `ith` key was released. Both arrays are **0-indexed**. The `0th` key was pressed at the time `0`, and every subsequent key was pressed at the **exact** time the previous key was released. The tester wants to know the key of the keypress that had the **longest duration**. The `ith` keypress had a **duration** of `releaseTimes[i] - releaseTimes[i - 1]`, and the `0th` keypress had a duration of `releaseTimes[0]`. Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key **may not** have had the same **duration**. _Return the key of the keypress that had the **longest duration**. If there are multiple such keypresses, return the lexicographically largest key of the keypresses._ **Example 1:** **Input:** releaseTimes = \[9,29,49,50\], keysPressed = "cbcd " **Output:** "c " **Explanation:** The keypresses were as follows: Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9). Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29). Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49). Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50). The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20. 'c' is lexicographically larger than 'b', so the answer is 'c'. **Example 2:** **Input:** releaseTimes = \[12,23,36,46,62\], keysPressed = "spuda " **Output:** "a " **Explanation:** The keypresses were as follows: Keypress for 's' had a duration of 12. Keypress for 'p' had a duration of 23 - 12 = 11. Keypress for 'u' had a duration of 36 - 23 = 13. Keypress for 'd' had a duration of 46 - 36 = 10. Keypress for 'a' had a duration of 62 - 46 = 16. The longest of these was the keypress for 'a' with duration 16. **Constraints:** * `releaseTimes.length == n` * `keysPressed.length == n` * `2 <= n <= 1000` * `1 <= releaseTimes[i] <= 109` * `releaseTimes[i] < releaseTimes[i+1]` * `keysPressed` contains only lowercase English letters.
We want to make the smaller digits the most significant digits in the number. For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly.
String,Greedy,Binary Indexed Tree,Segment Tree
Hard
null
224
hey friends welcome back to my channel today let's do leave code number 224 basic calculator this problem is to implement a basic calculator to evaluate a simple expression string so the input is going to be a string the expression stream may contain open parenthesis and closing parentheses plus sign minus I and now negative integers and empty spaces so let's take a look at an example so mathematically how it works is we calculate from left to right but if there is apprentice e we calculate whatever is inside the apprentice e then the operations outside the apprentice e my approach is to go through the strength character by character from left to right and use a stack to save the previous result when we see open parenthesis and when we reach a closing parenthesis we wrap this result inside and pop whatever is in the stack then add them together and keep moving to the right side as we calculate so we start from here at this time sum is 2 and we move along and C open parenthesis so we add the current sum and the operation outside the parenthesis which is plus then we reset the sum to zero and then we calculate whatever it is inside this parenthesis here we have some equals to 1 then we move along and see another open parenthesis that's when we save the current sum to the stack and the operator pushes + we the stack and the operator pushes + we the stack and the operator pushes + we reset the sum to 0 and I move inside of the prenta see we have 4 and then we have 4 plus 5 which is 9 and now we're move along a 9 plus 2y which is 11 and now we see a closing prenta see that's when we start popping the stack so now we see inside a stack we have 1 and we'll have plus that makes our sum tove and then we'll move along with the minus three so some minus three is nine then we see another closing parenthesis that's when we pop this back again so two plus nine is lovin now the stack is empty now we move along and see another open parenthesis so we saved the current sum and the operator then reset the son now we see 6 plus 8 is 14 and we see a closing parenthesis that's when we pop this deck so now sum is 14 plus 11 which is 25 and now stack should be empty so 25 should be our final result the time complexity of this solution should be Oh n because we go through each character of the string once now let's write the code since in this problem we're only going to have a plus sign and minus sign for saving the sign I'm simply just going to use an integer and I will initialize it to 1 so when it's minus we just change the sign to negative 1 and we will also need a sum initialize it to zero also a stack to iterate through out this strength I will use a for loop so for this problem we have five scenarios as different kind of input we can have a number we can have a plus sign we have minus sign or open parenthesis and closed parenthesis otherwise we will just ignore the digit such as a spaces first of all I'm going to check if the current position is a number so now the number might be one digit like 9 or it can be more than one digit like 9 and 9 so we need to read through the entire number so I'll use a while loop to keep checking the current digit until the next digit is not a number and add to this number as the pointer moves after we get a complete number we will grab the sign and update this um so if it's something - 999 will have some equals to some plus - 999 will have some equals to some plus - 999 will have some equals to some plus the sign which will be negative 1 times the number 99 which is equivalent to some equals to some minus 9 na by this time our eye is pointing to the digit after the number and here in the for loop were updated the eye again so here we need to reset eye back one space that's a scenario if we're looking at a number so if the current digit is a plus sign then we need to update the sign to positive one similarly if the current character is a minus sign then we'll update the sign to a negative one now let's take a look at the scenario when the current character is open privacy as we said in that case we're going to save the operator and the current sum into the stack and set sum to zero sign to one in our last scenario which is when we see a closing parenthesis so when we see a closing parenthesis we pop the previous sum and the previous sign and do the operation with the current Sun and that should cover all our scenarios so after this full loop the sum should be the final result that we want so we return sum so let's take a look at this problem from the beginning we have default sign to 1 we have a sum initialized to 0 and a stack and we go through each character in the string with this number then while the current digit is number and I is less than the length of the string then we add this current digit to the current number and update the I when we get a complete number we update the Sun and reset I to one digit back otherwise if it's a plus sign now though the sign is one if the sign is a minus sign then we update a sign to negative one if we see an open parenthesis we push our current sum to the stack and push the current sign to the stack set sum to zero sign to one as default last but not least when we see a closing parenthesis we pop the sign from the stack and update our current sum then add our current sum to the previous sum after everything we're returning the son so that should be it let's run it okay there's some more complicated case like this one that we just talked about maybe with a bunch of spaces as well we get 25 let me try an empty space they should just return the default psalm which is 0 yep let's submit it alright that's about it thanks for watching see you next time
Basic Calculator
basic-calculator
Given a string `s` representing a valid expression, implement a basic calculator to evaluate it, and return _the result of the evaluation_. **Note:** You are **not** allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`. **Example 1:** **Input:** s = "1 + 1 " **Output:** 2 **Example 2:** **Input:** s = " 2-1 + 2 " **Output:** 3 **Example 3:** **Input:** s = "(1+(4+5+2)-3)+(6+8) " **Output:** 23 **Constraints:** * `1 <= s.length <= 3 * 105` * `s` consists of digits, `'+'`, `'-'`, `'('`, `')'`, and `' '`. * `s` represents a valid expression. * `'+'` is **not** used as a unary operation (i.e., `"+1 "` and `"+(2 + 3) "` is invalid). * `'-'` could be used as a unary operation (i.e., `"-1 "` and `"-(2 + 3) "` is valid). * There will be no two consecutive operators in the input. * Every number and running calculation will fit in a signed 32-bit integer.
null
Math,String,Stack,Recursion
Hard
150,227,241,282,785,2147,2328
154
Hello Everyone Welcome Department Productive Liquid Subscribe to Channel and Drown Skimming Do Subscribe Video subscribe and subscribe this Video Please subscribe and subscribe the Channel subscribe Question in the Presentation Swift Message to liked The Video then 25 Minimum Do Liquid 150 Subscribe 0 Video Subscribe Loot Subscribe To Hain Let's Get Started Yudhbeer Wa Video Subscribe Not Mean That Water Element Subscribe To That Looking At This Riot Victims Knock Remaining Victim Pre Discover The White Part Subscribe To This Blind Andhe Element Tax Loot Appointment To -Do List To -Do List To -Do List Play List Candy Crush Game Liquid Loot Vid U210 Limit Marg Point Note Left Side This Remedy Electronic Media Tarzan Video not here in the Video then subscribe to subscribe our A Navodayan Food and it is reduced from 31243 Labs subscribe Video subscribe and subscribe this Video not guide channel subscribe and do subscribe middle class ka read skirt bodh element se Z2 plus a planned stir well side reaction this wala point to end points liquid plus pati ki is type 512 is a two cash withdrawal point to which Position Loot Lo The Word Video 94 Rich And Subscribe Point To Subscribe Element Subscribe To Subscribe Location To 9 And Subscribe To I Hop Difficult One Porn Tube However Didn't True Sense Of The Duplication More Subscribe Video Plz Subscribe Channel To Play List One Slightly more active example this for all elements in more fuel remedy list and president of the 121 subscribe to and unlock point to 0.5 meter element pintu b 0.5 meter element pintu b 0.5 meter element pintu b mp3 and evolve that more than 80 people subscribe Video subscribe will guide you left ventricle Which Process Will Look Into Your 5.25 And 5.25 And 5.25 And Avoid That Middle-aged Man Middle-aged Man Middle-aged Man More Subscribe And That Bigg Boss Vikar Make And This Regard In Half Month Will Have To Go For Education Is The Color Of Karo According To Robbers Points 240 To Z Subscribe Video subscribe point to point se 0.5 inch subscribe point to point se 0.5 inch subscribe point to point se 0.5 inch width subscribe and subscribe the Video then subscribe to subscribe our that people get updated to meet plus one with Shri Bhairav ​​point se zinc do hai and despite Shri Bhairav ​​point se zinc do hai and despite Shri Bhairav ​​point se zinc do hai and despite looted 20 subscribe this Video give vid oo ki nav lets formula Is this in superintendence this problem not rule subscribe to subscribe our and last twenty-20 low 2052 na and last twenty-20 low 2052 na and last twenty-20 low 2052 na dhone ase them Z2 plus subscribe The Video then subscribe to the Page if you liked The Video then subscribe to subscribe and subscribe the App hai अदर्वीस hai अदर्वीस hai अदर्वीस्चेडल्स है Note Darshan Sleep Set The स्चेडल्स है Note Darshan Sleep Set The स्चेडल्स है Note Darshan Sleep Set The Festival Video Subscribe Middle and Avoid updates Please subscribe our that Akshay Dead End Time Complexity of this approach is Note Mode of Law Appointed Subscribe Video Subscribe button
Find Minimum in Rotated Sorted Array II
find-minimum-in-rotated-sorted-array-ii
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,4,4,5,6,7]` might become: * `[4,5,6,7,0,1,4]` if it was rotated `4` times. * `[0,1,4,4,5,6,7]` if it was rotated `7` times. Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`. Given the sorted rotated array `nums` that may contain **duplicates**, return _the minimum element of this array_. You must decrease the overall operation steps as much as possible. **Example 1:** **Input:** nums = \[1,3,5\] **Output:** 1 **Example 2:** **Input:** nums = \[2,2,2,0,1\] **Output:** 0 **Constraints:** * `n == nums.length` * `1 <= n <= 5000` * `-5000 <= nums[i] <= 5000` * `nums` is sorted and rotated between `1` and `n` times. **Follow up:** This problem is similar to [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/), but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
null
Array,Binary Search
Hard
153
1,822
Hello gas I am Lalita Agarwal welcome to on your on coding channel conference made by you made on you so late na start tu days late tomorrow problem today's date ko ki problem kya bol rahi hai achha before de problem na 1 minute discussion par dost jinko This problem is good, if you have understood then try anything, see this question is literally a very easy question, you do not have to do anything, normally you have to iterate and after trading, learn the science of all the mines, now take the mine sign. What is the method of how much sign of mines? Said Sir, is it a simple method? What is the method? Said that whatever value is less than zero, what will be the saree of the saree? It will be with the mines sign. Okay, one e4 but what is the condition on the story? Also, if in this whole story there is a zero, then friends, what will you return directly, zero because what will be their product, you are equal to zero, okay, zero has no sign, it is a simple thing, have you understood this is the problem, you don't understand this. There is no need for them to take tension. First of all, we are going to understand very comfortably that the question of eating is six, after that we will approach it and give the final bill. Most implementation. Look at this question, what is the question of eating here? He is saying a simple thing that there is some error given here. He said it is a simple thing, now when we do its product, whatever number comes after that will be positive, this will come negative, this zero will come, there should be only three conditions, why is the power zero? This is possible because suppose here it was zero instead of tu, then now any number of packing inside it does not matter because as soon as it is multiplied by zero, the total number will become zero and zero has no sign. Say it simple. It's a simple thing, yes, if this is not zero, then here either the number of positive will come or the number of negative will come, it is a simple thing, if the number of positive comes, then what will you be doing, return said one, if the number of negative comes. So one of the mines and if zero came then zero, only three things were returned to me, any of the three said, it is a simple or technical thing, now how will we know the positive and negative, they said, it is a simple thing, this was negative and this was negative. If both the negatives are multiplied then what will happen, will they become positive or no? I said, yes brother, they have become positive, then this was negative, this negative, what will happen if both of them are multiplied, brother, will they become positive? Said, it is a simple thing, said exactly, all the rest are positive. It does n't matter to you about the rest. It doesn't matter to you. So, if you are here, then what will you consider as yours? If you will cancel out their negative, then what can you say as Apn? This means if your negative is if ands, I repeat myself, if yours are negative ands. What will it mean that they are equal to the positive ones, we will not count them but if the negative ones are equal to the positive ones, then it is ok and friends, what will be the meaning of this, what will it mean, what will be its overall answer, negative, it is a simple thing. Exactly and or even on the story, if there is a zero in the middle, what will you say, what is the answer, what is the meaning of zero, what did you do with it, did you create a variable named account, say, ok, initialize the variable named account as zero. Okay, then you also traded a loop of four, what is the retreat on top of this? I said above the full name of this, okay, you said that if any value has come, which is zero, that means it is in negative, then its Do it because let yourself do all the mines. Okay, you have done your account, but if at any point of time your number becomes zero, at any point of time it becomes zero, like there is zero in this. So, if zero comes at any point of time, then make a direct return at this point of time, do not go ahead with the question only after finishing the zero, it is okay and if zero does not come and you have attracted the whole, like in this If there was no zero then you traded on 15, what did you get, the value of the account, how many numbers of negative are there in it, then your partner said something like this, whatever is the count, how many numbers of negative are there if it is divided by you. Let's go whole, this means if and is ok, then not here, see the condition that if they are divided by tu, whole then it is a ternary operator, what does it mean that if it is true or if it is whole. If Pura is being divided by Tu, then return one and if Puri is not being divided by 2, there is some reminder child, what does this mean? If e1 is sorry, it is eld, then will you be getting returns of mines if it is alt? One, what does it mean, the number is negative, it is a simple thing, yes brother, it is a simple thing, your question has been solved, now tell me, what will be its time complexity, brother, the time complexity will be off N because we are trading with all our might. This is absolutely correct and what will be the space complexity brother? Let's just take one or two variables as normal. It's a simple thing. There is a submit button. Thank you. 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
301
hi everyone today I will talk about lead codes three CLO one I move in parallel parenthesis and this is a hard problem so look crunching is to remove the minimal number of invalid appearances to make it valid so like this case what we want to do is to remove one right appearances so we can add or remove the second one or remove the false one and to remove fourth and fifth one without our same we only out provide length so the solution is to go from left to right and thing we found if little more bad perón seized land left parentheses we will get a little of it and if it is afterwards we go from right to left if they are more level currencies land left grandparents ease we were good okay to little bit so let's walk through the code so here's a main function we first define output and laying construct the main function and finally output learn result so we start from position 0 and from left to right let's walk through the main function so the input here's the string into the string and this is the output result and position means starts from where we started calculate and lease what else wheeler from left to right or right to left so first we need to found the first in fact the position here's the input string he tells from left right all right to left so we starts from the start it is from left to right so let's like Cielo will be late appearances and flag one will be right appearances so when it's late prices it will have a counter to what as one when it is references or minus one and when less than one it will output disposition which is first invited position if not if go to the end stilted infinite which means it is fatted stream so it is the crushing function so we why we didn't found it we will return so if it is from left to right we were - from rights left to right we were - from rights left to right we were - from rights left to simplify we were just the first seat and the lane start from zero okay and if from rights left language will be first it main output it so if we found Allah in final position so we was from the start position until low invalid position and third and to found Allah invalid to cater the table invalid parenthesis so is from left right we work added it off the right prints it from right to left we will get rid of their parenthesis so this one the first line this line is to thumb to skip the one which is not right appearances and this line is to deal with continuous right premises if it continues we only need to calculate one offlane calculate the first one because and the output will be the same so and after we get to the top it say here this stream we get a little dinner I the position I and after wicked here least res is the output and I so actually it's a regional I passed one position because as we did it off the ice position so we will put the I here and the last way to keep the same thanks for watching this video I hope you learn something from it thank you
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
28
Hello Gas Myself Amrita Welcome Number 28 Date Is Tu Find D Index Of First Occurrence Of Needle In A String So Lets First Understand D Problem Given Tu Strings Needle And Has Tax Return D Index Of First Occurrence Of Needle In His And Mines Van If Needle Is Not Part Of are there are you strings when this is stack and another when this is needle c need you check d occurrence of needle in hashtag if it is date give c need you return d index of first occurrence because of jump b multiple accrensis else -1 if Needle is not there in this accrensis else -1 if Needle is not there in this accrensis else -1 if Needle is not there in this hairstyle so hair you can see only but the end Needle is not there in this hashtag which you can see times only this is there but you need you check first occurrence and D first akrens is there coming the protest index so see need you return zero and if it is not there in this case you can see it code and let leto is not there in lead court so date mains needle is not part of his tax see need You return -1 in this case so let's need You return -1 in this case so let's need You return -1 in this case so let's first understand the approach you are going to take and give will write a solution for it so you have to strings when its state date is set but set and inside when is needle date is said but in This case will take it one but let's see if you want you find but you understand more because sad is there at D zero then next so see will try you find but so there are just two steps to solve this problem when you can directly check weather b Is There Because If Beat Self Is Not There But Cannot Exist First Will Check Weather D First Character Is There If It Is There Then C Can Check D Complete String Date Mains Complete Substring In This Case In D First Case What Are You Going To Check First Character So Ho C Can Do Date C Can Run D Lu Lets Se 0 1 2 3 4 5 6 7 8 Will Run D Loop From D Zero Off Index Pet Se Date Mains D First Character Is S And Her In This Case It Will Always B because C has tu check D currency of B so S = B no tu check D currency of B so S = B no tu check D currency of B so S = B no false increment I so I ise van A = B falls I false increment I so I ise van A = B falls I false increment I so I ise van A = B falls I ise tu D = B false I = 3 B ise tu D = B false I = 3 B ise tu D = B false I = 3 B = B2 so date mens C have found B punch C = B2 so date mens C have found B punch C = B2 so date mens C have found B punch C found B Give C Can Check D Complete Substance So In D Next Case C Need You Check D Substance So D Substring C Are Going To Check From D I So Date Mains Once C Found D Character Be So Date Mains In This Case It Would Be Three Date Mains I earn so nine you have to check d substring till this character right date is b so in this case it should be five so ho c can find this five so this string is one three charactorsting so date mains if I make so nine this should be six So ho it can be six dat i kama needle.len six dat i kama needle.len six dat i kama needle.len plus i so needle dot length is three plus three six so six in this case science see no dat is in case of subtank and index not include thoughts wahi it should be six situated of five adervise you can think date it should be three comma five right start and next end index but science and index is not included in d case of substance it should be three comma six and three is i and six is ​​length of d three is i and six is ​​length of d three is i and six is ​​length of d string + i so This is ho c need tu string + i so This is ho c need tu string + i so This is ho c need tu find d substance if it is equals tu this give c can written d index date is i so in this case c need tu return substance is not found than c need tu return mines when so this is what c need tu Do let's try this solution for it let's try D method static C should have you return wait so it should be in level and there are you strings van is his state and d van is needle and they need you right are low date will Start from length of hairstyle because science it is a three character string so it can't be every so see can check till this only six and next six seven come so date it jump be last three letter string so can see pack dot lance - pack dot lance - pack dot lance - needle .length plus one let me show you the same we are taking it like needle .length plus one let me show you the same we are taking it like needle .length plus one let me show you the same we are taking it like date so let's give them hair stag way date but saad idle is but and saad anything you can take let's start so nine this is one three letter string correct so these 5 found S har let's say i found s har so i can't check wether said is there are not it can't exist right so see need tu check it only til this index so date is zero van tu three four five six seven come and see need tu check it Only til de six index so date mains i &lt; 7 de six index so date mains i &lt; 7 de six index so date mains i &lt; 7 correct so ho c can find d seven if only tag length is 9 - length of need is three find d seven if only tag length is 9 - length of need is three find d seven if only tag length is 9 - length of need is three plus one nine minus three six plus vani less give seven dates same c are running d Loop til hashtag dot length mines plus and give just tu steps first step is hairstyle dot caret i h character c need tu check weather date is equal tu needle dot caret zero right because c need tu check weather d first index is there if it texas Let C Need You Check Weather D Substring Of Stack Is Equals Tu Needle And If Date Is True Let C Need You Check Weather D Substring Of Face Tag Is Equals Tu Needle Date Mins Hair Stag Dot Substring I Earn needle.length Plus I = Substring I Earn needle.length Plus I = Substring I Earn needle.length Plus I = Needle And if both d cases are true then c need tu return i date is d first akkarens of d needle in hashtag else c need tu return mains van nine let's call r function let's try d print statement direct output level end hair stag is sad but Sad and needle is saad nau sadis akring aate de zero thundex first acre so it will rate on zero let's turn de program and cd output see can cd output is zero so let's check and read example a well dat vasta lead code and needle is Leto So Leto Is Not There In Lead Courts What Should It Be On It Written -1 So Courts What Should It Be On It Written -1 So Courts What Should It Be On It Written -1 So Let's Run D Program And C D Output Give Output Is -1 I Hope You Understand This Give Output Is -1 I Hope You Understand This Give Output Is -1 I Hope You Understand This Solution If You Have Other Questions Other Doubts Please Let Me Know In D Comment Please Don't Forget To Like Share And Subscribe Or Channel And Stay Tune For More Sach Video India Upcoming Video Will Solve More Late Code Problems Thank You So Much For Watching
Find the Index of the First Occurrence in a String
implement-strstr
Given two strings `needle` and `haystack`, return the index of the first occurrence of `needle` in `haystack`, or `-1` if `needle` is not part of `haystack`. **Example 1:** **Input:** haystack = "sadbutsad ", needle = "sad " **Output:** 0 **Explanation:** "sad " occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. **Example 2:** **Input:** haystack = "leetcode ", needle = "leeto " **Output:** -1 **Explanation:** "leeto " did not occur in "leetcode ", so we return -1. **Constraints:** * `1 <= haystack.length, needle.length <= 104` * `haystack` and `needle` consist of only lowercase English characters.
null
Two Pointers,String,String Matching
Easy
214,459
520
finally it's good number 520 detect Capital it's actually the lead code problem of the day and it's easy so the problem simply says that we should just uh tell or they give us a word and we return true or false depending on if it's a uh Capital right and we Define the use of capitals in a world to be right when one of the following cases hold in cases where all the letters are capital like in this one we are supposed to return true right and when all the um letters are lowercase like in this case as well we return true and when we have words we're just one that's the first letter of the um word is uppercase that's also true that's all and they give us other examples here such as USA and this returns true and then they give us examples of where it could be wrong and that's for instance in this case where it's used and it seems easy enough we gave us a couple of constraints uh they said that word only consist of lowercase and uppercase English letters which is so great because imagine if we have like a word that has numbers in it right and then the word length can be between one and one 100 so yeah let's actually get to solving this I think about different ways of solving this problem at first I was going to Traverse through each letter in the string and decide if it's an OPAC is set out a lowercase letter and keep track uh but that wasn't a very efficient solution then I thought about using regular expression to do it but then I realized that JavaScript itself already has an inbuilt method for doing something like this actually um well like not technically checking if it's a capital letter or not but you can easily convert a let's say you let the word like click it's good for instance you can convert it to Lower Keys or convert it to upper case using um using JavaScript so I'd say to use that so basically what I would be doing will be comparing the value of my conversion so for instance if I have this word lit code I convert it to lowercase and I check if this com this converted value I have is the same with the word I was given if it's the same then I should just return true and the same goes with if it's an all uppercase Setter and the only issue I would have would be when I have to check against a world like Google for instance which has uh the first letter capitalized while the others are lowercase right so that's the only place where I will have the problem so to do that I'll just have to take off the first letter of the word and change that capital letter and then convert the rest to lower case letters and then convert it and then compare it with the word I was given and if it's the same then I know it's true and I return true now if all these three cases are met I know that yeah now capital letter has been detected and I should just return true but if any of this even at any point any of these fails or if it goes through all of these checks and it still didn't like it didn't return true at any point then I should just return pause so see it's an easy solution and the time complexity for this because under the hood converting to lowercase or converting to upper case um is O of n so um time complexity so of n space complexity will be like constant space of one because I don't have to I don't know I don't have to allocate any Express extra space for this so let's actually get to solving this constraint here tells us that it's possible that the length of the word can be one so to start off you can just check if uh if the length of the world is one because if the length of the world is one then there's no need to actually combat and compare because if either it starts with a lowercase letter and in either case it's true so we just return true in that case right and in case closed so but if otherwise as if the length of the world is actually not one and then do what we want to do which is to first of all convert so you can start to conversing to lower case so you can convert the word lowercase and then we check if we convert it to the work is to check if it's the same thing as the word and if it's the same thing as the word return true but otherwise if we check if you convert the word upper case and we check against the word I'll check against the word and the same it's actually the same word then we just return true as well otherwise we now this is a tricky part which is in words like Google here where the first character of the world is the only one that's capitalized where every other thing is not so in that case all we have to do is to use the JavaScript character as property so this character property takes the first character in the world and converts it so now that I've gotten the first character in the world just convert it off of this I will convert it to uppercase and then we get every other word in every other string in that um every other word in that particular string except the first character so in that case we can use the JavaScript device method and you just get every other thing from get every single word starting from index one and then we convert it to lowercase in this case and then you check if it's equal to the word and if it is effective is equal to the word and if it is we return true as well but if by chance it goes through all this and it still does not have any it still does not meet any of the criteria then in this case we can return all speakers that's it at this point and um yeah I think that's it now we can run code and yeah you can submit as well I'm sorry about that and yay our solution beats 95 percent of the submissions and around time is 68 milliseconds which is better than it's six percent of the submission as well so that's it guys um let me know if you have a better solution in mind or if you'd like me to solve it using regular expression as well all right see you guys in the next one bye
Detect Capital
detect-capital
We define the usage of capitals in a word to be right when one of the following cases holds: * All letters in this word are capitals, like `"USA "`. * All letters in this word are not capitals, like `"leetcode "`. * Only the first letter in this word is capital, like `"Google "`. Given a string `word`, return `true` if the usage of capitals in it is right. **Example 1:** **Input:** word = "USA" **Output:** true **Example 2:** **Input:** word = "FlaG" **Output:** false **Constraints:** * `1 <= word.length <= 100` * `word` consists of lowercase and uppercase English letters.
null
String
Easy
2235
298
welcome back to the cracking fang youtube channel today we're going to be doing a quick video on lead code problem 298 binary tree longest consecutive sequence given the root of a binary tree return the length of the longest consecutive sequence path the path refers to any sequence of nodes from some starting node to any node in the tree along the parent child connections the longest consecutive path needs to be from parent to child and cannot be the reverse so let's look at an example here in this example we can see that three four five is the longest chain so let's look at some other chains we have one to three which doesn't work right because these are not consecutive there should be a two in between these so that doesn't work now the reason that we can't have a chain from three to two is because we need to be increasing right we can't be decreasing so that's why three to two is not a valid candidate so we can see that our solution here is gonna be starting at this node three it's gonna be going to four because obviously there's a difference of one between them so we can add one to get to four and then from four we can add one to get to five so obviously there's three nodes in this chain therefore we would return three as our final answer let's look at this example so we would start at two and the next node is three so obviously that's a consecutive one so that would be a chain and then from three we go to two but obviously we can only be increasing here so this wouldn't work despite you know technically these are one apart um because we're decreasing it doesn't work that way nor can we say three two one if we just started at three it has to be increasing we can choose whatever node we want to be the parent node but it has to be an increasing chain so for this one the longest chain is actually two to three so the way that we're going to do this is really simple this problem isn't that bad what we want to do is basically we want to do a top-down depth first search want to do a top-down depth first search want to do a top-down depth first search through our tree here and what we're going to do as we go through our tree is we're going to maintain the parent value oops that's terribly written parent value and the length of our longest chain that we have so far that we've built so far right so it'll be like current length and what we're gonna do is when we get to a node we're gonna check is our node's value minus the previous value of our parent is it one if it is then we know that we have a consecutive chain and therefore we can add one to our current length and then we want to compare our current length with the maximum length that we found and we're going to go down and try to build it so for example if we do this really quickly obviously when we start here there is no previous value so you know we can just set it to whatever we want we can do like minus infinity right as our previous and the length of our chain starting here would be you know one right so then we get here so we call the dfs here so we go to three obviously the difference between one and three is not one it's two so that way this isn't a chain so now from three we can dfs into its left and right children and you know the length of the chain is one because we would assuming that we're starting here and obviously the parent is three so then we go to the two and we see the difference between two and three is negative 1 so this doesn't work then we go to 3 and 4 and the difference is 1 because 4 minus 3 is 1. therefore we have a viable chain here so we can increment our chain count so now it becomes 2 we can update our global maximum to be two uh you know the base case is just one where it's just literally the root node um so our you know longest chain is now two then we go to the five and we see that the difference between five and four is one therefore we have another one so we can update our chain three and then update our global maximum which is now three obviously here there's no children so our dfs ends and we end up bubbling up the recursion until we get back to the root node uh in which case our recursion is done and all we would have to do is return three so that's enough blabbing let's go to the code editor or we'll type this up and it's really simple just a simple dfs here so i'll see you in the code editor we're back in the editor let's write the code now let's handle the base case which is we're actually given a an empty node obviously if we're given an empty node as our root then there's no sequence we can build we just need to return zero so let's handle that base case so we'll say if not root all we need to do is return zero there's nothing we can do so we're going to basically set up a variable to keep track of our global uh longest path so we're going to say self.longest path it's just going to be self.longest path it's just going to be self.longest path it's just going to be equal to 1 because that is just the case that one node is the longest chain that we can build so obviously the longest path is one now what we want to do is we want to call our dfs function on the root basically so we're going to say self.dfs say self.dfs say self.dfs and remember we're going to be passing in the node that we're currently at we need to take the parent value so we're going to say root.val minus 1. and the going to say root.val minus 1. and the going to say root.val minus 1. and the reason that we want to do -1 is because reason that we want to do -1 is because reason that we want to do -1 is because we're actually going to evaluate this first node as if it were you know part of the chain and the reason that we do minus one is you know say it's one then obviously that would make a chain of one so it's basically just to handle that edge case um with the root if you don't believe me that this works remove the minus one submit your same answer and you'll see that it doesn't work so and obviously the length of our longest chain is zero because we haven't formed a chain yet which is why we're basically you know gonna do this at the first node um so we have that and at the end all we need to do is just return self the longest path cool so that's the easy part now let's actually code up the dfs so def dfs and remember that here we're going to be taking the current node we're going to be taking the previous value and we're going to be taking in the current length right so what we want to do is we want to make sure that we actually have a node to process you know for example if we were at this 5 and we called the dfs into its left subtree or its right subtree obviously those nodes are null we can't process them otherwise we're going to get some sort of exception thrown so we need to make sure that we're actually at a valid node so we're going to say if kernode then we want to do some processing here so we're going to say if the current node's value minus 1 equals the previous value so basically if the difference between them is 1 and a positive 1 right because we don't want negative that would be the case that you know from two to three obviously two minus three is minus one we want a positive difference of one between them um if we have that what we're gonna do is we're gonna say that the current length of our chain is gonna be increased by one and now we need to update the global maximum if we have a new maximum so we're going to say self.longest path it's going to be the self.longest path it's going to be the self.longest path it's going to be the maximum of whatever the current longest path is and our current length now we want to do is we simply want to call into the left and right subtrees with our dfs function so we're going to say self.dfs say self.dfs say self.dfs cur dot sorry current node is i believe what we called it yeah curnode.left we called it yeah curnode.left we called it yeah curnode.left and remember now we need to pass the parent value which is our current node's value so we're going to say currentnode.val and we're going to pass currentnode.val and we're going to pass currentnode.val and we're going to pass the current length of our chain and we need to do the same thing for the right subtree so we're going to say currentnode.right we're going to pass currentnode.right we're going to pass currentnode.right we're going to pass current node.val again and current node.val again and current node.val again and current length so notice here that we have this if statement and basically what this means is that if there wasn't a difference of one well this two could still potentially be the start of our longest chain so we want to basically reset our dfs and pretend like this could be potentially the um you know the parent that we want to work with here so we want to say self.dfs so with here so we want to say self.dfs so with here so we want to say self.dfs so this is the case where we didn't have a difference of one we basically want to you know this could be actually the start of the longest one uh because we can choose any node to be basically the start of our chain um as long as it's the global maximum right so we're going to call into that node so we're going to say current node.left we're going to say current node.left we're going to say current node.left and as the parent value we're going to say kernel. and obviously the longest chain is going to be one cool so we're going to say self.dfs cool so we're going to say self.dfs cool so we're going to say self.dfs kernode.right kernode.right kernode.right cur node.val cur node.val cur node.val and one so that is going to be what we do in the case where you know we don't have a longest chain well and that's all we need to do for dfs so let me just make sure i haven't made any syntax mistakes and int has no valid oh dot val of course this is why i check these things let's just run this make sure no more errors and why it doesn't okay cool so i'll submit this and it works so what is the time and space complexity of our algorithm here well this is going to be a top down def depth first search so obviously dfsing through this tree uh is going to take in the worst case big o of n where n is the number of nodes in the tree pretty standard uh dfs here space complexity you'll notice that the only variable we define is this longest path variable which obviously is a constant space allocation but because we're using a depth first search which is recursive we do have to take into account the stack frames that we may accumulate while doing the depth first search so technically our um space complexity is going to be big o of n if we count uh stack frames otherwise it's going to be big o of 1. so that is how you solve this question again pretty straightforward just a regular depth first search nothing crazy you have definitely seen um you know this pattern before and yeah there you go that's how you solve 298 long binary tree longest consecutive sequence if you enjoyed this video please leave a like and a comment really helps me out with the youtube algorithm if you want to see more content like this please subscribe to the channel otherwise thank you so much for watching and have a great rest of your day
Binary Tree Longest Consecutive Sequence
binary-tree-longest-consecutive-sequence
Given the `root` of a binary tree, return _the length of the longest **consecutive sequence path**_. A **consecutive sequence path** is a path where the values **increase by one** along the path. Note that the path can start **at any node** in the tree, and you cannot go from a node to its parent in the path. **Example 1:** **Input:** root = \[1,null,3,2,4,null,null,null,5\] **Output:** 3 **Explanation:** Longest consecutive sequence path is 3-4-5, so return 3. **Example 2:** **Input:** root = \[2,null,3,2,null,1\] **Output:** 2 **Explanation:** Longest consecutive sequence path is 2-3, not 3-2-1, so return 2. **Constraints:** * The number of nodes in the tree is in the range `[1, 3 * 104]`. * `-3 * 104 <= Node.val <= 3 * 104`
null
Tree,Depth-First Search,Binary Tree
Medium
128,549,1416
253
hey everyone today we're going over leode problem 253 meeting rooms 2 this is another problem off the blind 75 list which is a list of problems commonly asked during technical interviews this problem is very similar to meeting rooms one which is another problem I solved in my channel in this problem we are given an array and this array is called intervals and each interval in this array has a start time and an end time what we want to do is basically return as an integer the minimum number of conference rooms needed for these meetings to occur so basically we have an example here where we have an array of intervals and we have three meetings and what we want to do is simply go and see what is the maximum number of meetings that occur at the same time because if we have say three meetings which conflict then what we need is at least three minimum conference rooms in order to hold all of these meetings because they all have to occur in different rooms because of the time conflict however if the meetings do not conflict based on time then we can reuse the same meeting rooms and we would not need to increase the number of conference rooms that we require I've created a more complicated example here down below with four intervals we see we have a first interval which starts at time zero and ends at time 3 a second meeting starting at time 2 and ending at time 8 and a third meeting which starts at Time 4 ends at time 6 while our last meeting starts at Time 5 and ends at time 7 now I think that in order to understand what algorithm we need to use in order to solve this problem it's convenient to depict these intervals along a timeline so we have these intervals along a timeline and we want to see how many of these meetings conflict during a specific time interval so we start off and we see that our first interv starts at time zero this interval then ends at time 3 however we see that at time two we have our second meeting which begins so we can see that because meeting one ends after meeting 2 begins there will be a portion in time where these two meetings occur at the same time therefore during this period in time we will need at least two rooms in order to hold the meetings in SE separate rooms before which instead we would only need one room now after this first interval ends we know that we no longer need that additional room so for the next period of time we would only require one conference room afterwards at time 3 we see that we have another meeting which starts therefore we will have a period of time in which interval 2 conflicts with interval 3 because interval 2 has still not yet ended so during that period of time we will once again require two meeting rooms when we continue on we see that then at Time 5 we have another meeting which begins however neither interval 2 nor meeting 3 have ended so because of this we will have a period of time in which we will need three meeting rooms then we see that this interval 3 ends at time six so we can go back down to needing only two intervals and then at time 7 our last interval 4 ends so we can go back down to needing only one room until our last meeting two ends at time 8 after which we will no longer require any more meeting rooms basically in this problem what we need to return is the number three we will require three meeting rooms Max in order to have all of these meetings occur because some of these meetings conflict in time so we need at least three separate rooms in order to hold all of the three meetings separately now based on how we went through the timeline we can see how we could actually solve this algorithm what we could do is create an array which will keep all of our start times for the intervals an array which will keep all of the end times for our intervals so we have here an array for the start times and what we'll do is go and put all of the start times that we have in our problem however what we want to do is sort these start times in increasing order for our end times we know that we have a meeting which ends at time three then we have another meeting which ends at time 6 one that ends at Time s and one that ends at time 8 then basically for our algorithm we're going to have two pointers starting at the beginning of each array we could call S the one that's for the start times and e the one that's for the end times and we're going to see what occurs next in this case Zero comes before three so we know that we will have a meeting start so a meeting is going to start and we're going to need an additional room so increase our current rooms to one and then we check to see if we have beat our current Max rooms we have in fact beat it so we increased our Max rooms to one after which since we knew that a meeting started we now have to move our start pointer so we go and move our start pointer for the next iteration now again we see that at time two which is smaller than time three another meeting starts so we need to increment our current rooms to two and once again check to see if we have be our current Max rooms and we have so we increase our Max rooms to two as well after which once again we move our start pointer now points to meeting which starts at Time 4 however Before Time 4 at time three we have a meeting which ends so what we will do is again move our end pointer instead and this time decrease the amount of current rooms that are going on so we decrease the amount of current rooms from 2 to one because the meeting has ended and we take our endp pointer and move it to the next element in our array now we see four comes before 6 so we see that another meeting has started so once again we update our current rooms we increase it by one and it has become two again once again we move our start pointer for the next iteration and we see that we're at a five so another meeting has begun and for this reason we increment our current rooms from 2 to 3 and we see that once again we have reached a new max number of rooms so we need to update our Max rooms from two to three after which we know that we last started a meeting so we would need to move our start pointer however there are no more meetings that could start so we know that from this point on we would only have meetings which end which means that our current number of rooms would only decrement from 3 to 2 to 1 and to zero so at this point when we're done with our start times we could actually just end our algorithm and return what we have for Max rooms which in this case is three our time complexity for this algorithm is O of n Ln and this is because of the sort we have done for both the start times and the end times and given we have n intervals it will take n lag n for this sort to occur after which we're going through the start times and end times in linear fashion however our overall time complexity remains n Logan before writing up our code I wanted to mention that in addition to Being nlog and Time our algorithm is linear in space and this is because of the start arrays and the end arrays that we're going to keep in order to store the sorted start times and the sorted end times we're going to create our empty start times and end times arrays and after which we're going to iterate through each every interval in our intervals array we can deconstruct the interval and separate it into start time and end time and after which we're going to add each and every start time to our start times array and each and every end time to our end times array after having created our initial arrays now what we have to do is simply sort them so we could say start times. sort and end times thatat sort furthermore we need to initialize our start pointer our end pointer our current rooms variable and our Max rooms variable all to zero now we want to start our comparison of the start times against the end times in order to determine how many rooms we need now this comparison will go on until our start pointer does not reach the end of the start times array now if the start pointer points to a time which comes before our end pointer then what we need to do is increase the amount of rooms that we currently need increase our start pointer by one and also update our Max rooms if needed in the other case where our end pointer points to a time which comes before instead we need to decrement our current number of rooms by one but still increment our Endo there and once we're done with this while loop we're done with the comparison so we can return our Max rooms let's make sure this runs and we see that it works thank you so much for watching this video If you enjoyed it please give it a like And subscribe to my Channel I'll see you on the next one
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
208
hey guys how's it going in this video i want to go through eco number 208 implement try uh it's also called prefix tree um so if this question was asked by this company google amazon twitter pinterest and microsoft prefix tree is one of the is a tree data structure and used to efficiently store and retrieve keys in a data set of strings there are many different applications so it was used in autocomplete spell check id routing predictive text solving word games and we didn't write four functions for the implementation the try function initialize the try object the insert function inserts a string of the words into the try system and then the boolean this search function which will return the boolean and it will returns of true if the string is in the try and that means the word has been entered before and false otherwise and another function is named starts with and we input the prefix to it and then we and return the boolean it returns a true if there is a previously insert were a string words that has the prefix of the input argument and false otherwise so let's look at some example um the try so we initialize the try object and then we insert the word apple anyways the function what it does so this function we need to write this is the function one of the functions will be to read the right um also we need to write a try function as well the search function also is another function that we need to write and we will search the keyword uh search the word apple because the apple the word apple has been previously inserted that's why when we search for it and returns true and when we search the word app and it returns false because the word app has not been previously inserted however if we search for the prefix app that will return it to because app is a prefix of the word apple and then if we insert the word app when we search for it we'll return it to i'm going to walk through our true implementation to see how this works let's take a look at the code and we can in the init uh function we can just uh put in the word list to it so this one this uh attribute will be attached this to this object each time we initialize this i try object and then if we put in the uh the keyword not keyword if we put in the word insert to it if the word is not already in the word list we'll just append to it so essentially this word list will keep track of all the word that has been previously inserted and it takes a big o of 1 for time complexity for the appending and the checking because we're checking on the set we converted the list to a set so the checking takes a time complexity of peak of one as well and then the searching is pretty easy just look for the specific word that to see if you're already in the in this word list just so that we can know that has the word being previously inserted to it not or not and the common complexity for this one is also the big o of one because we are just looking at the set and for the stores with definition or function we look at we look through all the parts all the word that has been inserted previously by using this for loop so it takes a bit o of the number of words that has been previously inserted in the appended to the word list if this previously if we found this word by font i mean if we look at the pre fixed number for i mean the length of the prefix number of uh to corrector so this one basically look at the first few characters of the word that we found if that is the same as prefix and it will return a true otherwise within the false so it's pretty straightforward implementation but in terms of performance it's not great compared to the prefix tree uh the try uh data structure because we just are using an array and a slightly modified solution will be instead of using a list we can use a set and some modification on this method previously we have a pen method but for the set data structure we just have the add method to append the new word to the set and the search statement at the search function and also starts with a function they are essentially the same and we gained a slightly better in performance for the time and slightly worse performance for the space complexity so a little bit trade-off here trade-off here trade-off here between the time complexity and also the space complex the next one we will go through is uh the tri data structure and i'm going to walk through the implementation but the theory behind it i think there's a youtube video that goes through it pretty well i recommend uh watch this video uh before going through the notes however um before going to the code however the implementation on this youtube video was on java in here we are doing on python so first thing we create a separate class name notes and each node has some child and the initialization is i have the 26 the size of 26 of a list and so trial because 26 being uh 26 english letter and all lower case that's why we only need 26 and initially all of the while being none and this end is a boolean attribute and true being that's the last character of the words and false mean otherwise so uh let's look at an example when we convert this one to be an as a series of notes this one the boolean of each n will be false all the way to appl so all of them the attribute of each n will be false until we have the last one the last character yi the east end will be the ssn attribute will be true so this is how we can tell um the data structure to see which of the character is the end of the word and then we have the try uh class and then the initialization we just have a uh dummy note we just create an object of the note with um every the area of the attribute as a default and they have the insert we have the pointer of the node so the initial pointer to be the self.note so this is the root note the self.note so this is the root note the self.note so this is the root note the root of the other root notes so this is the most root notes and for all the character in the words if the children attribute of the list is not already exist so if uh for that spot in the children list is none and what we need to do is to create a new node for that character and we use the ascii system to convert the character to the numbers and then we find the corresponding spot in the list so for example ord a so that is going to be in ascii system it is 61 and then the distance between the ascii value for the character and the ascii value of the small a will be where we can put the ch the trial node on that list if the child has been created previously we don't need to create it anymore and then we update the pointer to be the julian node the child load node by the statement and then the for loop comes back again to look at the next character and the next one and then at the end for the last character we will update each end to be true because it is really pointing to the last character so sorry this volume value points to the last one to see if that ends the word and so this is the insert function in terms of space complexity will be the big o of m because this is in the case where all the character has not been inserted previously so it takes a big o of m for each of the character that newly entered newly inserted and this is the same for the time complexity and it's very similar function between the search function and also a start speed function that's why i created a function named find as you can see both these functions cause this function let's take a look at this find function so the current node the pointer node is putting the root node at the beginning and then you look through all the character within that string if that character is already on in the child we update the pointer otherwise that means we couldn't find it that's why it that's how it does how we can return a force meaning that we couldn't find this uh children this child and then also return a self.note so this is the root node self.note so this is the root node self.note so this is the root node and in the success case we will turn the tube meaning that we already found it on the in the children and then we would find it will return the latest node as it is a tuple and the reason why we use this triple system is because uh the search and the stars with uh they need different um output from this find function for this first for the search we need the last node if the last node is end meaning we capture the last character meaning we capture the entire world and this will take on this case otherwise you take on this case the self.node will be a false statement self.node will be a false statement self.node will be a false statement if this is really the last character of a word it will return a trio in the east end attribute for the stars with function is a bit more straightforward and for the star spiff function we just need the first output first part of the triple output um to see if that prefix has been found or not so they have the same time complexity and also the space complexity the time complexity is where the worst case will be where we have to check each character of the words all the prefix and the space complexity is a bigger one this is so much about the solution i will like it if you do please consider like this video and also subscribe to the channel and thank you for watching i'll see you next time
Implement Trie (Prefix Tree)
implement-trie-prefix-tree
A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. Implement the Trie class: * `Trie()` Initializes the trie object. * `void insert(String word)` Inserts the string `word` into the trie. * `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise. * `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise. **Example 1:** **Input** \[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\] \[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\] **Output** \[null, null, true, false, true, null, true\] **Explanation** Trie trie = new Trie(); trie.insert( "apple "); trie.search( "apple "); // return True trie.search( "app "); // return False trie.startsWith( "app "); // return True trie.insert( "app "); trie.search( "app "); // return True **Constraints:** * `1 <= word.length, prefix.length <= 2000` * `word` and `prefix` consist only of lowercase English letters. * At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`.
null
Hash Table,String,Design,Trie
Medium
211,642,648,676,1433,1949
309
everyone welcome back and let's write some more neat code today so today let's solve best time to buy and sell a stock with a cool down and this is actually a very interesting problem and a very challenging problem but honestly i'm gonna make this problem look like a joke today and that's not because i'm really smart it's honestly only because i know how to draw a picture i'm sure you guys know how much i like drawing pictures for leak code problems and how helpful they are and this problem is a perfect example of why exactly that is so let's get into it we are given an array of prices the price at index i just represents the price of a given stock on the ith day and our goal is to maximize the profit that we can achieve and the complicated part is that actually we can make as many transactions as we like we can buy a stock and then sell a stock but there are a couple restrictions the main restriction here is that we can't buy a stock and then sell the stock on the next day we have to have at least one day in between called the cool down day now we could have one cool down day but we could actually have multiple cool down days if we really want to right because we have a choice of how many transactions we can complete and the other restriction here is that if we buy the stock let's say on index zero right we buy it for price one we can't just buy it the next day as well right we can't just have uh infinitely many we can only have one share at a time basically that's what they're trying to get at right we can't buy and then buy we have to buy and then sell and then rebuy so in this example with this array of prices the result happened to be three is the max profit we could get and these are the decisions we would make to result in the output three we buy on the first day we buy for one we sell for two that's a profit of one so far we have a profit of one we cool down on day three so we cool down we buy it for zero the next day and then sell it for two so that's a profit of two so the total profit was three so not too bad but the real uh complicated part about this problem is that we have so many choices that we could make and that can get really complicated unless of course you draw a picture so let me show you how with drawing a picture we can solve this problem in linear time so like i said there's a lot of decisions to make so let's try to draw out those decisions the first main thing here is we can either buy or we can sell and we can only sell if we have already bought the stock before so when we start out at this array right we start at day zero at this point at the beginning of the array are we buying or are we selling of course we're buying because we don't own the stock yet so we can't sell it so that's one part of the state that we have to kind of keep track of are we buying or are we selling and it's not too hard because it's just a boolean right it's true or false and initially we're buying so you know we have a choice at index one right we can buy so of course one decision is buy if we buy the stock on day zero it costs one so if we do buy what's our total profit so far well buying costs money so our total profit so far if we buy is gonna be negative one now are there any other decisions we can make other than buying well we definitely can't sell yet we don't own anything but we can definitely do a cool down now if we do a cool down then our profit is going to be zero so far and by the way let me just draw a little zero up here because when we initially started our profit was also zero okay now on the left path of the decision tree what choices can we make now can we also buy and do a cooldown well we already bought we can't buy again we have to sell now technically we don't have to sell but that definitely is one of our choices the other choice of course is cool down so as you can kind of tell now we always have a choice of cooling down right the main choice that we're going to be determining is are we buying or are we selling the other choice can always be cool down we don't have to do anything but if we do sell on the second day you can see on the second day the price is two so uh by selling we're basically doing a plus two operation right initially we had negative one we're doing a plus two so that means our total profit if we sell so far is going to be positive one so that's pretty good now of course if we cool down the profit is going to stay the same meaning negative one now let's quickly draw the decisions on the right side of the tree if we cool down then we can't sell because we haven't bought anything yet so the same decisions will be present as you know the original decisions basically buying cooldown over here and the other decision is going to be buying so here if we buy we saw that initially we had zero as the total profit but if we buy on the second day that'll be a minus two operation so our total profit so far will be minus two if we cool down of course it'll just stay zero so now we get to a kind of interesting case uh after we have already sold then what are our decisions can we buy and then also have a cool down well the answer is no and the reason is because remember after selling we are forced to have at least one cool down day right after selling so basically just pretend like we skipped a day right we had a forced cooldown day right that's our uh one decision and we can't make any other decisions here right this is our decision we're forced to do a cool down after selling but after doing that uh we know our profit is going to stay the exact same plus one after doing that though then we do have a choice of buying or having another cool down day so we can buy or we can have another consecutive cool down day if we have another cool down day of course our profit is going to stay the exact same plus one but if we buy well first what day is it's the fourth day now it's uh the price is zero so if we buy it's going gonna cost us zero i wish i could buy stocks for a zero price but in this case of course if it costs zero then our total profit is just going to stay the same so we can stay at plus one now let's continue on this path last decision we can make is either selling or having another cool down day of course if we sold well we're on the fifth day the last day it costs the prices to so we'll make a profit of plus two we were already at plus one so one plus two is going to be three that's going to be our total profit if we took this chain of decisions right if we bought sold had a cool down then bought and sold again this is what the profit would be of course every path in this decision tree is going to have a different number right for the total profit so far and of course we want to return the maximum and by the way if we had the cooldown day instead on the last day then our profit would stay the same it would be plus one as opposed to plus three and just imagine that you know every leaf node of this tree has some different number and among all of those we want to return the maximum so among these two decisions between three and one of course the value we are going to return when we implement the solution recursively the value we're going to return is going to be the plus three we're just going to take the maximum of these two and return the max so i really hope looking at this picture makes the solution understandable for you the downside to the solution though is the time complexity you can see that the height of the tree that we're making is going to be n where n is the size of the price's array and the number of decisions at every point we can make is up to two decisions so the overall time complexity is going to be 2 to the power of n but we can actually use a very simple dynamic programming technique called caching in this case and by doing that we can reduce the time complexity to big o of n the reason why is because the key for the caching that i'm going to be doing is one going to be the index right the index of what position we're at in the price is array the second key i'm going to be using is a boolean for buy or sell i want to know if we're buying or are we selling it's a binary decision so we can just use a boolean for that right if we take this key value how many possible values could it be well the index i there's n different possible values for it this uh by or cell state is going to be two different states for it because it's just a boolean right so if we take n times two uh we basically get two times n right which we know is just can reduce to big o of n so in this case if we use caching the time complexity will be big o of n the memory complexity will also be big o of n because we are caching if you're not familiar with caching i'll be explaining it right now as i go into the coding solution okay so now let's write out the code you can see i already wrote out a few things one is just a comment kind of explaining what we're going to be doing we're going to keep tracking of the state whether we're buying or we're selling if we buy we're just going to increment the index by one if we sell we're going to increment the index by two reason is because we remember we have to take a cool down day after we sell and remember we are going to be using caching a dynamic programming technique so the easiest way to do a cache is just use a hashmap so that's what i'm doing here with python and just a comment what i'm going to be using as the key value of this hashgraph is going to be the index i that we're at in our prices array and a boolean which is called buying it's going to be true if we're in a buying state and it's going to be false if we're in a selling state and the value of the hashmap is just going to be the max profit associated with this key value so now let's get into it i'm going to be writing out a recursive function dfs i'm going to be writing the function inside of our root function because it's just easier that way we don't have to pass in every single parameter we don't have to pass in the prices array we don't have to pass in our dp cash we only have to pass in our index and whether we're buying or we're selling so first thing with recursive functions i like to do is just write out the base case so we know that the main base case is going to be if index goes out of bounds so basically if index is greater than or equal to the length of the prices array i didn't really cover this base case in the drawing explanation but i think it's pretty self-explanatory if i think it's pretty self-explanatory if i think it's pretty self-explanatory if we go out of bounds basically if we have an empty array of prices what are we going to return well we can't make any profit off of that so we're going to return zero okay so that's great and the other base case i just want to quickly mention is the case that if this pair of values this i and buying pair has already been computed before so basically if this is in our dp hash map initially our dp hash map is empty but if this is in our dp hash map then we assume that the max profit associated with this key has already been stored so then we can return that right so in dp we can just use this key value and then return whatever that max profit we stored was okay so now for the actual decision that we can make and remember that decision that we make is going to depend on only one thing what state are we in are we buying or are we selling so it's a binary estate right so if else so let's start with the buying so we know in the buying state we can do two things we can buy or we can have a cool down day right what's going to be the profit the max profit associated with each of these well if we buy we're going to recursively call dfs at index i plus 1. and what's the state going to be are we gonna leave buying as the same of course not because if we just bought then we're in the opposite state we're in the not buying state so in python this will literally just take that boolean value and negate it or in other languages you could just do like the exclamation mark but i'll leave this as is so that's how the recursive call is gonna work pretty straightforward but the only thing is if we bought doesn't that affect our profit so far remember that's what i was keeping track of so if we bought we have to subtract the price of what we just bought we bought the index on day i so that's what we have to subtract from the total this will tell us what the max profit we can get from the remaining array starting at the not buying state and this will tell us how much it actually costed us to get to this state in the first place similarly we'll do the cool down state which is slightly easier because all we have to do is do i plus one and in this case the buying state actually stays the exact same because we did not buy so we're still in a buying state and we don't have to subtract anything because we didn't spend any money and last but not least don't forget to cash the results so now we have our result so i'm going to use our key value i and buying and remember we took two decisions among these two decisions what do we want to know which one created the max profit for us so let's just take the max of buy and cool down and then assign that to dp so this is where we are actually caching so if we cache the solution and then we try to recompute that solution up above then we're going to end up returning it instantly rather than going through all the recursive calls over again okay so that's really the bulk of the problem last thing we have to do is handle the sell case so if we sell then we're going to do dfs and remember if we sell we're actually going to increment the index by two because we have to take a cool down day and if we sell we also have to negate the value of the boolean and you know you can do what's readable for you if you want to change this to you know set the buying state to true now uh you know whatever is readable for you i prefer just setting it to the negation um but instead of subtracting the price like we did with buying we want to actually add the price because if we sold that means we made some money so we can you know add the profit of this uh notice i forgot the s up above um and yeah so that's one decision and the other decision is just the cooldown decision which we can literally just copy and paste from up above because the cooldown is just skipping the day and it'll be the same in both cases and i'm going to copy the dp assignment up above because the only difference uh if we sold is we're going to take the max of sell and the cool down day and if you want to save like one line of code here you can probably just take one of the cool down functions move it outside of the if else statement and then delete the other cooldown which i guess i'll do for you but i don't think it's really that important but yeah once that's done what do we want to return whatever the max profit was we luckily stored that in our dp so we can just return uh just like this and believe it or not that really is the entire function but we don't have to we don't want to forget to actually call that function so let's call our dfs starting at index zero and initially the buying state is true because we are buying when we start out so let's run this to make sure that it works and as you can see on the left yes it works and it is pretty efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Best Time to Buy and Sell Stock with Cooldown
best-time-to-buy-and-sell-stock-with-cooldown
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: * After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** prices = \[1,2,3,0,2\] **Output:** 3 **Explanation:** transactions = \[buy, sell, cooldown, buy, sell\] **Example 2:** **Input:** prices = \[1\] **Output:** 0 **Constraints:** * `1 <= prices.length <= 5000` * `0 <= prices[i] <= 1000`
null
Array,Dynamic Programming
Medium
121,122
1,870
welcome to Pomodoro Joe for Wednesday July 26 2023 today we're looking at leapkid problem 1870 minimum speed to arrive on time this is a medium problem you are given a floating Point number hour representing the amount of time you have to reach the office to commute to the office you must take n trains in sequential order you are also given an integer array dist of length n or a dist index I describes the distance in kilometers of the ith train ride each train can only depart at an integer hour so you may need to wait between each train ride for example if the first train ride takes 1.5 hours you must wait an takes 1.5 hours you must wait an takes 1.5 hours you must wait an additional 0.5 hours before you can additional 0.5 hours before you can additional 0.5 hours before you can depart on the second train all right return the minimum positive integer speed okay minimum positive integer speed in kilometers per hour that all trains must travel for you to reach the office on time or negative one if it is impossible to be on time tests are generated such that the answer will not exceed 10 to the 7th and our must have at most two digits after the decimal point all right and then we have some examples here oh boy this is a tricky one well a couple of ways to come to mind how to do this so I think I'm kind of inspired by yesterday's problem where we did a binary search and this one actually seems like it might be a good fit for a binary search algorithm so in this case we'll have some function that tells us whether or not a speed is an acceptable speed so we just say will this speed get us there on time then we can just search all the different speeds between one and some maximum speed to see which one gives us the best answer and it looks like we are bounded here so it does say the answer will not exceed 10 to the seventh so we could use that as our Max one as our Min and just do a binary search for our answer so let's do that so we'll put 25 minutes on the pomodo timer and we will get started all right so the first thing I think I'll do let's do a quick early out I don't know if this is necessary but it might help us out so how many departure times do we get this is the departure account that's going to be let's see I guess it's going to be so if we have one hour we get one departure if we have two hours we get two departures but what if we get 2.5 hours we get one two we get 2.5 hours we get one two we get 2.5 hours we get one two we get two departures not including the first one if we have 2.5 hours we can leave it hour zero 2.5 hours we can leave it hour zero 2.5 hours we can leave it hour zero that's one train leave it hour one that's two trains and leave it hour two that's three trades so this is kind of ceiling of the hour I think that's right okay now we can do a quick check if we don't have enough departures to fit all of our trains in then we have to return negative one so if departure count less than the length of our train our dist are right here then we'll return negative one we don't have enough departure times for all of our trains all right this isn't really necessary well it might not be necessary we'll find out later okay now for our binary search algorithm we'll need a couple things one we'll need to know our Min speed and our Max Speed then we'll have to go through and find our best speed the other thing we'll need is some function that tells us whether or not a speed is a valid speed so let's have some function here called is valid speed and we'll take a speed all right I'm just going to pass on this for now we'll come back to it all right what's our slowest speed then these are going to be our bounds so the slowest speed is one it has to be an integer it does say somewhere here posit a minimum positive integer speed so the minimum positive integer that we can have is one and what's our fastest speed well it says here it's going to be 10 to the seventh so that's 10 to the seventh all right now we can start our binary search so for this one we're going to essentially take our slow and fast speeds find the midpoint between them that's going to be our check speed our mid speed so once we find this midpoint we'll actually check is that a valid speed if it is a valid speed then we can lower our fast speed to that midpoint speed so that's lowering or confining our search area to a smaller set of speeds if it's not a valid speed if the midpoint is not a valid speed well then we have to move our slowest speed up to that midpoint because we don't have enough time to get to our office at that speed all right so all our slow so while the slow speed is less than the fast speed we'll find some mid speed here and that's just going to be well for this one we need to find what's the delta in our speed So that's fast speed minus our slow speed so this is the Delta between the speeds and we'll do an integer divide by 2 to give us our midpoint speed so now this will give us just the midpoint in terms of our range but we still need to add in the base speed so that's going to be slow speed plus this Delta this is fairly typical of our binary search type problems if you saw yesterday's video this is very familiar to you so check out yesterday's video if this doesn't make sense all right so now we just check if this mid speed is a valid speed then we can reduce our fast speed if this is not a valid speed we have to raise our slow speed up so if it is valid speed all right if this is a valid speed then our fast speed can be a drop down to this midpoint otherwise we'll have to increase our slow speed to this midpoint and we'll do plus one because we already know this midpoint isn't going to be valid so we have to go at least a little bit faster than this midpoint so that's slow plus one all right and now at the end we will return our slow speed all right so this should give us our base here now we have to do this is a valid speed how do we figure this one out oh man well we can basically go through calculate essentially how long it's going to take each train to make its distance to cover its required distance add up all these times and at that time at the end is less than this hour then we're good all right so let's have travel time here maybe we'll call it total time all right so the total time will start at zero and for every distance in our dista right here so this is how far the train has to travel so this is the current time that it's going to take we have to cover this distance in this amount of time and our speed so let's see this is basically saying we have to do 10 kilometers and it's we're going 10 kilometers an hour that's going to take us one hour 50 or 20 kilometers and we're going 10 kilometers per hour that's going to take us two hours so this is how many hours it's going to take us and let's see I should do no I don't want to do an integer five this is a floating Point divide all right now the total time will just increase by this time but there's a slight catch here so in our very last train we might have some fractional hour we might not have a full hour on that very last train hmm all right so for each of our normal trains we actually have to raise this up to the closest hour because we basically might have to wait for the next train so normally we will actually have to call ceiling on this time so that will take some floating point and raise it to the next closest integer greater than this current time so this will give us basically our integer times or our departure times but that's only if this is not the last train so I might need to keep track of whether or not this is the last train uh so I can't just use distance here oh that's too bad all right let's do this I'll have to say for index in range length of our distance all right so the reason I'm doing this previously I can just grab the distance figure out the speed and the time unfortunately I need to know if this is the last train and in order to do that I'm going to use this index to tell me whether or not this is the last train all right so this will be dist at index I all right and that's if this is not the last index actually let's create a helper variable out here that's Max index it's going to be the length of our dist minus one so if I is not the last index or Max index otherwise instead of using the ceiling we won't have to wait around we have to get to the office but that means that this time is basically a fractional time okay and then finally down here we've calculated the total travel time for all of our train rides is this going to be less than or equal to our current given amount of time so we will return total time less than or equal to the time that we're given hour okay so this should tell us whether or not we have a valid speed I hope hopefully I did this right all right so now we have our binary search we're just going through checking all these midpoints to see if they're valid if they are valid we can always lower our speed to see if we can find a slower speed that's valid or we can raise our speed up if this speed isn't valid all right I think this should be good one concern here well we'll just run this and see I do have one concern that I'm not necessarily checking whether or not this slow in the end is a valid speed but anyway we'll try this we'll see how it goes okay so this works let's see if this will pass all the tests and we pass all right so how do we do okay not great 47 for run time and 25 from memory that's not too bad yeah that's not too bad all right let's jump back here and see if there's something else we can do one thing I'm calculating this length over and over again so one thing we could do is just have disc length all right and we can use that here so this is a minor optimization basically I don't have to call length function every time I do this so that might save us a little bit of time all right what else can we do in here we could actually well I don't think this is taking that much time we could actually just count out the seven so ten to the seventh two three four five six seven so we could do that might save us a little bit all right let's see if this still works all right still works let's see how this goes all right let's see did that save as anything that made zero difference I guess we got a little bit faster we went from 47 to 48 not much faster all right I don't really know if there's a ton we can do here we could try to wrap this in to here instead of making a function call I don't know if that's going to be that much faster hmm well shoot we could try getting rid of this I guess I don't know if this is strictly necessary it was sort of an optimization that might have helped us but let's see if this is actually we might need that yeah I yeah because otherwise we don't have this return negative one hmm I wonder okay well I think I'm going to leave any optimizations up to you but let's just check out how other people do this really quick we got a little bit of time let's jump in here we're pretty much solidly in the middle of the pack let's see how some of these faster algorithms go all right so this one does not have an internal function oh it does it has this check oh so it's doing the same thing we're doing but it's using numpy that's pretty smart so numpy is a library for doing math a lot of number stuff especially really good stuff with matrices and arrays so see what they're doing here they're taking this numpy array or they're making they're taking this distance and making it into a numpy style array which means that they can just call distance divided by their speed V I guess that's for velocity so they can just do their time calculation really fast on the entire array just by making this one call whereas I have a for Loop because I'm going through every single element in the array the other thing they're doing they're using numpy ceiling which is the same basically oh yeah so this is basically the same and they're using uh they're doing a sum that's pretty smart too so I'm going through and adding up the times individually they're just going to create their entire array and then sum it that's pretty smart all right the rest of this looks about the same they have one optimization here if there's only one train they just return this value so that's probably a smart one to do I should have thought of that one too anyway I'm going to leave that up to you can check this out again this Elite code problem something 1870 and it's a fun one so check it out alright I hope you enjoyed this hope you had fun hope you learned something hope you can go out and write better code
Minimum Speed to Arrive on Time
minimum-speed-to-arrive-on-time
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. * For example, if the `1st` train ride takes `1.5` hours, you must wait for an additional `0.5` hours before you can depart on the `2nd` train ride at the 2 hour mark. Return _the **minimum positive integer** speed **(in kilometers per hour)** that all the trains must travel at for you to reach the office on time, or_ `-1` _if it is impossible to be on time_. Tests are generated such that the answer will not exceed `107` and `hour` will have **at most two digits after the decimal point**. **Example 1:** **Input:** dist = \[1,3,2\], hour = 6 **Output:** 1 **Explanation:** At speed 1: - The first train ride takes 1/1 = 1 hour. - Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours. - Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours. - You will arrive at exactly the 6 hour mark. **Example 2:** **Input:** dist = \[1,3,2\], hour = 2.7 **Output:** 3 **Explanation:** At speed 3: - The first train ride takes 1/3 = 0.33333 hours. - Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour. - Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours. - You will arrive at the 2.66667 hour mark. **Example 3:** **Input:** dist = \[1,3,2\], hour = 1.9 **Output:** -1 **Explanation:** It is impossible because the earliest the third train can depart is at the 2 hour mark. **Constraints:** * `n == dist.length` * `1 <= n <= 105` * `1 <= dist[i] <= 105` * `1 <= hour <= 109` * There will be at most two digits after the decimal point in `hour`.
null
null
Medium
null
143
hi everyone let's do lead code 143 reorder list so we're given the head of a singly link list and we want to reorder this list following this form here so this can be a bit confusing so let's look at an example so given this input list this is the output we are looking for so the first position of the output we got the initial node the second position we've got the last node of the list the third node is the second node of the input list and the last node is the third node of the list so as you can see uh we alternate one node from the beginning and one node from the end and that's how we get this output node there are a couple of ways uh to do this problem so one is to have time complexity equals to Big O of N and space complexity equals to Big O of n as well this first way what you could actually do is get the input list put it in a array and then what we could do is have a pointer at the beginning and a pointer at the end and actually form the output as we Traverse through the array so we could have the output list with the first node in the array the second node to be the last node in the array then move the pointers and do the same but this is going to require extra space there is a more efficient solution which is actually a one that requires constant space so basically it's not going to get any extra space and the time complexity is going to be the same Big O of n so let's actually see how to solve using this different method that's going to just take big of one space let's take again this list as an example so a different way to solve this problem is to actually use the following method what we could do is we could split this list in two and then merge the elements in an alternating way so this is the middle of the list as we know what we could do is start at the beginning have the first node as the output then go to the end of the second and get this element and have it as the next one in our output list then move over to the second element in the first list add it here but now we've got an issue actually as you can see this is not a dou link list it's actually a singly link list so we can't go from four to three so that's actually a problem so how can you solve that one way to solve it is actually get the second half of the list and then reverse it before starting the merge so we could do something like this but you might be wondering how is this algorithm going to work so there are actually multiple steps so let's go through each step and then let's go through an example the first step in the algorithm is to find the middle point of the list so how can we find the middle of the list so one way is to have two pointers a slow pointer and a fast pointer let's initialize two pointers so fast is going to move by two and slow is going to move by one position so if our fast starts here we're going to move it by two slow is going to move by one so slow is going to be here fast is now here and as you can see fast is already at the end of the list and slow it's at the end of our first list so actually our middle is here wherever slow pointer is uh but you might be wondering what if it's a odd list so let's say we also had a five here in case of a odd link list our method is still going to work fast is first going to move here slow is going to move here now we want to move fast again fast is not going to be null and slow is going to be here we have first list which is this one and our second list which is this one and when we are going to merge is still going to work uh you'll see it in a bit when I'm going to go through an example we now know how to find the middle of our link list okay so we have the middle of our link list we now want to split the list in what this actually means is that we want the end of our first list to now point to null once we have split the list we need to go to the next step which is reverse the second list it's quite simple I've actually made a video on another lead code problem where we have to reverse a link list so uh please check that out we're simply going to change the way the links work so five is now going to point to four so once we have reversed our second list we reach our last step which is we merge our lists how can we merge through the list what's going to happen is we're going to start with the head of our first list which is going to be our output now we want this node do next to be equal to five and not equal to two so this link is going to break and one is now going to point to five and now we want to break this link and we want to have five to point at two we then want to move our pointers so you might be wondering oh we have broke in the list how we are going to move we actually need to store these two links before breaking them so we will actually have some extra variables in the code that's going to be clearer so now two is going to point to four and four is now going to point to three and three is pointing to null so this is actually the desired output as explained this solution has a Time complexity of Big O of N and it doesn't use any extra memory okay let's try some code now I've added some comments with the various tabs so that should make it a bit easier so the first thing we need to do is find the middle point of the list by using slow and fast pointer let's have two pointers a slow and a fast one so slow is going to start at the head and fast is going to be one position after slow so we now want to move fast until it's not at the end of the list or until fast is not null so this is how we can do it and we're going to use a while loop for that we want to move slow by one and we want to move fast by two positions so now our slow pointer is going to be at the middle of the list what you want to do is we want to split the list into two the way to do is to have slow. next to point at null the head of the second list is actually this one slot. next so now that you have split our list we want to reverse the second half of the list and in order to do this we actually need a variable that is going to contain the previous node which are actually going to initialize at none sorry this should be none not null so now we want to reverse the second half of the list so we need a condition while second is not null we want to actually reverse the nodes so we're actually going to save the links in a temporary variable so as we said second is not the head of the second list so we want to save the connection to the next one we want to actually reverse the list so second do next is now equal to previous one which is initially pointing to null and previous is now going to become second and second is going to become our temp okay at this point we have two lists and the second half of the list is also reversed the last step we need to do is actually want to merge the two halves so let's initialize our two uh pointers so first pointer which is going to be the head of the first list and the second pointer which is actually going to be the beginning of the second half so this is going to start at previous we need a while loop now so we know that the second list is probably going to be shorter if it's even so we just need a condition while second is not null we want to First store the current Links of the two uh nodes and you can use temporary variables so let's have time one and temp two and let's initialize them so first next and second. next we want to actually have first. next to point to Second so what's happening is the node from the first list is going to point to the node from the second list and then we want the second do next to point to Temp one so what we are actually doing is we're putting the node from the second list in between nodes of the first list and that's how we actually achiev that at the end we want to Simply update the first and second pointer okay the coding is complete we don't need to return anything as the exercise said let's see if this works okay there is an error um so let's see okay I think the error is uh because of these two lines so slow. next should become null after we have saved it in two second we can get rid of that so let's see if this works now as you can see uh it does work if you found this video useful please like And subscribe and also check the other problems I've solved there is a playlist called Blind 75 thank you
Reorder List
reorder-list
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **Input:** head = \[1,2,3,4\] **Output:** \[1,4,2,3\] **Example 2:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,5,2,4,3\] **Constraints:** * The number of nodes in the list is in the range `[1, 5 * 104]`. * `1 <= Node.val <= 1000`
null
Linked List,Two Pointers,Stack,Recursion
Medium
2216
836
hey guys welcome back to hippo function in this video we will discuss another interview problem rectangles overlap so the problem statement says that we are given with 2 rectangles and we need to determine if they overlap or not now for the representation of rectangles we have been given two coordinates when is the bottom-left coordinate let's say x1 and bottom-left coordinate let's say x1 and bottom-left coordinate let's say x1 and y1 and another is the top right corner that is x2 and y2 it is also given that the sides of the rectangle are axis aligned which means that they are parallel to the x axis and the y axis and also if two rectangles touch the boundaries then they are not considered to be overlap so let's say for example we have one rectangle with coordinates as 0 &amp; 2 and then we have another as 0 &amp; 2 and then we have another as 0 &amp; 2 and then we have another rectangle with coordinates s 1 &amp; 3 rectangle with coordinates s 1 &amp; 3 rectangle with coordinates s 1 &amp; 3 so if we draw the first rectangle let's say this is 0 and this is 2 comma 2 this will be my axis and for second rectangle this point would be 1 comma 1 and this point would be 3 comma 3 so that's my second rectangle so from the figure it is clear that they overlap and because they overlap we will return true as our answer so let's see how we will solve this let's say this is the first rectangle given with coordinates x1 y1 and x2 y2 now let's consider the cases where the rectangles second rectangle will not overlap that is the second rectangle can be here or anywhere outside this rectangle now note that if the rectangle is inside the first rectangle it is also considered to be overlapped so broadly we can say that the rectangle is on the upper side or the rectangle is on the down side or the rectangle is on the left side or it is on the right side let's try and understand again this is our first rectangle with coordinates x1 y1 and x2 y2 now let's say we have a rectangle on the upper half then this will not overlap will let's name its coordinate as P 1 Q 1 and P 2 Q 2 then this will not overlap with the given rectangle if and only if my Q 1 is greater than equals to Y 2 if we have a rectangle on the lower half then again this will not overlap with the given rectangle if and only if my Y 1 is greater than equals to Q do similarly for the x axis if it lies on the right part then it will not overlap only if my p 1 is greater than equals to X 2 and if it lies of your hair even Q 1 and P 2 Q 2 then the condition for not overlapping would be P 2 should be lesser than equals to or let me say like this X 1 should be greater than equals to P 2 so these are the four conditions that we need to check for non overlapping if any of these condition satisfies then it means that the rectangles don't overlap and we will return false otherwise it is guaranteed that the rectangles will overlap and we will return true now to code this is pretty simple we just need to write those four conditions and if any of these conditions will work we will return false otherwise we will return true now we are given the rectangle coordinates as a vector list so Rick one of zero represents x1 Rick two of Rick one of one represents y1 Rick one of two represents x2 and break one of three will represents y2 similarly this will represents P 1 this will represents P 2 this represents Q 1 and this represents Q 2 thus our four conditions are x1 greater than equals to P 2 P 1 greater than equals to x 2y 1 greater than equals to Q 2 and Q 1 greater than equals to Y 2 so if we go back to the dashboard these were the four conditions that we have created so this was all about the problem I put the problem link in the description so you can go and solve it if I need out some suggestion please write in the comment and if not subscribe to the channel yet then please do that thank you so much for watching
Rectangle Overlap
race-car
An axis-aligned rectangle is represented as a list `[x1, y1, x2, y2]`, where `(x1, y1)` is the coordinate of its bottom-left corner, and `(x2, y2)` is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles overlap if the area of their intersection is **positive**. To be clear, two rectangles that only touch at the corner or edges do not overlap. Given two axis-aligned rectangles `rec1` and `rec2`, return `true` _if they overlap, otherwise return_ `false`. **Example 1:** **Input:** rec1 = \[0,0,2,2\], rec2 = \[1,1,3,3\] **Output:** true **Example 2:** **Input:** rec1 = \[0,0,1,1\], rec2 = \[1,0,2,1\] **Output:** false **Example 3:** **Input:** rec1 = \[0,0,1,1\], rec2 = \[2,2,3,3\] **Output:** false **Constraints:** * `rec1.length == 4` * `rec2.length == 4` * `-109 <= rec1[i], rec2[i] <= 109` * `rec1` and `rec2` represent a valid rectangle with a non-zero area.
null
Dynamic Programming
Hard
null
1,680
Hello Hi Everyone Welcome To My Channel It's All The Problems And Definition Of Positive Energy Number Most Zor Distic For Consideration Of 2nd In Order To Power In The World Number One To Three Selection In This Will Have To Subscribe Button * Number 0001 Number 90 After The Will Convert Decimal To Have Converted Into Decimal Number Been Stopped For Lips And Went Over 120 Value * Tourist Places Where From Right To Value * Tourist Places Where From Right To Value * Tourist Places Where From Right To Left Every Time Increase The Power Of Subscribe * 2510 * Tourist Power To Do Subscribe * 2510 * Tourist Power To Do Subscribe * 2510 * Tourist Power To Do A Plus Woven Into A Power Trailer In The Largest Richest Woman In Tourist Powerful Subscribe Number 66 Wishes To Subscribe Like Convert Into Every Candidate Can Convert Decimal Number 230 Switch Off Birth Time Hello How They Can Also Effective Object Carefully This Multiplication So Let's Spread Over Straight Last One Should Be Quenched This Rumor Note C dish what is this what we can do we can take you to power to is the common in this two multiplicative one * * multiplicative one * * multiplicative one * * a plus 0.22 power to the a plus 0.22 power to the a plus 0.22 power to the correct bite gold into power then a message we can write further in this is to two * whole power to do a * whole power to do a * whole power to do a plus 3 number its flowers ronit hindu tourist power for oo ki sister bhi advance tej bhi common in this tool power two so they can write over life one * power two so they can write over life one * power two so they can write over life one * tourist power two plus two * tourist power two plus two * tourist power two plus two * tourist power two Plus Number 3 Se Zari Pattern Disawar Number Two Or Three What They Are Doing A Good Time For Black Dress Power Subscribe Veer 2012 Similarly In We Live With Two The Number Well So This Is The Final Multiply Now This Is What We Can Do For solving this will start from selection list start corresponding follow from physical 212 for 20 December 2004 detail subscribe now setting on that a currency value and food act will multiply various maths power of to power in delhi e and representation of currency converter app yes so Which will be like and share software 3100 2100 plus one in the next two plus 303 president check video like share and subscribe pani over fun time wa funnnnn multiply like this is the way to 4 inch Plus And Use This Channel Subscribe To That Bigg Boss Plus One Which Will Also Give The Length Of In The Representation Of Nuvvu Divided In To IDBI Stand Divided Way Of Best Wishes 2ND Year Simple Method Of Pure Withdrawal Login That Can We Further Optimizing So Let's See How They Can Do This Everytime They Divide Of 120 Freelance 1051 0570 subscribe to Saw Her Life After She Will Give One Number Of Power To Do The Power Of With Multiply Increase Quid Dip Number Of Viruses Power To Have Checked Device Powerful Sudhir and middle this check the power of to my channel I will have to the number one to the power of wave live video 100 4913 vibration of three do the fifth wise and of this 200 x b device and with x minus one 21000 free live Web Media 0 Number Four Is The Power Of Flexed One Is Number Three Years In The Native 108 Dual Give 1080 subscribe The Channel subscribe to subscribe our Channel 90 Robert Rafiyasha Bhosle Defined S Model Uvve 9790 subscribe The Amazing Thing In Your Problem For Tracking Start From Plus Thursday Ko Ki And Wise End With High Minus One Is Power Of To All Sorts Of Evil Resident Evil Know What Will Oo Vice Is Equal To Fail Slang For Example Appointed Committee 10 2012 90 And Vivid Loop Do Subscribe Nau Ki I Is To - According to Do Lines Will Welcome Ki I Is To - According to Do Lines Will Welcome Ki I Is To - According to Do Lines Will Welcome to Begusarai to Electrification of First Wave Subscribe 107 and 151 Similarly in Three Languages ​​2000 Which is the Widely Considered to Three Languages ​​2000 Which is the Widely Considered to Three Languages ​​2000 Which is the Widely Considered to Convert into Life Including All Everything Aaj Tak Bhi Mode of This Whole Vriddhi Modified Sunna Vansh Thursday Ko Yes Intent After Sun Celebs Caught And Will Take You All Subscribe 214 345 Number 12A 220 Marketing Correct Answer Know When Time Side Of Dissolution Accept What Will Be The Time Complexity Of Reservations At That Time Adjust Five Operations Subscribe And Then They Reduce And Sorry For The Time Complexity of a key and space complexities of one feel it solution for the like button and drive way are very important problem thanks for watching
Concatenation of Consecutive Binary Numbers
count-all-possible-routes
Given an integer `n`, return _the **decimal value** of the binary string formed by concatenating the binary representations of_ `1` _to_ `n` _in order, **modulo**_ `109 + 7`. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation: ** "1 " in binary corresponds to the decimal value 1. **Example 2:** **Input:** n = 3 **Output:** 27 **Explanation:** In binary, 1, 2, and 3 corresponds to "1 ", "10 ", and "11 ". After concatenating them, we have "11011 ", which corresponds to the decimal value 27. **Example 3:** **Input:** n = 12 **Output:** 505379714 **Explanation**: The concatenation results in "1101110010111011110001001101010111100 ". The decimal value of that is 118505380540. After modulo 109 + 7, the result is 505379714. **Constraints:** * `1 <= n <= 105`
Use dynamic programming to solve this problem with each state defined by the city index and fuel left. Since the array contains distinct integers fuel will always be spent in each move and so there can be no cycles.
Array,Dynamic Programming,Memoization
Hard
null
989
The values ​​are, if I The values ​​are, if I The values ​​are, if I write them in the form of interior, it is okay and if I add them with k, then our result will be returned to us in the form of vector, okay, so I will not be a little clear here, I will give you an example. I understand that here the example number is given to us, what is the value of the name here, what is the value of our vector, what is its value, I have said 1 2 00, okay 34, so if I do, how much will be the value, it will be 1034 and that if in the form, it means representative. How many values ​​should I do, then we can give an example, okay, so a basic approach, we will write it later, okay, this has already been done in ours, but what does our basic approach say that if I write this in the form of India, here it means one. Let me try again and make it an interior, it is okay and with that, our net means my net is waiting here, it is okay if I add a key in front of it, which is my net, what do I have to do, it is okay to represent it in the form of vector. What else should I do after that, I should modify the value here and take one value each time, okay, after that keep doing app end inside it, okay and make the urgent like this, so first of all, what is our problem, this problem can happen. What can happen if we convert it into interior form? What is the number of elements inside it? We will do 10 to the power of four. What can we do simply by adding two walls to it? I also showed you yesterday. That is, how do we add desi, okay that means how do we do normal addition and how do we do binary addition, so here we will put simple how we have to do addition, we have to do basic addition, how do we do addition, we have to do addition in decimal form, okay. So if I look here, it is 215, okay, so where do I have to add this value, this is the value, I basically have to add it inside this, okay, so what am I doing, I have added this total values ​​in the last. I have added this total values ​​in the last. I have added this total values ​​in the last. Okay, so midnight valid, look like this, if I add 8060, then why not this 8 11 Okay, now this is basically what is my value, this is my net value which came here, okay, now what can I do here. Resident here to see how much net value will come after addition of these values ​​because after addition of these values ​​because after addition of these values ​​because I had attended, I have to retain it. Okay, so if I look carefully here, then how will I get the value that has to be stored here, its model here. I should do it with 10 because we are editing the form of the edition, right, that means we are editing the interior, so if I do the mode of 10, how will it come out, then I liked it is okay, watch tomorrow's video, it will become more clear. There is nothing much here that 811 which was ours and if I divide this by 10 then how much carrier will be 81. Okay, so this is how much our net will come, meaning whatever is new will come, why first for the next value because we know the addition here. Let's say it will be 81, okay now I went to the ATM, 81 means for N-2 value, this is the value on the index, for means for N-2 value, this is the value on the index, for whom will be the next value, okay, then how much is it to forward 81, so how is the value here? How will we get the value by storing it and what does it mean next that we have to carry it inside the next element or the new one that will come out, how will we get the divide for the next element. Okay, so if I look here, how many times the value is right here? There was a van here earlier also and what will be the value of K 81. So if I add both then the net is only you. Now here, how will I calculate the value fee, its model stunt is 2. I have written it here, now how much will this carrier K do for forward 82. How much does 10/10 become 8 then how much should it forward 82. How much does 10/10 become 8 then how much should it forward? How much is our value module stand till now? What will be the value of zero and K? Because if I do 10/10 then how many times will it go once. do 10/10 then how many times will it go once. do 10/10 then how many times will it go once. No matter what is the value of K. Okay, so we have done the total driver as much as our number off value is okay within this factor but what is the value of our k non equasha is zero means we have some carry forward okay means we still have some value left which we Next we have to add, okay so if my value is &gt; 0, okay till when I &gt; 0, okay till when I &gt; 0, okay till when I can travel all the values ​​inside my vector, okay that can travel all the values ​​inside my vector, okay that can travel all the values ​​inside my vector, okay that means I come to the index number zero and after that my k value is non-zero. after that my k value is non-zero. after that my k value is non-zero. What does it mean, there is some value left ahead which I will have to add, okay, what will I do to you, from now on, I will apply the same process until the value of my A is zero, let's take the mode, stunt and adopt it here, keep starting, okay. And then forward K divide by time like I am doing till now. Like in this case, what was the value of our K? Okay, so this is the value of K, so here I am till now where is my first. Even I have added the WAN and how much will I carry forward? This means that the WAN module is standing. Look carefully, my answer is 1021. How much is the answer here? Unless the value of 1021 is zero. Okay, and I am creating each value, adding the value of index to both, okay, the value store is the nickel which I showed you how VX comes out, I will do the modulation of the stem by stunting the model, it will be the value of the particular point and how much forward will be the carry. Will I do it or what will I get on net, how much will I get for the next value, that is, our value which was na+, by the is, our value which was na+, by the is, our value which was na+, by the time we have done the entire journey, it will be zero, after that, what will happen if our video goes ahead, that is, we will have to insert some value. I have to do the same here, as long as the value of t is greater than zero, then whatever the name insert means, what value will we add at the beginning of our insert function, how much will we add and how much will we carry forward after that so that we do not return fundamentally modified. Okay, here I have modified the same vector and returned it. I think the question has been cleared. Look, by doing it, we are off, so basically it will be that we are traveling, okay and the driver is doing it, and what is the problem if Here, if ken &gt; 0 means if some of ours is Here, if ken &gt; 0 means if some of ours is Here, if ken &gt; 0 means if some of ours is left, then when will it be completed? What to do every time, that is, we are decreasing the video by 10, that is, we are dividing, so this is basically, are people off, are they okay, so these two Out of these, the one whose value will be bigger will be the maximum value, that is our answer. Okay, so what will be the maximum of space. Basically, what are we doing with the same, here we are adding the key of the wash, what will we do in it, the key value. If it increases, then how much will be the value added? How much will be the value of the lock? I show everything in full like this video, thank you.
Add to Array-Form of Integer
largest-component-size-by-common-factor
The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. **Example 1:** **Input:** num = \[1,2,0,0\], k = 34 **Output:** \[1,2,3,4\] **Explanation:** 1200 + 34 = 1234 **Example 2:** **Input:** num = \[2,7,4\], k = 181 **Output:** \[4,5,5\] **Explanation:** 274 + 181 = 455 **Example 3:** **Input:** num = \[2,1,5\], k = 806 **Output:** \[1,0,2,1\] **Explanation:** 215 + 806 = 1021 **Constraints:** * `1 <= num.length <= 104` * `0 <= num[i] <= 9` * `num` does not contain any leading zeros except for the zero itself. * `1 <= k <= 104`
null
Array,Math,Union Find
Hard
2276
76
so uh let's read the problem statement so we are given two strings as NT of length M and N respectively so we have to return the minimum window substring of s such that every character in t including duplicates also is included in the window if there is no each such substring we have to return the empty string so a such thing basically we know that it is a contiguous sequence of characters within the string quantities means that are coming one after another for example here just for example if we have ba so bar continues they are coming just one after another but B and C are not continuous right so this is what called as a substrate so uh in the first test case so you can see so uh characters of TR a b and c so we want to we have to uh search that much window a minimum window which should contain the characters ABC right so you can see if we go from left to right so you can see we will find B A and C in this much window and it is the minimum window so that's why there is a B A and C of answer so the minimum Windows of sync B A and C includes a b and c from string t so we want to find a in the string s so a is present the entire string s is the minimum window right so for example as given is a and t given is a and a so we have to find two A's in the string s so uh there is only one a present in s so that's why we are returning an empty string if that much window is not present in our string s uh what if T is not present in s that's why we are returning an empty string so I hope problem is clear so you can post the video and think of by yourself uh which concept we are going to use right please post the video so I hope you have tried so it's a standard problem of sliding window algorithm right we are going to use sliding window in sliding window what we do is we take two pointers you can see left and right pointers right so with the help of that like our right pointer will keep expanding and our left pointer will keep contacting we will see by diagram don't worry so at the time when we get our minimum window then we'll return so our only condition should be all the characters of T should be present in that much window right so we have to return that much window from s so let's see how we are going to use sliding window concept so let's see so uh let me write the problem here what our problem is so our question is basically we have to uh return the minimum window right from string as given from string s which has all the characters which has all characters of string T right so uh let's take any another example so let's say the S is a b a c b a b any there is any string as given and her T given is let's say ABC so we have to find a that much string that much window in our string as that contains a b and c so let's see so we are starting from here so we are just seeing manually we are not applying sliding window here so we'll apply later so a found now B found so we are remained with C so again a found so we found C also so this much window can be our answer can be a answer but we have to find the minimum window so let's see any another answer so let's say our pointer is here let's say this is right pointer this is left pointer so let's say about both the pointers have found that much window which window a b AAC this can be our answer because it contains ABC all the letters of t so on all the letters of t are just a b c so we have found ABC in this so we have found a b AAC so in this you can see a is present B is present is C is present right so this can be of also let's try to find another answer so we have a b a c let me write it again so we have to find such window in this string s such that a b and c is Translating that much window so you can see uh a c b this can be a one so instead of this also because its length is prime its length is only 3 and all that all the characters are present ABC we don't have to worry about a pattern here if a b is coming before c then it is not a compulsory here that uh pattern should also be same so we have to just found the tractors in that much window so this will be our answer ACB because in this all the characters are present so but we are going to do is so we'll take two pointers left and right as we take in our sliding window algorithm it's a standard sliding window algorithm problem you can say right so initially both are pointing into our first element of the string so our string moves so it was uh a b a c and b a b so in Italy our both pointers are at post element post factor left and right pointers so our right pointer is going to expand in this way left pointer will also move in this way but what our left pointer do is it contracts power window right pointer is expanding the window right so we use the right pointer to expand our window how much will expand until we get our desirable window so let's say ABC channel so we are expanding our right pointer right a left is initially at a we are expanding so right came here we have found the B okay so we have found a already because both the pointers are pointing to a so we are only left to be the C right so we'll again expand right to enter will X again expand right pointer how much will expand until we found all the characters so here we found C so we have found a also B also C also will stop here and uh we can return this much window which one a b a c but we need a minimum window size we need minimum window which contain all the characters so we can again so we'll save this also for further but uh we'll again try to contract the window contract means will again be uh try to uh decrease the window size by moving left to the right side okay so if we ignore this a and we move left here so you can see this can be our another answer b a c right so why because it is all it is also containing both the uh three characters which are a b and c so its size is four so we have reduced from five to four so this is better so we can expand right pointer more so okay right came here right and uh okay uh our left goes at this B so you can stop here why we are stopping because we found all the characters here also which was ACB we have found the minimum window you can see so this is containing all the characters of the string P right this window is also containing all the characters so we'll return this one because it says right its size is three so three windows so this will be our required answer in this case right so I hope intuition and algorithm is clear so let's jump to the code so here is our code so I have taken a map unordered map to show the frequencies because why we are taking because uh we have to return the minimum window substring of s such that every character in t including duplicates also right so we have to keep track of or duplicates also in t so let's say is right so first we have stored the frequency of each character in the string T right so we have found the size and stored in the variable unique so I have taken another variable let's say unique till now so I have taken two pointers left and right and I see so to update our left pointer if we are uh like whenever we are Contracting right so because we are founding multiple windows here so from that we need minimum window tomorrow so we have taken another variable in a and initialize it with int Max because we need something minimum is so now we are running low so while R is less than s dot run right so we have stored the frequency so when we have found that much string in s which has a frequency of character equal to that in string T what it means that means we have found that much window means all the factors in that are present which are in t right so we have saved that much window right so uh while left is less than or equal to right so and unique till now is equal to unique means uh this thing uh in T is a subset of that string means uh we have found that one string so now we'll try shortening we'll keep we'll move our left pointer and expand our right point also but how much is a b and c right so that's why we are trying to shortening the string so if uh first of all this condition should be true if right if minus left plus one is less than size so we'll update our left pointer and size also right and will decrease the frequency means that's why only we'll move over a left pointer because we are ignoring because we are starting ignoring the characters from left to right that only then we are going to move the left pointer frequency practice foreign will get longer so I will paste this code in the comment box so you can try running you will easily get on any example right so and that's it for this video If you still haven't out you can ask in the comment box and time complexity we are using this much M plus n because we are traversing both the swings and we are using space Also so that's it for this video you can connect with me my LinkedIn and Twitter handles are given in the description box so uh stay tuned for more videos
Minimum Window Substring
minimum-window-substring
Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`. The testcases will be generated such that the answer is **unique**. **Example 1:** **Input:** s = "ADOBECODEBANC ", t = "ABC " **Output:** "BANC " **Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t. **Example 2:** **Input:** s = "a ", t = "a " **Output:** "a " **Explanation:** The entire string s is the minimum window. **Example 3:** **Input:** s = "a ", t = "aa " **Output:** " " **Explanation:** Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string. **Constraints:** * `m == s.length` * `n == t.length` * `1 <= m, n <= 105` * `s` and `t` consist of uppercase and lowercase English letters. **Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
Hash Table,String,Sliding Window
Hard
30,209,239,567,632,727
232
hey everybody this is Larry this is day 16 of the legal daily challenge hit the like button hit the Subscribe button join me on Discord let me apparently I've done this week I don't know if my uh Firefox or whatever is just having a good memory but yeah today's problem is Implement cues using Stacks 232 easy prom hit the like button hit the Subscribe button join me on Discord let me know what you think about today's pop so this is actually a um I probably talked about this before and I've done this problem a few times oh only once I lied actually so maybe I haven't talked about this before um I mean I know how to do this so that's what I saw it was a little spoiler blue but a little bit of a minor story time is that um I never forget this problem even though now is it easy apparently but it was uh an interview question for me really early in my career this is what year is this 2022 almost literally 20 years ago so uh and I honestly did mess this up because back then there's no studying and even though I or like this problem at the time was legitimately new to me right so and uh and even though I did do some competitive Programming type things even though they wouldn't call that back then um I think it was just something that um you know the standards were a little bit different back then in terms of a little bit less algo at least in my region a little bit less alcohol a little bit less data structure and a little bit more just like hardcore implementation the type things in my region anyway for competitive so that why I uh I don't know I mean I did obviously figure out this one and have a very strong um memory say of this one because of that reason because um because this was a very sad thing to me because I did get this one wrong and I think oh I didn't um I got yeah I just didn't get this one in a really good time even though now is a user apparently uh and this is a long time ago and that journey is a long time so you know you do get better you do make me uh you do make mistakes and you do learn from your mistakes and it's something that uh you know I'm just kind of every time I see this farmers or whatever I'm always like a I mean I would say though um even at that time I knew that you know I just didn't know how to do it I think at the time I was struggling because I was still new with this idea of amortized analysis and we'll get to that part a little bit but basically it's just the idea of amortized analysis and I wasn't quite I mean I had some framework mentally but I didn't I wasn't as practice and rehearse as I am now with respect to amortized analysis and the other part of that though you I mean even then I knew that um because the question was more open-ended when I got asked in an open-ended when I got asked in an open-ended when I got asked in an interview um which was like you know it was basically like if you're given to stat uh if you're giving only Stacks can you implement a queue right um so it wasn't like a you know a foregone at least at that time conclusion that you know you can enable you are able to do it I mean of course if you're new to literature you know the literature but it wasn't like oh you know we know that you can well like that's not how the question was asked to me anyway um and that said I was trying to be like smart I was like oh I took my theory of computational uh conversation class and you know and if you remember that class if you're in that class or if you took that class um about like you know it's just a class about complexity Theory and uh analysis of complexity and stuff like that but one of the things that it talked about was you know this idea of a turing machine or not that turing machine is it no yeah a towing machine right um so I sometimes I get confused or I mix up Turing machines and ran Newman machines and uh and of course as you know uh um I'm doing these live so if I'm a little bit in that good here if there's a bit of inaccuracy my apologies but these are just like Story Time more than anything and of course you can skip forward but maybe I should have said to skip before I put a little bit earlier but if you remember from your theory of complexity if you remember your towing machine then you know that having two stacks is uh turning complete is one stack it's not two stack it is right because now um uh what you might call it because now um having two tapes uh you can um you know there's a turing machine and that was the other thing that I was trying to think about oh yeah because and you know and you get into this idea about tapes and languages and stuff like that because with one stack it turns out that you can only recognize uh record is it no what's this ah man I forgot I forget the name of these things but you can only do uh okay never mind may I can't remember the name of all the vocabulary it's been a long time uh so apologies for that but yeah but basically you know um so I knew that using two stacks would be sufficient but it took me and I was and we have two stacks it's kind of obvious how you implemented and I did get I think maybe I lied a little bit by saying that I got the wrong result but no I mean I got the answer at the end but it was wasn't very smooth because I was trying to figure out like is it okay like I said I struggled a lot of amortized analysis and judging by my Discord um and just conversations um it's something that is not unique to me um and even you know this is of course when I was more of a beginner but you know so um but even then I was you know a little bit more advanced on the beginner so it is very easy to get um make a mistake on the amortized analysis or just like really wrapping your head around it but yeah so we'll go over it now and yeah that's just have two stacks that I should say have a left stack and a right stack right and the way that I think about these is that you can um and I didn't have this visual visualization when I was coming from scratch is that you could think about it as uh I'm trying to think of there's a way I can draw this but basically you can think about this once you know instead of two stacks like this left and right um you could kind of turn them away from each other maybe something like this so that your left stack you know and then if you visualize it that way then it becomes a cue right maybe I could join here in ASCII art because I'm okay fine let me just put out the paint real quick I'm just a little bit lazier today maybe but uh my computer is a little bit messed up so give me a second question foreign put it on the screen also I just got my uh and then another I got the flu shot and I got the right uh the other uh the new covert vaccine so my left um my left shoulder is kind of really sore right now but anyway my idea my um thing about this visualization um which I think is I know I like it I think it's cute you could you know it's just that you can think about the stack as two stacks going from left to right something like this so that as um you know as uh as long as you kind of make sure you keep track of some invariants uh then it should be okay for example if you put like a b c right and then now you want to put on the other side then it would go from you know C and then now and of course these are no long here but you can kind of see it like visually as a cue as you kind of you know do it this way and we've yet and you know I talk a lot about visualization on this channel because I think that once you have the right visualization and ideas the implementation is just following through right I mean sometimes you have uh silly off by ones as I uh often do but the idea is the core part of allowing us to kind of go on um the invariant here though of course is that one of the one uh one of the yeah one of the stacks you know uh we have to be careful about it okay so anyway so push we always push to the left right pop uh I mean you can and as long as you keep track of these invariants it doesn't mean like there may be some variation in how you want to do it but it'll be okay but yeah so if length of self that right is uh greater than is if it's equal to zero then um then Wow's length of self that's left is greater than zero I'm self dot write dot a pen self dot left dot pop foreign and then now we um return self.white.pop right uh Peak so empty let's do empty first basically return length of self dot left plus length of self that way is equal to zero um and Peak is I mean and I'm a little bit lazy today but it probably we could have done this with a decorator or something like this um I don't want to go over I know that this is like pi-fi magic and it's this is like pi-fi magic and it's this is like pi-fi magic and it's something that I definitely recommend um uh like once you're more familiar with python you would do it but here you know we'll just do this for now and then I want to see whether what if we Peak on an empty thing okay so okay um and of course you can maybe just do like a quick uh maybe we adjust things as a as um as a decorator afterwards and you could do stuff that made the adjust and yeah and let's give a quick submit because I'm too lazy to check and it looks good um yeah so yeah I mean let's do this in a naive um and uh analyze right analysis so this is going to be our one uh this is going to be o of n because you know and most there'll be an element right um and as a result this is also o of N and this is O of N and this is well this is of one so then the question is okay well in that case isn't this n square and this is where you know uh the amortized and I think that's one of the thing um yeah well I mean I already did this and this is already that but basically the idea is that okay what's another way of thinking about it right well we think about it in terms of um we think about it right now in terms of per function but what we could do and in this case should do for a more tighter bound is do this amortization analysis and in this case um yeah in this case instead of thinking about in functions you should think about it in terms of elements right well and what I mean by that means that for every element that you put you push and you pop and you I don't know Peak I guess doesn't recap but uh the question is okay what happens through the life cycle of every element right and what I mean by that is that okay so you know I'm uh I'm a little element going through this away uh or throwing this uh data structure just abstract data structure and it first it gets appended to self.lev right and it only happens once self.lev right and it only happens once self.lev right and it only happens once and this is an old one operation and then maybe at some point it gets you know moved from the left to the right so that means that also is two or one operations the purpose of one a pen isol of one and then at the way and it gets popped from the right uh maybe get to pick that at some point but it can only so if you think about the state machine if you will maybe that's another better way of thinking about it or just different way of thinking about it if you think about the state machine of where it is um you know where the element is at every given time well we can only go through one of those stages every time once so it's going to be all of ones uh o of one and in total because the N element and each element will only do over one operation on the system altogether this is of an amortized in total or one per operation um that's pretty much all I have for today uh I am very hungry don't know why so I'm gonna go eat uh no bonus question today uh yeah that's why I have to so stay good stay healthy to good mental health I'll see y'all later and take care bye
Implement Queue using Stacks
implement-queue-using-stacks
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`). Implement the `MyQueue` class: * `void push(int x)` Pushes element x to the back of the queue. * `int pop()` Removes the element from the front of the queue and returns it. * `int peek()` Returns the element at the front of the queue. * `boolean empty()` Returns `true` if the queue is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid. * Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. **Example 1:** **Input** \[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 1, 1, false\] **Explanation** MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: \[1\] myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is \[2\] myQueue.empty(); // return false **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`. * All the calls to `pop` and `peek` are valid. **Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
null
Stack,Design,Queue
Easy
225
438
Hello Guys Welcome Back To Decades And This Video Will See The Find All And Grass In Spring Problem Specific Click Code Se Yadav Challenged So Let's Not Look At The Problem Statement Before Looking And The Problem Latest June 2012 From Thursday Can They Arrange Is The Most Frequent Flyer Important and subscribe the Channel Character Channel Subscribe Enough to Do the subscribe and Share and subscribe the Channel Half Exactly Equal in the Distinct Superintendents of 200 Subscribe Only 2000 Channel Subscribe Now to the Problem Subscribe The Problem Only Subscribe Now to The subscribe like and subscribe who is the first window sagittarius can c d a b c d correct order and seervi and location of this is the answer will contest all the best location subscribe and subscribe the Video then subscribe to The Amazing Subscribe Well Madam Gastritis Sliding Window Approach So Let's Know Price Leading Man To Approach To This Problem IF Taken Example String And Examples Paytm Buffets 100 Subscribe Now To Record All The Positions Of The Most Important Point To 9 To The Channel And Subscribe the Channel subscribe Video subscribe this Video plz Similarly they Swift Window for the First Winters Dushman ABC No Will Devalue Her Worth Basically Sliding Window Frequency of Every Character of Frequency and Frequency of Railways During Computer Labs Servi Subscribe Position Which Will B C D subscribe The Video then subscribe to the Page Thank You Can Directly John Sauda Validated by One Value and mid-november by One Value and mid-november by One Value and mid-november Notice to them for Starting Index Nodes Patient Scenes with Remote Idi Aghyaksha No Entry Movie Should Remind Value 100 Grams Setting subscribe Dance on Winning Decrement Divine One and All Decisions Including Overseas Validated by the Way 100 Grams 150 Subscribe Now to Subscribe My Next subscribe and subscribe the Channel Please subscribe and subscribe the Channel press The Gas Containing Decagram Off But Know What Is The Time Complexity of this Algorithm The Time Complexity Will Be Veeravansh Show Length Office End Points Character Wear Earrings Pay Order of the Year Subscribe 602 Likes Every Individual and Collective Efforts into subscribe and subscribe the Channel and subscribe Weston TV Actor No The Left and Right and Fix to 20 Exactly the Frequency of Every Character for the First Video subscribe The Wind Only Know of Calculating Window Will Lead Character will also subscribe this Video Please subscribe and subscirbe Solution in different languages ​​please like in comment section languages ​​please like in comment section languages ​​please like in comment section Share and Subscribe to the channel
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